forked from Deen-Bridge/dnb-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrefund.test.js
More file actions
384 lines (326 loc) · 12.6 KB
/
Copy pathrefund.test.js
File metadata and controls
384 lines (326 loc) · 12.6 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
// test/refund.test.js
import "dotenv/config";
import dns from "node:dns";
dns.setServers(["8.8.8.8", "8.8.4.4"]);
import { jest } from "@jest/globals";
import express from "express";
import request from "supertest";
import jwt from "jsonwebtoken";
import mongoose from "mongoose";
import * as StellarSdk from "@stellar/stellar-sdk";
import User from "../src/models/User.js";
import Book from "../src/models/Book.js";
import Course from "../src/models/Course.js";
import Transaction from "../src/models/Transaction.js";
import Refund from "../src/models/Refund.js";
import paymentRoutes from "../src/routes/stellar/paymentRoutes.js";
import { server } from "../src/services/stellar/stellarService.js";
jest.setTimeout(60000);
const app = express();
app.use(express.json());
app.use("/api/stellar/payment", paymentRoutes);
const JWT_SECRET = process.env.JWT_SECRET || "deenbridge-temp-secret-key-2024";
const generateToken = (userId, role = "student") => {
return jwt.sign({ userId, role }, JWT_SECRET, { expiresIn: "1h" });
};
describe("Non-Custodial Refund & Dispute Flow (#62)", () => {
let buyer, educator, otherUser, adminUser;
let buyerWallet;
let buyerToken, educatorToken, otherToken, adminToken;
let confirmedTx;
let course;
beforeAll(async () => {
const uri = process.env.MONGO_URI || "mongodb://127.0.0.1:27017/dnb-backend-test";
if (mongoose.connection.readyState === 0) {
await mongoose.connect(uri);
}
// Mock Horizon Server
jest.spyOn(server, "loadAccount").mockImplementation(async (publicKey) => {
const acc = new StellarSdk.Account(publicKey, "1000");
acc.balances = [{ asset_type: "native", balance: "100" }];
return acc;
});
jest.spyOn(server, "submitTransaction").mockImplementation(async () => ({
hash: "mock_reverse_tx_hash_12345",
ledger: 998877,
successful: true,
}));
jest.spyOn(server, "transactions").mockImplementation(() => ({
transaction: () => ({
call: async () => ({
successful: true,
ledger: 998877,
created_at: new Date().toISOString(),
}),
}),
}));
jest.spyOn(server, "operations").mockImplementation(() => ({
forTransaction: () => ({
call: async () => ({
records: [
{
type: "payment",
to: buyerWallet,
amount: "50",
asset_code: "USDC",
asset_issuer: "GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5",
},
],
}),
}),
}));
});
afterAll(async () => {
jest.restoreAllMocks();
if (mongoose.connection.readyState !== 0) {
await mongoose.disconnect();
}
});
beforeEach(async () => {
await User.deleteMany({});
await Course.deleteMany({});
await Book.deleteMany({});
await Transaction.deleteMany({});
await Refund.deleteMany({});
buyerWallet = StellarSdk.Keypair.random().publicKey();
const educatorWallet = StellarSdk.Keypair.random().publicKey();
const otherWallet = StellarSdk.Keypair.random().publicKey();
// Create test users
buyer = await User.create({
name: "Buyer Student",
email: "buyer@example.com",
password: "Qx7#vLmp92Zt",
role: "student",
stellarWallet: { publicKey: buyerWallet },
purchasedCourses: [],
});
educator = await User.create({
name: "Educator Tutor",
email: "tutor@example.com",
password: "Qx7#vLmp92Zt",
role: "tutor",
stellarWallet: { publicKey: educatorWallet },
});
otherUser = await User.create({
name: "Other User",
email: "other@example.com",
password: "Qx7#vLmp92Zt",
role: "student",
stellarWallet: { publicKey: otherWallet },
});
adminUser = await User.create({
name: "Admin Arbiter",
email: "admin@example.com",
password: "Qx7#vLmp92Zt",
role: "admin",
});
buyerToken = generateToken(buyer._id, "student");
educatorToken = generateToken(educator._id, "tutor");
otherToken = generateToken(otherUser._id, "student");
adminToken = generateToken(adminUser._id, "admin");
// Create a purchased course and enroll buyer
course = await Course.create({
title: "Advanced Fiqh Course",
description: "Comprehensive Fiqh study",
category: "Fiqh",
price: 50,
createdBy: educator._id,
enrolledUsers: [buyer._id],
});
buyer.purchasedCourses = [{ courseId: course._id, purchaseDate: new Date() }];
await buyer.save();
// Create confirmed purchase transaction
confirmedTx = await Transaction.create({
stellarTxHash: "mock_original_tx_hash_99999",
buyer: buyer._id,
buyerWallet: buyer.stellarWallet.publicKey,
creator: educator._id,
creatorWallet: educator.stellarWallet.publicKey,
itemType: "course",
itemId: course._id,
itemTypeModel: "Course",
itemTitle: course.title,
amount: "50",
currency: "USDC",
network: "testnet",
status: "confirmed",
confirmedAt: new Date(),
});
});
describe("1. Refund Request (POST /transactions/:id/refund-request)", () => {
it("should allow original buyer to request refund within window", async () => {
const res = await request(app)
.post(`/api/stellar/payment/transactions/${confirmedTx._id}/refund-request`)
.set("Authorization", `Bearer ${buyerToken}`)
.send({ reason: "Accidental purchase" });
expect(res.status).toBe(201);
expect(res.body.success).toBe(true);
expect(res.body.refund.status).toBe("requested");
expect(res.body.refund.reason).toBe("Accidental purchase");
});
it("should reject refund request from non-buyer (403)", async () => {
const res = await request(app)
.post(`/api/stellar/payment/transactions/${confirmedTx._id}/refund-request`)
.set("Authorization", `Bearer ${otherToken}`)
.send({ reason: "Unwanted item" });
expect(res.status).toBe(403);
expect(res.body.success).toBe(false);
});
it("should enforce idempotency (prevent duplicate active refund requests)", async () => {
// First request
await request(app)
.post(`/api/stellar/payment/transactions/${confirmedTx._id}/refund-request`)
.set("Authorization", `Bearer ${buyerToken}`)
.send({ reason: "First request" });
// Second request
const res = await request(app)
.post(`/api/stellar/payment/transactions/${confirmedTx._id}/refund-request`)
.set("Authorization", `Bearer ${buyerToken}`)
.send({ reason: "Second request" });
expect(res.status).toBe(400);
expect(res.body.success).toBe(false);
expect(res.body.message).toMatch(/already exists/i);
});
it("should reject refund request for non-confirmed transaction", async () => {
const pendingTx = await Transaction.create({
stellarTxHash: "mock_pending_hash",
buyer: buyer._id,
buyerWallet: buyer.stellarWallet.publicKey,
creator: educator._id,
creatorWallet: educator.stellarWallet.publicKey,
itemType: "course",
itemId: course._id,
itemTypeModel: "Course",
itemTitle: course.title,
amount: "50",
network: "testnet",
status: "pending",
});
const res = await request(app)
.post(`/api/stellar/payment/transactions/${pendingTx._id}/refund-request`)
.set("Authorization", `Bearer ${buyerToken}`)
.send({ reason: "Cancel pending" });
expect(res.status).toBe(400);
expect(res.body.success).toBe(false);
});
});
describe("2. Reverse Payment XDR Build & Submission", () => {
let refund;
beforeEach(async () => {
refund = await Refund.create({
originalTransaction: confirmedTx._id,
buyer: buyer._id,
educator: educator._id,
itemType: "course",
itemId: course._id,
amount: "50",
currency: "USDC",
reason: "Course not relevant",
status: "requested",
});
});
it("should allow educator to build unsigned reverse payment XDR", async () => {
const res = await request(app)
.post(`/api/stellar/payment/refunds/${refund._id}/build`)
.set("Authorization", `Bearer ${educatorToken}`)
.send();
expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
expect(res.body.unsignedXdr).toBeDefined();
expect(res.body.refund.status).toBe("approved");
});
it("should prevent non-educator from building reverse payment XDR (403)", async () => {
const res = await request(app)
.post(`/api/stellar/payment/refunds/${refund._id}/build`)
.set("Authorization", `Bearer ${buyerToken}`)
.send();
expect(res.status).toBe(403);
});
it("should submit signed XDR, verify Horizon, and revoke item access atomically", async () => {
// Step 1: Educator builds
const buildRes = await request(app)
.post(`/api/stellar/payment/refunds/${refund._id}/build`)
.set("Authorization", `Bearer ${educatorToken}`)
.send();
const unsignedXdr = buildRes.body.unsignedXdr;
// Step 2: Educator submits signed XDR
const res = await request(app)
.post(`/api/stellar/payment/refunds/${refund._id}/submit`)
.set("Authorization", `Bearer ${educatorToken}`)
.send({ signedXdr: unsignedXdr });
expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
expect(res.body.refund.status).toBe("confirmed");
// Verify access revocation on User and Course
const updatedBuyer = await User.findById(buyer._id);
const updatedCourse = await Course.findById(course._id);
const updatedTx = await Transaction.findById(confirmedTx._id);
expect(updatedBuyer.purchasedCourses.map((c) => c.courseId.toString())).not.toContain(course._id.toString());
expect(updatedCourse.enrolledUsers.map((u) => u.toString())).not.toContain(buyer._id.toString());
expect(updatedCourse.enrolledUsers.length).toBe(0);
expect(updatedTx.status).toBe("refunded");
});
it("should block submit if refund is not in approved state", async () => {
// Try submitting directly on 'requested' refund without building
const res = await request(app)
.post(`/api/stellar/payment/refunds/${refund._id}/submit`)
.set("Authorization", `Bearer ${educatorToken}`)
.send({ signedXdr: "AAAA...XDR..." });
expect(res.status).toBe(400);
expect(res.body.message).toMatch(/Must be 'approved' first/i);
});
});
describe("3. Dispute Escalation & Admin Arbitration", () => {
let refund;
beforeEach(async () => {
refund = await Refund.create({
originalTransaction: confirmedTx._id,
buyer: buyer._id,
educator: educator._id,
itemType: "course",
itemId: course._id,
amount: "50",
currency: "USDC",
reason: "Educator uncooperative",
status: "rejected",
});
});
it("should allow buyer to escalate rejected refund to disputed", async () => {
const res = await request(app)
.post(`/api/stellar/payment/refunds/${refund._id}/dispute`)
.set("Authorization", `Bearer ${buyerToken}`)
.send();
expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
expect(res.body.refund.status).toBe("disputed");
const updatedTx = await Transaction.findById(confirmedTx._id);
expect(updatedTx.status).toBe("disputed");
});
it("should allow admin/arbiter to record arbitration resolution", async () => {
// Escalate to disputed first
refund.status = "disputed";
await refund.save();
const res = await request(app)
.patch(`/api/stellar/payment/refunds/${refund._id}/arbitrate`)
.set("Authorization", `Bearer ${adminToken}`)
.send({
decision: "off_chain_resolved",
notes: "Mediated off-chain resolution with educator",
});
expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
expect(res.body.refund.status).toBe("resolved");
expect(res.body.refund.resolution.decision).toBe("off_chain_resolved");
expect(res.body.disclaimer).toMatch(/Non-custodial Limitation/i);
});
it("should reject arbitration attempt from non-admin user (403)", async () => {
refund.status = "disputed";
await refund.save();
const res = await request(app)
.patch(`/api/stellar/payment/refunds/${refund._id}/arbitrate`)
.set("Authorization", `Bearer ${buyerToken}`)
.send({ decision: "approved" });
expect(res.status).toBe(403);
});
});
});