xytara 3.1.13 → 3.1.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/.env.example +38 -4
  2. package/BSV_TERANODE_PLATFORM_DISCONTINUITY_RUNBOOK.md +126 -126
  3. package/REAL_PAYMENT_SETUP.md +14 -7
  4. package/RELEASE_NOTES.md +9 -4
  5. package/fixtures/catalog.js +22 -0
  6. package/lib/a2a_rpc.js +287 -280
  7. package/lib/account_auth.js +585 -585
  8. package/lib/agent_identity.js +162 -162
  9. package/lib/asyncapi_contract.js +3 -3
  10. package/lib/bolt_adapter.js +187 -187
  11. package/lib/bolt_payment_front.js +224 -224
  12. package/lib/buyer_event_log.js +215 -0
  13. package/lib/buyer_safety_policy.js +132 -0
  14. package/lib/checkout_processor_adapter.js +217 -217
  15. package/lib/command_flow.js +911 -722
  16. package/lib/commerce_artifacts.js +591 -591
  17. package/lib/commerce_bridge.js +274 -274
  18. package/lib/commerce_cases.js +399 -399
  19. package/lib/commerce_client.js +7694 -7694
  20. package/lib/commerce_quotes.js +29 -0
  21. package/lib/commerce_runtime.js +322 -322
  22. package/lib/execution_dedupe.js +86 -86
  23. package/lib/external_credit_bridge.js +142 -142
  24. package/lib/http_transport.js +99 -81
  25. package/lib/l402_adapter.js +241 -241
  26. package/lib/l402_payment_front.js +265 -265
  27. package/lib/mpp_adapter.js +237 -237
  28. package/lib/openapi_contract.js +4 -0
  29. package/lib/payment_config.js +257 -253
  30. package/lib/payment_verification.js +357 -357
  31. package/lib/provider_payout_execution.js +155 -155
  32. package/lib/provider_registry.js +852 -842
  33. package/lib/rate_limiter.js +81 -81
  34. package/lib/runtime_state_store.js +495 -369
  35. package/lib/settlement_bsv_live.js +600 -600
  36. package/lib/settlement_bsv_teranode.js +117 -117
  37. package/lib/stripe_mpp_payment_front.js +258 -258
  38. package/lib/x402_facilitator.js +198 -191
  39. package/lib/x402_lane_contract.js +5 -3
  40. package/lib/x402_settlement_recovery.js +175 -0
  41. package/package.json +9 -3
  42. package/scripts/buyer_events_daily_report.js +79 -0
  43. package/scripts/state_backup_offsite.js +196 -0
  44. package/scripts/verify_a2a_rpc.js +131 -105
  45. package/scripts/verify_agent_identity.js +153 -153
  46. package/scripts/verify_all.js +1 -1
  47. package/scripts/verify_bolt_adapter.js +128 -128
  48. package/scripts/verify_buyer_event_log.js +123 -0
  49. package/scripts/verify_buyer_safety.js +141 -0
  50. package/scripts/verify_cdp_facilitator.js +110 -110
  51. package/scripts/verify_checkout_processor.js +109 -109
  52. package/scripts/verify_commerce_bridge.js +177 -177
  53. package/scripts/verify_execution_dedupe.js +189 -189
  54. package/scripts/verify_execution_surfacing.js +76 -76
  55. package/scripts/verify_final_activation.js +191 -191
  56. package/scripts/verify_l402_adapter.js +86 -86
  57. package/scripts/verify_lifecycle_spend_binding.js +88 -0
  58. package/scripts/verify_mpp_adapter.js +128 -128
  59. package/scripts/verify_production_readiness.js +268 -268
  60. package/scripts/verify_rate_limiter.js +52 -52
  61. package/scripts/verify_refund_credit.js +106 -106
  62. package/scripts/verify_release_candidate.js +81 -81
  63. package/scripts/verify_runtime_state_guard.js +117 -0
  64. package/scripts/verify_service.js +15421 -15421
  65. package/scripts/verify_verify_execute_settle.js +209 -208
  66. package/scripts/verify_x402_facilitator.js +307 -286
  67. package/scripts/verify_x402_settlement_recovery.js +153 -0
  68. package/server.js +12242 -11974
