forked from Deen-Bridge/dnb-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrefundController.js
More file actions
512 lines (450 loc) · 15.7 KB
/
Copy pathrefundController.js
File metadata and controls
512 lines (450 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
// controllers/stellar/refundController.js
import mongoose from "mongoose";
import User from "../../models/User.js";
import Book from "../../models/Book.js";
import Course from "../../models/Course.js";
import Transaction from "../../models/Transaction.js";
import Refund from "../../models/Refund.js";
import {
buildReversePaymentTransaction,
submitTransaction,
verifyPaymentOperations,
} from "../../services/stellar/stellarService.js";
import { isAssetSupported, getSupportedCodes } from "../../config/assets.js";
import logger from "../../config/logger.js";
const REFUND_WINDOW_DAYS = parseInt(process.env.REFUND_WINDOW_DAYS || "14", 10);
/**
* Buyer requests a refund
* POST /api/stellar/payment/transactions/:id/refund-request
*/
export const requestRefund = async (req, res) => {
try {
const { id: transactionId } = req.params;
const { reason } = req.body;
const buyerId = req.user._id;
if (!reason || typeof reason !== "string" || !reason.trim()) {
return res.status(400).json({
success: false,
message: "A valid refund reason is required",
});
}
const transaction = await Transaction.findById(transactionId);
if (!transaction) {
return res.status(404).json({
success: false,
message: "Transaction not found",
});
}
if (transaction.buyer.toString() !== buyerId.toString()) {
return res.status(403).json({
success: false,
message: "Forbidden: You are not the purchaser of this item",
});
}
if (transaction.status !== "confirmed") {
return res.status(400).json({
success: false,
message: `Cannot request refund for transaction in '${transaction.status}' status`,
});
}
const confirmedTime = new Date(
transaction.confirmedAt || transaction.updatedAt
).getTime();
const windowMs = REFUND_WINDOW_DAYS * 24 * 60 * 60 * 1000;
if (Date.now() - confirmedTime > windowMs) {
return res.status(400).json({
success: false,
message: `Refund window of ${REFUND_WINDOW_DAYS} days has expired for this transaction`,
});
}
const existingRefund = await Refund.findOne({
originalTransaction: transaction._id,
status: { $in: ["requested", "approved", "submitted", "confirmed", "disputed"] },
});
if (existingRefund) {
return res.status(400).json({
success: false,
message: "An active or completed refund request already exists for this transaction",
refundId: existingRefund._id,
});
}
const refund = await Refund.create({
originalTransaction: transaction._id,
buyer: transaction.buyer,
educator: transaction.creator,
itemType: transaction.itemType,
itemId: transaction.itemId,
amount: transaction.amount,
currency: transaction.currency || "USDC",
reason: reason.trim(),
status: "requested",
expiresAt: new Date(Date.now() + windowMs),
});
transaction.refund = refund._id;
await transaction.save();
logger.info(`Refund requested for transaction ${transaction._id} by buyer ${buyerId}`);
return res.status(201).json({
success: true,
message: "Refund request submitted successfully",
refund,
});
} catch (error) {
logger.error("Error requesting refund:", error);
return res.status(500).json({
success: false,
message: error.message || "Failed to request refund",
});
}
};
/**
* Educator approves refund & builds reverse payment XDR
* POST /api/stellar/payment/refunds/:refundId/build
*/
export const buildRefundXdr = async (req, res) => {
try {
const { refundId } = req.params;
const educatorId = req.user._id;
const refund = await Refund.findById(refundId).populate("originalTransaction");
if (!refund) {
return res.status(404).json({
success: false,
message: "Refund request not found",
});
}
if (refund.educator.toString() !== educatorId.toString()) {
return res.status(403).json({
success: false,
message: "Forbidden: Only the educator can approve this refund",
});
}
if (refund.status !== "requested") {
return res.status(400).json({
success: false,
message: `Cannot build reverse payment for refund in '${refund.status}' status`,
});
}
// Validate the refund's currency before resolving an asset from it, so
// an unsupported/unknown currency returns a clean 400 instead of a 500
// from buildReversePaymentTransaction's resolveAsset call.
const refundAssetCode = refund.currency || "USDC";
if (!isAssetSupported(refundAssetCode)) {
return res.status(400).json({
success: false,
message: `Refund currency ${refundAssetCode} is not supported. Supported: ${getSupportedCodes().join(", ")}`,
});
}
const buyer = await User.findById(refund.buyer);
const educator = await User.findById(refund.educator);
const buyerWallet = buyer?.stellarWallet?.publicKey;
const educatorWallet = educator?.stellarWallet?.publicKey;
if (!buyerWallet || !educatorWallet) {
return res.status(400).json({
success: false,
message: "Missing wallet information for buyer or educator",
});
}
const originalTxHash = refund.originalTransaction?.stellarTxHash || "";
// Build reverse payment transaction (educator -> buyer), in the same
// asset the original payment was made in, so an EURC/XLM purchase is
// refunded in EURC/XLM rather than always defaulting to USDC.
const result = await buildReversePaymentTransaction({
sourcePublicKey: educatorWallet,
destinationPublicKey: buyerWallet,
amount: refund.amount,
originalTxHash,
assetCode: refundAssetCode,
});
refund.status = "approved";
await refund.save();
logger.info(`Reverse payment XDR built for refund ${refund._id} by educator ${educatorId}`);
return res.status(200).json({
success: true,
message: "Unsigned reverse payment XDR built successfully",
refund,
unsignedXdr: result.xdr,
networkPassphrase: result.networkPassphrase,
});
} catch (error) {
logger.error("Error building refund XDR:", error);
return res.status(500).json({
success: false,
message: error.message || "Failed to build refund XDR",
});
}
};
/**
* Educator submits signed reverse payment XDR & triggers atomic revocation
* POST /api/stellar/payment/refunds/:refundId/submit
*/
export const submitRefund = async (req, res) => {
try {
const { refundId } = req.params;
const { signedXdr } = req.body;
const educatorId = req.user._id;
if (!signedXdr) {
return res.status(400).json({
success: false,
message: "signedXdr is required",
});
}
const refund = await Refund.findById(refundId);
if (!refund) {
return res.status(404).json({
success: false,
message: "Refund request not found",
});
}
if (refund.educator.toString() !== educatorId.toString()) {
return res.status(403).json({
success: false,
message: "Forbidden: Only the educator can submit this refund",
});
}
if (refund.status !== "approved") {
return res.status(400).json({
success: false,
message: `Cannot submit refund in '${refund.status}' status. Must be 'approved' first.`,
});
}
// Fetch the buyer once up front: we need their wallet as the expected
// destination for on-chain verification below, and we reuse the same
// buyer document for access revocation later instead of looking it up
// a second time.
const buyer = await User.findById(refund.buyer);
const buyerWallet = buyer?.stellarWallet?.publicKey;
if (!buyerWallet) {
refund.status = "failed";
await refund.save();
return res.status(400).json({
success: false,
message: "Missing buyer wallet information; cannot verify refund payment",
});
}
// Submit transaction to Stellar network
let submissionResult;
try {
submissionResult = await submitTransaction(signedXdr);
} catch (submitErr) {
refund.status = "failed";
await refund.save();
return res.status(400).json({
success: false,
message: `Stellar transaction failed: ${submitErr.message}`,
});
}
// On-Chain Truth Verification via Horizon: validate the actual reverse
// payment operation (destination, amount, and asset), not just that a
// successful transaction with this hash exists on Horizon.
const verification = await verifyPaymentOperations(
submissionResult.hash,
[{ destination: buyerWallet, amount: refund.amount }],
refund.currency || "USDC"
);
if (!verification.verified) {
refund.status = "failed";
await refund.save();
return res.status(400).json({
success: false,
message: `Reverse payment could not be verified on Horizon: ${verification.reason || "payment mismatch"}`,
});
}
// Access Revocation — sequential writes (no session/transaction required;
// the Stellar on-chain verification above is the source of truth)
try {
if (refund.itemType === "course") {
// Remove course from buyer's purchased list. purchasedCourses
// entries are subdocuments ({ courseId, purchaseDate }), so match
// on the courseId field rather than the subdocument itself.
if (buyer) {
buyer.purchasedCourses = (buyer.purchasedCourses || []).filter(
(entry) => entry.courseId?.toString() !== refund.itemId.toString()
);
await buyer.save();
}
const course = await Course.findById(refund.itemId);
if (course) {
course.enrolledUsers = (course.enrolledUsers || []).filter(
(uId) => uId.toString() !== refund.buyer.toString()
);
await course.save();
}
} else if (refund.itemType === "book") {
// Same subdocument shape as above: match on bookId, not the entry.
if (buyer) {
buyer.purchasedBooks = (buyer.purchasedBooks || []).filter(
(entry) => entry.bookId?.toString() !== refund.itemId.toString()
);
await buyer.save();
}
}
refund.status = "confirmed";
refund.refundTxHash = submissionResult.hash;
refund.refundLedger = submissionResult.ledger;
await refund.save();
await Transaction.findByIdAndUpdate(
refund.originalTransaction,
{ status: "refunded", refund: refund._id }
);
logger.info(`Refund confirmed and access revoked atomically for refund ${refund._id}`);
} catch (revokeErr) {
logger.error("Error during atomic access revocation:", revokeErr);
throw revokeErr;
}
return res.status(200).json({
success: true,
message: "Refund confirmed on-chain and item access revoked successfully",
refund,
txHash: submissionResult.hash,
});
} catch (error) {
logger.error("Error submitting refund:", error);
return res.status(500).json({
success: false,
message: error.message || "Failed to submit refund",
});
}
};
/**
* Educator rejects a refund request
* POST /api/stellar/payment/refunds/:refundId/reject
*/
export const rejectRefund = async (req, res) => {
try {
const { refundId } = req.params;
const { rejectionReason } = req.body;
const educatorId = req.user._id;
const refund = await Refund.findById(refundId);
if (!refund) {
return res.status(404).json({
success: false,
message: "Refund request not found",
});
}
if (refund.educator.toString() !== educatorId.toString()) {
return res.status(403).json({
success: false,
message: "Forbidden: Only the educator can reject this refund",
});
}
if (refund.status !== "requested") {
return res.status(400).json({
success: false,
message: `Cannot reject refund in '${refund.status}' status`,
});
}
refund.status = "rejected";
refund.rejectionReason = rejectionReason || "Refund request rejected by educator";
await refund.save();
logger.info(`Refund ${refund._id} rejected by educator ${educatorId}`);
return res.status(200).json({
success: true,
message: "Refund request rejected",
refund,
});
} catch (error) {
logger.error("Error rejecting refund:", error);
return res.status(500).json({
success: false,
message: error.message || "Failed to reject refund",
});
}
};
/**
* Buyer escalates refund to dispute
* POST /api/stellar/payment/refunds/:refundId/dispute
*/
export const escalateDispute = async (req, res) => {
try {
const { refundId } = req.params;
const buyerId = req.user._id;
const refund = await Refund.findById(refundId);
if (!refund) {
return res.status(404).json({
success: false,
message: "Refund request not found",
});
}
if (refund.buyer.toString() !== buyerId.toString()) {
return res.status(403).json({
success: false,
message: "Forbidden: Only the buyer can escalate this dispute",
});
}
if (!["requested", "rejected"].includes(refund.status)) {
return res.status(400).json({
success: false,
message: `Cannot escalate refund in '${refund.status}' status`,
});
}
refund.status = "disputed";
await refund.save();
await Transaction.findByIdAndUpdate(refund.originalTransaction, {
status: "disputed",
});
logger.info(`Refund ${refund._id} escalated to dispute by buyer ${buyerId}`);
return res.status(200).json({
success: true,
message: "Refund request escalated to dispute for admin review",
refund,
});
} catch (error) {
logger.error("Error escalating dispute:", error);
return res.status(500).json({
success: false,
message: error.message || "Failed to escalate dispute",
});
}
};
/**
* Admin / Arbiter resolves a dispute
* PATCH /api/stellar/payment/refunds/:refundId/arbitrate
*/
export const arbitrateDispute = async (req, res) => {
try {
const { refundId } = req.params;
const { decision, notes } = req.body;
const adminId = req.user._id;
if (!["approved", "rejected", "off_chain_resolved"].includes(decision)) {
return res.status(400).json({
success: false,
message: "Invalid decision. Must be 'approved', 'rejected', or 'off_chain_resolved'",
});
}
const refund = await Refund.findById(refundId);
if (!refund) {
return res.status(404).json({
success: false,
message: "Refund request not found",
});
}
if (refund.status !== "disputed") {
return res.status(400).json({
success: false,
message: `Cannot arbitrate refund in '${refund.status}' status. Must be 'disputed'`,
});
}
refund.resolution = {
decision,
notes: notes || "",
resolvedBy: adminId,
resolvedAt: new Date(),
};
refund.status = "resolved";
await refund.save();
logger.info(`Dispute for refund ${refund._id} arbitrated by admin ${adminId}`);
return res.status(200).json({
success: true,
message:
"Dispute resolution recorded successfully. Note: DeenBridge is a non-custodial platform; on-chain funds transfers require the creator's wallet signature.",
refund,
disclaimer:
"Non-custodial Limitation: The platform wallet does not hold buyer or creator funds and cannot unilaterally move Stellar assets on-chain without the educator's signed transaction.",
});
} catch (error) {
logger.error("Error arbitrating dispute:", error);
return res.status(500).json({
success: false,
message: error.message || "Failed to arbitrate dispute",
});
}
};