@@ -1,399 +1,399 @@
1
- "use strict";
2
-
3
- const crypto = require("crypto");
4
-
5
- function setResultRemediation(state, transactionId, patch) {
6
- if (!transactionId || !state.transactions.has(transactionId)) {
7
- return;
8
- }
9
- const current = state.transactions.get(transactionId);
10
- const currentTransactionRemediation = current.transaction && current.transaction.remediation && typeof current.transaction.remediation === "object"
11
- ? current.transaction.remediation
12
- : {};
13
- const currentReceiptRemediation = current.receipt && current.receipt.remediation && typeof current.receipt.remediation === "object"
14
- ? current.receipt.remediation
15
- : {};
16
- const nextRemediation = {
17
- ...currentTransactionRemediation,
18
- ...currentReceiptRemediation,
19
- ...(patch || {}),
20
- updated_at_iso: new Date().toISOString()
21
- };
22
- current.transaction.remediation = nextRemediation;
23
- current.receipt.remediation = nextRemediation;
24
- }
25
-
26
- function appendHistory(record, event, body, nextStatus) {
27
- const timestamp = new Date().toISOString();
28
- const actor = body && body.actor && typeof body.actor === "object" ? body.actor : { type: "operator", role: "reviewer" };
29
- const context = body && body.context && typeof body.context === "object" ? body.context : null;
30
- const previousStatus = record.status || null;
31
- return {
32
- ...record,
33
- status: nextStatus || record.status,
34
- updated_at_iso: timestamp,
35
- history: [
36
- ...(Array.isArray(record.history) ? record.history : []),
37
- {
38
- at_iso: timestamp,
39
- event,
40
- note: body && typeof body.note === "string" ? body.note : null,
41
- reason_code: body && typeof body.reason_code === "string" ? body.reason_code : record.reason_code || null,
42
- action_code: body && typeof body.action_code === "string" ? body.action_code : null,
43
- previous_status: previousStatus,
44
- next_status: nextStatus || record.status,
45
- actor,
46
- context
47
- }
48
- ].slice(-20)
49
- };
50
- }
51
-
52
- function createDispute(state, body) {
53
- const timestamp = new Date().toISOString();
54
- const actor = body && body.actor && typeof body.actor === "object" ? body.actor : { type: "operator", role: "creator" };
55
- const context = body && body.context && typeof body.context === "object" ? body.context : null;
56
- const dispute = {
57
- dispute_id: `dsp_${crypto.randomBytes(6).toString("hex")}`,
58
- title: typeof body.title === "string" && body.title.trim() ? body.title.trim() : "Dispute",
59
- description: typeof body.description === "string" && body.description.trim() ? body.description.trim() : null,
60
- status: "open",
61
- transaction_id: body.transaction_id || null,
62
- receipt_id: body.receipt_id || null,
63
- reason_code: body.reason_code || "other",
64
- note: body.note || null,
65
- evidence: body && body.evidence && typeof body.evidence === "object" ? body.evidence : {},
66
- created_at_iso: timestamp,
67
- updated_at_iso: timestamp,
68
- created_actor: actor,
69
- created_context: context,
70
- history: [
71
- {
72
- at_iso: timestamp,
73
- event: "opened",
74
- note: body.note || body.description || null,
75
- reason_code: body.reason_code || "other",
76
- action_code: null,
77
- previous_status: null,
78
- next_status: "open",
79
- actor,
80
- context
81
- }
82
- ]
83
- };
84
- state.disputes.set(dispute.dispute_id, dispute);
85
- setResultRemediation(state, dispute.transaction_id, {
86
- status: "under_dispute",
87
- reason_code: dispute.reason_code,
88
- active_case_type: "dispute",
89
- active_case_id: dispute.dispute_id,
90
- compensating_action_status: "none"
91
- });
92
- return dispute;
93
- }
94
-
95
- function createRefund(state, body) {
96
- const timestamp = new Date().toISOString();
97
- const actor = body && body.actor && typeof body.actor === "object" ? body.actor : { type: "operator", role: "creator" };
98
- const context = body && body.context && typeof body.context === "object" ? body.context : null;
99
- const refund = {
100
- refund_id: `rfd_${crypto.randomBytes(6).toString("hex")}`,
101
- status: "requested",
102
- transaction_id: body.transaction_id || null,
103
- receipt_id: body.receipt_id || null,
104
- purchase_intent_id: body.purchase_intent_id || null,
105
- reason_code: body.reason_code || "other",
106
- note: body.note || null,
107
- requested_by: typeof body.requested_by === "string" && body.requested_by.trim() ? body.requested_by.trim() : "operator",
108
- created_at_iso: timestamp,
109
- updated_at_iso: timestamp,
110
- created_actor: actor,
111
- created_context: context,
112
- history: [
113
- {
114
- at_iso: timestamp,
115
- event: "requested",
116
- note: body.note || null,
117
- reason_code: body.reason_code || "other",
118
- action_code: null,
119
- previous_status: null,
120
- next_status: "requested",
121
- actor,
122
- context
123
- }
124
- ]
125
- };
126
- state.refunds.set(refund.refund_id, refund);
127
- setResultRemediation(state, refund.transaction_id, {
128
- status: "remediation_pending",
129
- reason_code: refund.reason_code,
130
- active_case_type: "refund",
131
- active_case_id: refund.refund_id,
132
- compensating_action_status: "none"
133
- });
134
- return refund;
135
- }
136
-
137
- function actOnDispute(state, disputeId, body) {
138
- const current = state.disputes.get(disputeId);
139
- if (!current) return null;
140
- const action = String((body && body.action) || "").trim();
141
- const statusByAction = {
142
- review: "under_review",
143
- escalate: "escalated",
144
- reopen: "open",
145
- resolve: "resolved",
146
- dismiss: "dismissed"
147
- };
148
- const nextStatus = statusByAction[action] || current.status;
149
- const next = appendHistory(current, action || "review", body, nextStatus);
150
- if (body && typeof body.resolution_code === "string" && body.resolution_code.trim()) {
151
- next.resolution_code = body.resolution_code.trim();
152
- }
153
- state.disputes.set(disputeId, next);
154
- const remediationStatus = next.status === "resolved" || next.status === "dismissed"
155
- ? "none"
156
- : next.status === "escalated"
157
- ? "escalated"
158
- : "under_dispute";
159
- setResultRemediation(state, next.transaction_id, {
160
- status: remediationStatus,
161
- reason_code: remediationStatus === "none" ? null : next.reason_code,
162
- active_case_type: remediationStatus === "none" ? null : "dispute",
163
- active_case_id: remediationStatus === "none" ? null : next.dispute_id,
164
- compensating_action_status: remediationStatus === "none" ? null : "none"
165
- });
166
- return next;
167
- }
168
-
169
- function actOnRefund(state, refundId, body) {
170
- const current = state.refunds.get(refundId);
171
- if (!current) return null;
172
- const action = String((body && body.action) || "").trim();
173
- const allowedActionsByStatus = {
174
- requested: ["review", "cancel"],
175
- under_review: ["approve", "cancel", "fail", "pending_manual"],
176
- approved: ["complete", "fail", "pending_manual", "cancel"],
177
- pending_manual: ["complete", "fail", "cancel"],
178
- failed: [],
179
- completed: [],
180
- cancelled: []
181
- };
182
- const allowedActions = allowedActionsByStatus[current.status] || [];
183
- if (action && !allowedActions.includes(action)) {
184
- return null;
185
- }
186
- const statusByAction = {
187
- review: "under_review",
188
- approve: "approved",
189
- complete: "completed",
190
- cancel: "cancelled",
191
- fail: "failed",
192
- pending_manual: "pending_manual"
193
- };
194
- const nextStatus = statusByAction[action] || current.status;
195
- const next = appendHistory(current, action || "review", body, nextStatus);
196
- if (body && typeof body.action_code === "string" && body.action_code.trim()) {
197
- next.action_code = body.action_code.trim();
198
- }
199
- state.refunds.set(refundId, next);
200
- const remediationStatus = next.status === "completed"
201
- ? "compensated"
202
- : next.status === "cancelled"
203
- ? "none"
204
- : next.status === "approved"
205
- ? "remediation_pending"
206
- : next.status === "pending_manual"
207
- ? "remediation_pending"
208
- : next.status === "failed"
209
- ? "compensation_failed"
210
- : "remediation_pending";
211
- setResultRemediation(state, next.transaction_id, {
212
- status: remediationStatus,
213
- reason_code: remediationStatus === "none" ? null : next.reason_code,
214
- active_case_type: remediationStatus === "compensated" || remediationStatus === "none" ? null : "refund",
215
- active_case_id: remediationStatus === "compensated" || remediationStatus === "none" ? null : next.refund_id,
216
- compensating_action_status: remediationStatus === "none" ? null : next.status
217
- });
218
- return next;
219
- }
220
-
221
- function createRemediationTicket(state, body) {
222
- const timestamp = new Date().toISOString();
223
- const actor = body && body.actor && typeof body.actor === "object" ? body.actor : { type: "operator", role: "creator" };
224
- const context = body && body.context && typeof body.context === "object" ? body.context : null;
225
- const ticket = {
226
- ticket_id: `rmt_${crypto.randomBytes(6).toString("hex")}`,
227
- status: "open",
228
- transaction_id: body.transaction_id || null,
229
- receipt_id: body.receipt_id || null,
230
- reason_code: body.reason_code || "other",
231
- action_code: body.action_code || "investigate",
232
- assigned_owner: typeof body.assigned_owner === "string" && body.assigned_owner.trim() ? body.assigned_owner.trim() : null,
233
- note: body.note || null,
234
- created_at_iso: timestamp,
235
- updated_at_iso: timestamp,
236
- created_actor: actor,
237
- created_context: context,
238
- history: [
239
- {
240
- at_iso: timestamp,
241
- event: "opened",
242
- note: body.note || null,
243
- reason_code: body.reason_code || "other",
244
- action_code: body.action_code || "investigate",
245
- previous_status: null,
246
- next_status: "open",
247
- actor,
248
- context
249
- }
250
- ]
251
- };
252
- state.remediationTickets.set(ticket.ticket_id, ticket);
253
- setResultRemediation(state, ticket.transaction_id, {
254
- status: "remediation_pending",
255
- reason_code: ticket.reason_code,
256
- active_case_type: "remediation_ticket",
257
- active_case_id: ticket.ticket_id,
258
- compensating_action_status: ticket.action_code
259
- });
260
- return ticket;
261
- }
262
-
263
- function actOnRemediationTicket(state, ticketId, body) {
264
- const current = state.remediationTickets.get(ticketId);
265
- if (!current) return null;
266
- const action = String((body && body.action) || "").trim();
267
- const statusByAction = {
268
- acknowledge: "acknowledged",
269
- assign: "assigned",
270
- escalate: "escalated",
271
- resolve: "resolved",
272
- clear: "cleared"
273
- };
274
- const next = appendHistory(current, action || "acknowledge", body, statusByAction[action] || current.status);
275
- if (body && body.reason_code) {
276
- next.reason_code = body.reason_code;
277
- }
278
- if (body && body.action_code) {
279
- next.action_code = body.action_code;
280
- }
281
- if (body && typeof body.assigned_owner === "string" && body.assigned_owner.trim()) {
282
- next.assigned_owner = body.assigned_owner.trim();
283
- }
284
- if (body && typeof body.note === "string" && body.note.trim()) {
285
- if (next.status === "assigned") {
286
- next.assignment_note = body.note.trim();
287
- }
288
- if (next.status === "cleared") {
289
- next.cleared_note = body.note.trim();
290
- }
291
- }
292
- state.remediationTickets.set(ticketId, next);
293
- const remediationStatus = next.status === "cleared"
294
- ? "none"
295
- : next.status === "resolved"
296
- ? "none"
297
- : next.status === "escalated"
298
- ? "escalated"
299
- : "remediation_pending";
300
- setResultRemediation(state, next.transaction_id, {
301
- status: remediationStatus,
302
- reason_code: remediationStatus === "none" ? null : next.reason_code,
303
- active_case_type: remediationStatus === "none" ? null : "remediation_ticket",
304
- active_case_id: remediationStatus === "none" ? null : next.ticket_id,
305
- compensating_action_status: remediationStatus === "none" ? null : next.action_code
306
- });
307
- return next;
308
- }
309
-
310
- function resolveRefundAccountId(state, refund, body) {
311
- const explicit = body && typeof body.account_id === "string" && body.account_id.trim() ? body.account_id.trim() : null;
312
- if (explicit) return explicit;
313
- const txId = refund && refund.transaction_id;
314
- if (txId && state.transactions && state.transactions.has(txId)) {
315
- const record = state.transactions.get(txId);
316
- const fromTx = record && ((record.transaction && record.transaction.account_id) || record.account_id);
317
- if (typeof fromTx === "string" && fromTx.trim()) return fromTx.trim();
318
- }
319
- return null;
320
- }
321
-
322
- // Settle a refund by returning value to the paying account as re-spendable CREDITS.
323
- // This is deliberately NOT an autonomous outbound transfer: it only MINTS credits into
324
- // the account's balance (reusing the proven external-credit-grant primitive) and never
325
- // moves funds out of the treasury. The credited amount is operator-controlled
326
- // (refund_units, required) rather than auto-derived, and the operation is idempotent per
327
- // refund (grant_id = refund_credit_<id>), so a refund can never mint twice. The caller
328
- // (server route) MUST gate this behind the credit-bridge bearer, exactly like direct
329
- // credit grants, so a refund cannot become an unauthenticated credit-minting bypass.
330
- function settleRefundAsCredit(state, refundId, body) {
331
- const refund = state.refunds.get(refundId);
332
- if (!refund) return { ok: false, status: 404, reason: "refund_not_found" };
333
- if (refund.credit_grant_id) {
334
- return { ok: true, status: 200, already_settled: true, refund, grant_id: refund.credit_grant_id };
335
- }
336
- const settleableStatuses = new Set(["requested", "under_review", "approved", "pending_manual"]);
337
- if (!settleableStatuses.has(refund.status)) {
338
- return { ok: false, status: 409, reason: "refund_not_settleable", detail: `refund status is ${refund.status}` };
339
- }
340
- const units = Number(body && body.refund_units);
341
- if (!Number.isFinite(units) || units <= 0) {
342
- return { ok: false, status: 400, reason: "refund_units_required", detail: "provide a positive refund_units to return value as credits" };
343
- }
344
- const accountId = resolveRefundAccountId(state, refund, body);
345
- if (!accountId) {
346
- return { ok: false, status: 400, reason: "refund_account_unresolved", detail: "provide account_id or link the refund to a known transaction" };
347
- }
348
- const { createExternalCreditGrant } = require("./external_credit_bridge");
349
- const grant = createExternalCreditGrant(state, {
350
- grant_id: `refund_credit_${refund.refund_id}`,
351
- idempotency_key: `refund_credit_${refund.refund_id}`,
352
- account_id: accountId,
353
- units,
354
- amount_minor: Number.isFinite(Number(body && body.refund_amount_minor)) ? Number(body.refund_amount_minor) : null,
355
- currency: body && typeof body.currency === "string" && body.currency.trim() ? body.currency.trim() : null,
356
- source: "refund_credit",
357
- // Honest ledger labeling: refund-origin credits bucket under their own rail_kind/
358
- // reason so rail-summary views never conflate them with external-checkout money-in.
359
- rail_kind: "refund_credit_bridge",
360
- reason: "refund_credit",
361
- metadata: {
362
- refund_id: refund.refund_id,
363
- transaction_id: refund.transaction_id || null,
364
- reason_code: refund.reason_code || null
365
- }
366
- });
367
- if (grant && grant.ok === false) {
368
- return { ok: false, status: 422, reason: grant.reason || "refund_credit_failed" };
369
- }
370
- const next = appendHistory(refund, "settle_credit", body, "completed");
371
- next.credit_grant_id = grant.grant_id;
372
- next.refunded_units = units;
373
- next.refund_settlement = {
374
- mode: "credit",
375
- grant_id: grant.grant_id,
376
- account_id: accountId,
377
- units,
378
- amount_minor: grant.amount_minor != null ? grant.amount_minor : null
379
- };
380
- state.refunds.set(refundId, next);
381
- setResultRemediation(state, next.transaction_id, {
382
- status: "compensated",
383
- reason_code: null,
384
- active_case_type: null,
385
- active_case_id: null,
386
- compensating_action_status: "completed"
387
- });
388
- return { ok: true, status: 200, refund: next, grant_id: grant.grant_id, account_id: accountId, units };
389
- }
390
-
391
- module.exports = {
392
- actOnDispute,
393
- actOnRefund,
394
- actOnRemediationTicket,
395
- createDispute,
396
- createRefund,
397
- createRemediationTicket,
398
- settleRefundAsCredit
399
- };
1
+ "use strict";
2
+
3
+ const crypto = require("crypto");
4
+
5
+ function setResultRemediation(state, transactionId, patch) {
6
+ if (!transactionId || !state.transactions.has(transactionId)) {
7
+ return;
8
+ }
9
+ const current = state.transactions.get(transactionId);
10
+ const currentTransactionRemediation = current.transaction && current.transaction.remediation && typeof current.transaction.remediation === "object"
11
+ ? current.transaction.remediation
12
+ : {};
13
+ const currentReceiptRemediation = current.receipt && current.receipt.remediation && typeof current.receipt.remediation === "object"
14
+ ? current.receipt.remediation
15
+ : {};
16
+ const nextRemediation = {
17
+ ...currentTransactionRemediation,
18
+ ...currentReceiptRemediation,
19
+ ...(patch || {}),
20
+ updated_at_iso: new Date().toISOString()
21
+ };
22
+ current.transaction.remediation = nextRemediation;
23
+ current.receipt.remediation = nextRemediation;
24
+ }
25
+
26
+ function appendHistory(record, event, body, nextStatus) {
27
+ const timestamp = new Date().toISOString();
28
+ const actor = body && body.actor && typeof body.actor === "object" ? body.actor : { type: "operator", role: "reviewer" };
29
+ const context = body && body.context && typeof body.context === "object" ? body.context : null;
30
+ const previousStatus = record.status || null;
31
+ return {
32
+ ...record,
33
+ status: nextStatus || record.status,
34
+ updated_at_iso: timestamp,
35
+ history: [
36
+ ...(Array.isArray(record.history) ? record.history : []),
37
+ {
38
+ at_iso: timestamp,
39
+ event,
40
+ note: body && typeof body.note === "string" ? body.note : null,
41
+ reason_code: body && typeof body.reason_code === "string" ? body.reason_code : record.reason_code || null,
42
+ action_code: body && typeof body.action_code === "string" ? body.action_code : null,
43
+ previous_status: previousStatus,
44
+ next_status: nextStatus || record.status,
45
+ actor,
46
+ context
47
+ }
48
+ ].slice(-20)
49
+ };
50
+ }
51
+
52
+ function createDispute(state, body) {
53
+ const timestamp = new Date().toISOString();
54
+ const actor = body && body.actor && typeof body.actor === "object" ? body.actor : { type: "operator", role: "creator" };
55
+ const context = body && body.context && typeof body.context === "object" ? body.context : null;
56
+ const dispute = {
57
+ dispute_id: `dsp_${crypto.randomBytes(6).toString("hex")}`,
58
+ title: typeof body.title === "string" && body.title.trim() ? body.title.trim() : "Dispute",
59
+ description: typeof body.description === "string" && body.description.trim() ? body.description.trim() : null,
60
+ status: "open",
61
+ transaction_id: body.transaction_id || null,
62
+ receipt_id: body.receipt_id || null,
63
+ reason_code: body.reason_code || "other",
64
+ note: body.note || null,
65
+ evidence: body && body.evidence && typeof body.evidence === "object" ? body.evidence : {},
66
+ created_at_iso: timestamp,
67
+ updated_at_iso: timestamp,
68
+ created_actor: actor,
69
+ created_context: context,
70
+ history: [
71
+ {
72
+ at_iso: timestamp,
73
+ event: "opened",
74
+ note: body.note || body.description || null,
75
+ reason_code: body.reason_code || "other",
76
+ action_code: null,
77
+ previous_status: null,
78
+ next_status: "open",
79
+ actor,
80
+ context
81
+ }
82
+ ]
83
+ };
84
+ state.disputes.set(dispute.dispute_id, dispute);
85
+ setResultRemediation(state, dispute.transaction_id, {
86
+ status: "under_dispute",
87
+ reason_code: dispute.reason_code,
88
+ active_case_type: "dispute",
89
+ active_case_id: dispute.dispute_id,
90
+ compensating_action_status: "none"
91
+ });
92
+ return dispute;
93
+ }
94
+
95
+ function createRefund(state, body) {
96
+ const timestamp = new Date().toISOString();
97
+ const actor = body && body.actor && typeof body.actor === "object" ? body.actor : { type: "operator", role: "creator" };
98
+ const context = body && body.context && typeof body.context === "object" ? body.context : null;
99
+ const refund = {
100
+ refund_id: `rfd_${crypto.randomBytes(6).toString("hex")}`,
101
+ status: "requested",
102
+ transaction_id: body.transaction_id || null,
103
+ receipt_id: body.receipt_id || null,
104
+ purchase_intent_id: body.purchase_intent_id || null,
105
+ reason_code: body.reason_code || "other",
106
+ note: body.note || null,
107
+ requested_by: typeof body.requested_by === "string" && body.requested_by.trim() ? body.requested_by.trim() : "operator",
108
+ created_at_iso: timestamp,
109
+ updated_at_iso: timestamp,
110
+ created_actor: actor,
111
+ created_context: context,
112
+ history: [
113
+ {
114
+ at_iso: timestamp,
115
+ event: "requested",
116
+ note: body.note || null,
117
+ reason_code: body.reason_code || "other",
118
+ action_code: null,
119
+ previous_status: null,
120
+ next_status: "requested",
121
+ actor,
122
+ context
123
+ }
124
+ ]
125
+ };
126
+ state.refunds.set(refund.refund_id, refund);
127
+ setResultRemediation(state, refund.transaction_id, {
128
+ status: "remediation_pending",
129
+ reason_code: refund.reason_code,
130
+ active_case_type: "refund",
131
+ active_case_id: refund.refund_id,
132
+ compensating_action_status: "none"
133
+ });
134
+ return refund;
135
+ }
136
+
137
+ function actOnDispute(state, disputeId, body) {
138
+ const current = state.disputes.get(disputeId);
139
+ if (!current) return null;
140
+ const action = String((body && body.action) || "").trim();
141
+ const statusByAction = {
142
+ review: "under_review",
143
+ escalate: "escalated",
144
+ reopen: "open",
145
+ resolve: "resolved",
146
+ dismiss: "dismissed"
147
+ };
148
+ const nextStatus = statusByAction[action] || current.status;
149
+ const next = appendHistory(current, action || "review", body, nextStatus);
150
+ if (body && typeof body.resolution_code === "string" && body.resolution_code.trim()) {
151
+ next.resolution_code = body.resolution_code.trim();
152
+ }
153
+ state.disputes.set(disputeId, next);
154
+ const remediationStatus = next.status === "resolved" || next.status === "dismissed"
155
+ ? "none"
156
+ : next.status === "escalated"
157
+ ? "escalated"
158
+ : "under_dispute";
159
+ setResultRemediation(state, next.transaction_id, {
160
+ status: remediationStatus,
161
+ reason_code: remediationStatus === "none" ? null : next.reason_code,
162
+ active_case_type: remediationStatus === "none" ? null : "dispute",
163
+ active_case_id: remediationStatus === "none" ? null : next.dispute_id,
164
+ compensating_action_status: remediationStatus === "none" ? null : "none"
165
+ });
166
+ return next;
167
+ }
168
+
169
+ function actOnRefund(state, refundId, body) {
170
+ const current = state.refunds.get(refundId);
171
+ if (!current) return null;
172
+ const action = String((body && body.action) || "").trim();
173
+ const allowedActionsByStatus = {
174
+ requested: ["review", "cancel"],
175
+ under_review: ["approve", "cancel", "fail", "pending_manual"],
176
+ approved: ["complete", "fail", "pending_manual", "cancel"],
177
+ pending_manual: ["complete", "fail", "cancel"],
178
+ failed: [],
179
+ completed: [],
180
+ cancelled: []
181
+ };
182
+ const allowedActions = allowedActionsByStatus[current.status] || [];
183
+ if (action && !allowedActions.includes(action)) {
184
+ return null;
185
+ }
186
+ const statusByAction = {
187
+ review: "under_review",
188
+ approve: "approved",
189
+ complete: "completed",
190
+ cancel: "cancelled",
191
+ fail: "failed",
192
+ pending_manual: "pending_manual"
193
+ };
194
+ const nextStatus = statusByAction[action] || current.status;
195
+ const next = appendHistory(current, action || "review", body, nextStatus);
196
+ if (body && typeof body.action_code === "string" && body.action_code.trim()) {
197
+ next.action_code = body.action_code.trim();
198
+ }
199
+ state.refunds.set(refundId, next);
200
+ const remediationStatus = next.status === "completed"
201
+ ? "compensated"
202
+ : next.status === "cancelled"
203
+ ? "none"
204
+ : next.status === "approved"
205
+ ? "remediation_pending"
206
+ : next.status === "pending_manual"
207
+ ? "remediation_pending"
208
+ : next.status === "failed"
209
+ ? "compensation_failed"
210
+ : "remediation_pending";
211
+ setResultRemediation(state, next.transaction_id, {
212
+ status: remediationStatus,
213
+ reason_code: remediationStatus === "none" ? null : next.reason_code,
214
+ active_case_type: remediationStatus === "compensated" || remediationStatus === "none" ? null : "refund",
215
+ active_case_id: remediationStatus === "compensated" || remediationStatus === "none" ? null : next.refund_id,
216
+ compensating_action_status: remediationStatus === "none" ? null : next.status
217
+ });
218
+ return next;
219
+ }
220
+
221
+ function createRemediationTicket(state, body) {
222
+ const timestamp = new Date().toISOString();
223
+ const actor = body && body.actor && typeof body.actor === "object" ? body.actor : { type: "operator", role: "creator" };
224
+ const context = body && body.context && typeof body.context === "object" ? body.context : null;
225
+ const ticket = {
226
+ ticket_id: `rmt_${crypto.randomBytes(6).toString("hex")}`,
227
+ status: "open",
228
+ transaction_id: body.transaction_id || null,
229
+ receipt_id: body.receipt_id || null,
230
+ reason_code: body.reason_code || "other",
231
+ action_code: body.action_code || "investigate",
232
+ assigned_owner: typeof body.assigned_owner === "string" && body.assigned_owner.trim() ? body.assigned_owner.trim() : null,
233
+ note: body.note || null,
234
+ created_at_iso: timestamp,
235
+ updated_at_iso: timestamp,
236
+ created_actor: actor,
237
+ created_context: context,
238
+ history: [
239
+ {
240
+ at_iso: timestamp,
241
+ event: "opened",
242
+ note: body.note || null,
243
+ reason_code: body.reason_code || "other",
244
+ action_code: body.action_code || "investigate",
245
+ previous_status: null,
246
+ next_status: "open",
247
+ actor,
248
+ context
249
+ }
250
+ ]
251
+ };
252
+ state.remediationTickets.set(ticket.ticket_id, ticket);
253
+ setResultRemediation(state, ticket.transaction_id, {
254
+ status: "remediation_pending",
255
+ reason_code: ticket.reason_code,
256
+ active_case_type: "remediation_ticket",
257
+ active_case_id: ticket.ticket_id,
258
+ compensating_action_status: ticket.action_code
259
+ });
260
+ return ticket;
261
+ }
262
+
263
+ function actOnRemediationTicket(state, ticketId, body) {
264
+ const current = state.remediationTickets.get(ticketId);
265
+ if (!current) return null;
266
+ const action = String((body && body.action) || "").trim();
267
+ const statusByAction = {
268
+ acknowledge: "acknowledged",
269
+ assign: "assigned",
270
+ escalate: "escalated",
271
+ resolve: "resolved",
272
+ clear: "cleared"
273
+ };
274
+ const next = appendHistory(current, action || "acknowledge", body, statusByAction[action] || current.status);
275
+ if (body && body.reason_code) {
276
+ next.reason_code = body.reason_code;
277
+ }
278
+ if (body && body.action_code) {
279
+ next.action_code = body.action_code;
280
+ }
281
+ if (body && typeof body.assigned_owner === "string" && body.assigned_owner.trim()) {
282
+ next.assigned_owner = body.assigned_owner.trim();
283
+ }
284
+ if (body && typeof body.note === "string" && body.note.trim()) {
285
+ if (next.status === "assigned") {
286
+ next.assignment_note = body.note.trim();
287
+ }
288
+ if (next.status === "cleared") {
289
+ next.cleared_note = body.note.trim();
290
+ }
291
+ }
292
+ state.remediationTickets.set(ticketId, next);
293
+ const remediationStatus = next.status === "cleared"
294
+ ? "none"
295
+ : next.status === "resolved"
296
+ ? "none"
297
+ : next.status === "escalated"
298
+ ? "escalated"
299
+ : "remediation_pending";
300
+ setResultRemediation(state, next.transaction_id, {
301
+ status: remediationStatus,
302
+ reason_code: remediationStatus === "none" ? null : next.reason_code,
303
+ active_case_type: remediationStatus === "none" ? null : "remediation_ticket",
304
+ active_case_id: remediationStatus === "none" ? null : next.ticket_id,
305
+ compensating_action_status: remediationStatus === "none" ? null : next.action_code
306
+ });
307
+ return next;
308
+ }
309
+
310
+ function resolveRefundAccountId(state, refund, body) {
311
+ const explicit = body && typeof body.account_id === "string" && body.account_id.trim() ? body.account_id.trim() : null;
312
+ if (explicit) return explicit;
313
+ const txId = refund && refund.transaction_id;
314
+ if (txId && state.transactions && state.transactions.has(txId)) {
315
+ const record = state.transactions.get(txId);
316
+ const fromTx = record && ((record.transaction && record.transaction.account_id) || record.account_id);
317
+ if (typeof fromTx === "string" && fromTx.trim()) return fromTx.trim();
318
+ }
319
+ return null;
320
+ }
321
+
322
+ // Settle a refund by returning value to the paying account as re-spendable CREDITS.
323
+ // This is deliberately NOT an autonomous outbound transfer: it only MINTS credits into
324
+ // the account's balance (reusing the proven external-credit-grant primitive) and never
325
+ // moves funds out of the treasury. The credited amount is operator-controlled
326
+ // (refund_units, required) rather than auto-derived, and the operation is idempotent per
327
+ // refund (grant_id = refund_credit_<id>), so a refund can never mint twice. The caller
328
+ // (server route) MUST gate this behind the credit-bridge bearer, exactly like direct
329
+ // credit grants, so a refund cannot become an unauthenticated credit-minting bypass.
330
+ function settleRefundAsCredit(state, refundId, body) {
331
+ const refund = state.refunds.get(refundId);
332
+ if (!refund) return { ok: false, status: 404, reason: "refund_not_found" };
333
+ if (refund.credit_grant_id) {
334
+ return { ok: true, status: 200, already_settled: true, refund, grant_id: refund.credit_grant_id };
335
+ }
336
+ const settleableStatuses = new Set(["requested", "under_review", "approved", "pending_manual"]);
337
+ if (!settleableStatuses.has(refund.status)) {
338
+ return { ok: false, status: 409, reason: "refund_not_settleable", detail: `refund status is ${refund.status}` };
339
+ }
340
+ const units = Number(body && body.refund_units);
341
+ if (!Number.isFinite(units) || units <= 0) {
342
+ return { ok: false, status: 400, reason: "refund_units_required", detail: "provide a positive refund_units to return value as credits" };
343
+ }
344
+ const accountId = resolveRefundAccountId(state, refund, body);
345
+ if (!accountId) {
346
+ return { ok: false, status: 400, reason: "refund_account_unresolved", detail: "provide account_id or link the refund to a known transaction" };
347
+ }
348
+ const { createExternalCreditGrant } = require("./external_credit_bridge");
349
+ const grant = createExternalCreditGrant(state, {
350
+ grant_id: `refund_credit_${refund.refund_id}`,
351
+ idempotency_key: `refund_credit_${refund.refund_id}`,
352
+ account_id: accountId,
353
+ units,
354
+ amount_minor: Number.isFinite(Number(body && body.refund_amount_minor)) ? Number(body.refund_amount_minor) : null,
355
+ currency: body && typeof body.currency === "string" && body.currency.trim() ? body.currency.trim() : null,
356
+ source: "refund_credit",
357
+ // Honest ledger labeling: refund-origin credits bucket under their own rail_kind/
358
+ // reason so rail-summary views never conflate them with external-checkout money-in.
359
+ rail_kind: "refund_credit_bridge",
360
+ reason: "refund_credit",
361
+ metadata: {
362
+ refund_id: refund.refund_id,
363
+ transaction_id: refund.transaction_id || null,
364
+ reason_code: refund.reason_code || null
365
+ }
366
+ });
367
+ if (grant && grant.ok === false) {
368
+ return { ok: false, status: 422, reason: grant.reason || "refund_credit_failed" };
369
+ }
370
+ const next = appendHistory(refund, "settle_credit", body, "completed");
371
+ next.credit_grant_id = grant.grant_id;
372
+ next.refunded_units = units;
373
+ next.refund_settlement = {
374
+ mode: "credit",
375
+ grant_id: grant.grant_id,
376
+ account_id: accountId,
377
+ units,
378
+ amount_minor: grant.amount_minor != null ? grant.amount_minor : null
379
+ };
380
+ state.refunds.set(refundId, next);
381
+ setResultRemediation(state, next.transaction_id, {
382
+ status: "compensated",
383
+ reason_code: null,
384
+ active_case_type: null,
385
+ active_case_id: null,
386
+ compensating_action_status: "completed"
387
+ });
388
+ return { ok: true, status: 200, refund: next, grant_id: grant.grant_id, account_id: accountId, units };
389
+ }
390
+
391
+ module.exports = {
392
+ actOnDispute,
393
+ actOnRefund,
394
+ actOnRemediationTicket,
395
+ createDispute,
396
+ createRefund,
397
+ createRemediationTicket,
398
+ settleRefundAsCredit
399
+ };