xytara 3.1.13 → 3.1.14
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.
- package/.env.example +8 -1
- package/BSV_TERANODE_PLATFORM_DISCONTINUITY_RUNBOOK.md +126 -126
- package/RELEASE_NOTES.md +6 -4
- package/lib/a2a_rpc.js +280 -280
- package/lib/account_auth.js +585 -585
- package/lib/agent_identity.js +162 -162
- package/lib/bolt_adapter.js +187 -187
- package/lib/bolt_payment_front.js +224 -224
- package/lib/checkout_processor_adapter.js +217 -217
- package/lib/command_flow.js +722 -722
- package/lib/commerce_artifacts.js +591 -591
- package/lib/commerce_bridge.js +274 -274
- package/lib/commerce_cases.js +399 -399
- package/lib/commerce_client.js +7694 -7694
- package/lib/commerce_quotes.js +29 -0
- package/lib/commerce_runtime.js +322 -322
- package/lib/execution_dedupe.js +86 -86
- package/lib/external_credit_bridge.js +142 -142
- package/lib/http_transport.js +81 -81
- package/lib/l402_adapter.js +241 -241
- package/lib/l402_payment_front.js +265 -265
- package/lib/mpp_adapter.js +237 -237
- package/lib/payment_config.js +253 -253
- package/lib/payment_verification.js +357 -357
- package/lib/provider_payout_execution.js +155 -155
- package/lib/provider_registry.js +842 -842
- package/lib/rate_limiter.js +81 -81
- package/lib/runtime_state_store.js +491 -369
- package/lib/settlement_bsv_live.js +600 -600
- package/lib/settlement_bsv_teranode.js +117 -117
- package/lib/stripe_mpp_payment_front.js +258 -258
- package/lib/x402_facilitator.js +191 -191
- package/package.json +5 -3
- package/scripts/state_backup_offsite.js +196 -0
- package/scripts/verify_a2a_rpc.js +105 -105
- package/scripts/verify_agent_identity.js +153 -153
- package/scripts/verify_all.js +1 -1
- package/scripts/verify_bolt_adapter.js +128 -128
- package/scripts/verify_cdp_facilitator.js +110 -110
- package/scripts/verify_checkout_processor.js +109 -109
- package/scripts/verify_commerce_bridge.js +177 -177
- package/scripts/verify_execution_dedupe.js +189 -189
- package/scripts/verify_execution_surfacing.js +76 -76
- package/scripts/verify_final_activation.js +191 -191
- package/scripts/verify_l402_adapter.js +86 -86
- package/scripts/verify_mpp_adapter.js +128 -128
- package/scripts/verify_production_readiness.js +268 -268
- package/scripts/verify_rate_limiter.js +52 -52
- package/scripts/verify_refund_credit.js +106 -106
- package/scripts/verify_release_candidate.js +81 -81
- package/scripts/verify_runtime_state_guard.js +117 -0
- package/scripts/verify_service.js +15421 -15421
- package/scripts/verify_verify_execute_settle.js +208 -208
- package/scripts/verify_x402_facilitator.js +286 -286
- package/server.js +11976 -11974
package/lib/commerce_bridge.js
CHANGED
|
@@ -1,274 +1,274 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
// Generic external-commerce bridge — the name-neutral server-side contract an upstream
|
|
4
|
-
// fiat SaaS front calls after a confirmed payment. Two jobs:
|
|
5
|
-
// 1. /v1/commerce/grants -> mint internal units for a confirmed purchase
|
|
6
|
-
// (reuses the proven external-credit-grant primitive; idempotent per upstream event
|
|
7
|
-
// so a payment-webhook retry never double-mints).
|
|
8
|
-
// 2. /v1/commerce/prepare-execution -> issue a time-boxed DELEGATED-SPEND CREDENTIAL
|
|
9
|
-
// (the identity bridge) so the paying customer's agent can spend those units here,
|
|
10
|
-
// gated on sufficient balance.
|
|
11
|
-
// 3. /v1/commerce/state -> read-only unit balance for an account.
|
|
12
|
-
//
|
|
13
|
-
// This module names no upstream brand and the upstream names nothing here — the only
|
|
14
|
-
// things crossing the seam are opaque refs + units. Routes are gated by the commerce-
|
|
15
|
-
// bridge bearer (verifyCommerceBridgeAccess in server.js).
|
|
16
|
-
|
|
17
|
-
const { createExternalCreditGrant } = require("./external_credit_bridge");
|
|
18
|
-
const { createAuthorityBinding } = require("./account_auth");
|
|
19
|
-
const { normalizeAgentPublicKey } = require("./agent_identity");
|
|
20
|
-
const { buildCreditBalanceSummary, consumeAccountCredits } = require("./commerce_economics");
|
|
21
|
-
const { findCreditPack } = require("../fixtures/catalog");
|
|
22
|
-
|
|
23
|
-
function normalizeString(value, fallback = null) {
|
|
24
|
-
const s = typeof value === "string" ? value.trim() : "";
|
|
25
|
-
return s || fallback;
|
|
26
|
-
}
|
|
27
|
-
function ensureObject(value) {
|
|
28
|
-
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
function loadCommercePackMap() {
|
|
32
|
-
const raw = String(process.env.XYTARA_COMMERCE_PACK_MAP_JSON || "").trim();
|
|
33
|
-
if (!raw) return {};
|
|
34
|
-
try {
|
|
35
|
-
const parsed = JSON.parse(raw);
|
|
36
|
-
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
37
|
-
} catch (_) {
|
|
38
|
-
return {};
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
// How many internal units a package/plan grants: explicit pack map first
|
|
43
|
-
// (packageRef/planRef -> units), then a catalog credit pack's issued_units.
|
|
44
|
-
function resolveCommerceUnits(packageRef, planRef) {
|
|
45
|
-
const map = loadCommercePackMap();
|
|
46
|
-
const key = packageRef || planRef;
|
|
47
|
-
if (key && Object.prototype.hasOwnProperty.call(map, key)) {
|
|
48
|
-
const n = Number(map[key]);
|
|
49
|
-
if (Number.isFinite(n) && n > 0) return { units: n, pack_id: key };
|
|
50
|
-
}
|
|
51
|
-
const pack = key ? findCreditPack(key) : null;
|
|
52
|
-
if (pack && Number.isFinite(Number(pack.issued_units)) && Number(pack.issued_units) > 0) {
|
|
53
|
-
return { units: Number(pack.issued_units), pack_id: pack.pack_id };
|
|
54
|
-
}
|
|
55
|
-
return { units: null, pack_id: key || null };
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
function availableUnits(state, accountId) {
|
|
59
|
-
const summary = buildCreditBalanceSummary(state, accountId);
|
|
60
|
-
if (!summary) return 0;
|
|
61
|
-
if (typeof summary.available_units === "number") return summary.available_units;
|
|
62
|
-
if (summary.balance && typeof summary.balance.available_units === "number") return summary.balance.available_units;
|
|
63
|
-
if (summary.lifecycle_totals && typeof summary.lifecycle_totals.available_units === "number") return summary.lifecycle_totals.available_units;
|
|
64
|
-
return 0;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
// POST /v1/commerce/grants
|
|
68
|
-
function grantCommerceAllocation(state, body) {
|
|
69
|
-
const b = ensureObject(body);
|
|
70
|
-
const accountRef = normalizeString(b.accountRef);
|
|
71
|
-
if (!accountRef) return { http_status: 400, body: { ok: false, reason: "account_ref_required" } };
|
|
72
|
-
// Require a single stable, globally-unique dedup anchor (the upstream event id). No
|
|
73
|
-
// fallback chain: an ambiguous anchor could either double-mint (retry omits eventRef)
|
|
74
|
-
// or wrongly dedup a distinct purchase whose ref collides with a prior eventRef.
|
|
75
|
-
const eventRef = normalizeString(b.eventRef);
|
|
76
|
-
if (!eventRef) return { http_status: 400, body: { ok: false, reason: "event_ref_required" } };
|
|
77
|
-
const { units, pack_id } = resolveCommerceUnits(normalizeString(b.packageRef), normalizeString(b.planRef));
|
|
78
|
-
if (!Number.isFinite(units) || units <= 0) {
|
|
79
|
-
return { http_status: 422, body: { ok: false, reason: "unknown_package", detail: "no unit mapping for the package/plan; set XYTARA_COMMERCE_PACK_MAP_JSON" } };
|
|
80
|
-
}
|
|
81
|
-
// Both the grant_id and the idempotency_key are account-namespaced so a shared eventRef
|
|
82
|
-
// across two accounts (upstreams whose event ids are per-account sequences) cannot
|
|
83
|
-
// collide on grant_id (checked first by createExternalCreditGrant) and under-mint one.
|
|
84
|
-
const dedupeAnchor = `${accountRef}:${eventRef}`;
|
|
85
|
-
const idempotencyKey = `commerce_grant:${dedupeAnchor}`;
|
|
86
|
-
const grant = createExternalCreditGrant(state, {
|
|
87
|
-
grant_id: `commerce_grant_${dedupeAnchor}`,
|
|
88
|
-
idempotency_key: idempotencyKey,
|
|
89
|
-
account_id: accountRef,
|
|
90
|
-
// units is explicit; do NOT pass pack_id (createExternalCreditGrant validates pack_id
|
|
91
|
-
// against the catalog and the package ref is an upstream key, not a catalog pack).
|
|
92
|
-
units,
|
|
93
|
-
source: "commerce_bridge",
|
|
94
|
-
rail_kind: "commerce_bridge",
|
|
95
|
-
reason: "commerce_grant",
|
|
96
|
-
provider_reference: normalizeString(b.providerRef),
|
|
97
|
-
purchase_reference: normalizeString(b.purchaseRef),
|
|
98
|
-
metadata: {
|
|
99
|
-
order_type: normalizeString(b.orderType),
|
|
100
|
-
checkout_surface: ensureObject(b.metadata).checkoutSurface || "public_checkout",
|
|
101
|
-
package_ref: pack_id || null,
|
|
102
|
-
event_ref: eventRef
|
|
103
|
-
}
|
|
104
|
-
});
|
|
105
|
-
if (grant && grant.ok === false) {
|
|
106
|
-
return { http_status: 422, body: { ok: false, reason: grant.reason || "commerce_grant_failed" } };
|
|
107
|
-
}
|
|
108
|
-
// Response fields mirror what the upstream client reads (camelCase) + snake aliases.
|
|
109
|
-
return {
|
|
110
|
-
http_status: 200,
|
|
111
|
-
body: {
|
|
112
|
-
ok: true,
|
|
113
|
-
status: "granted",
|
|
114
|
-
grantId: grant.grant_id,
|
|
115
|
-
grant_id: grant.grant_id,
|
|
116
|
-
accountRef,
|
|
117
|
-
account_ref: accountRef,
|
|
118
|
-
hiddenAccountRef: accountRef,
|
|
119
|
-
hidden_account_ref: accountRef,
|
|
120
|
-
units,
|
|
121
|
-
unitsGranted: units,
|
|
122
|
-
entitlementRef: grant.entitlement_id || null,
|
|
123
|
-
economicRef: grant.entitlement_id || null
|
|
124
|
-
}
|
|
125
|
-
};
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
// POST /v1/commerce/prepare-execution
|
|
129
|
-
function prepareCommerceExecution(state, body) {
|
|
130
|
-
const b = ensureObject(body);
|
|
131
|
-
const accountRef = normalizeString(b.accountRef);
|
|
132
|
-
if (!accountRef) return { http_status: 400, body: { ok: false, reason: "account_ref_required" } };
|
|
133
|
-
const featureRef = normalizeString(b.featureRef);
|
|
134
|
-
const quotedUnits = Number.isFinite(Number(b.quotedUnits)) ? Number(b.quotedUnits) : 0;
|
|
135
|
-
const delegatedSpend = ensureObject(b.delegatedSpend);
|
|
136
|
-
const available = availableUnits(state, accountRef);
|
|
137
|
-
|
|
138
|
-
const refuse = (decision, extra) => ({
|
|
139
|
-
http_status: 200,
|
|
140
|
-
body: Object.assign({
|
|
141
|
-
ok: true,
|
|
142
|
-
authorized: false,
|
|
143
|
-
authorityMode: "delegated_spend_credential",
|
|
144
|
-
authorityDecision: decision,
|
|
145
|
-
spendAuthorityRef: null,
|
|
146
|
-
spendAuthorityToken: null,
|
|
147
|
-
validUntil: null,
|
|
148
|
-
delegatedSpendAccepted: false,
|
|
149
|
-
availableUnits: available,
|
|
150
|
-
quotedUnits,
|
|
151
|
-
capabilitySummary: []
|
|
152
|
-
}, extra || {})
|
|
153
|
-
});
|
|
154
|
-
|
|
155
|
-
// A bounded authorization requires a positive quote — the credential is capped to it.
|
|
156
|
-
if (!(quotedUnits > 0)) return refuse("quoted_units_required");
|
|
157
|
-
// Economic gate: only authorize when the account can cover the quote.
|
|
158
|
-
if (available < quotedUnits) return refuse("insufficient_units");
|
|
159
|
-
|
|
160
|
-
// Optional cryptographic agent-key binding. If an upstream intends identity binding
|
|
161
|
-
// but sends an unparseable key, REFUSE rather than silently downgrade to bearer-only
|
|
162
|
-
// (createSpendCredential would otherwise drop the key and still authorize).
|
|
163
|
-
const agentPublicKey = normalizeString(delegatedSpend.agent_public_key || delegatedSpend.agentPublicKey, null);
|
|
164
|
-
if (agentPublicKey && !normalizeAgentPublicKey(agentPublicKey)) {
|
|
165
|
-
return refuse("invalid_agent_key");
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
const ttlMs = Math.max(60000, Number(process.env.XYTARA_COMMERCE_PREP_TTL_MS || 900000) || 900000);
|
|
169
|
-
const validUntil = new Date(Date.now() + ttlMs).toISOString();
|
|
170
|
-
|
|
171
|
-
// Issue a BOUND delegated-spend credential via an authority binding: each spend action
|
|
172
|
-
// is capped at quotedUnits (max_commit/reserve/reversal), so the token can never commit
|
|
173
|
-
// more than the quote in one action and cannot drain the whole balance. Total spend is
|
|
174
|
-
// additionally hard-capped by the account balance at commit time. (Without a binding the
|
|
175
|
-
// credential is open_spend and the quote is not enforced.)
|
|
176
|
-
const binding = createAuthorityBinding(state, {
|
|
177
|
-
account_id: accountRef,
|
|
178
|
-
scope: "runtime_spend",
|
|
179
|
-
labels: [featureRef, "commerce_prepared"].filter(Boolean),
|
|
180
|
-
expires_at_iso: validUntil,
|
|
181
|
-
issued_by: "commerce_bridge",
|
|
182
|
-
// Constrain to spend/commit only — this credential is for executing paid work, not
|
|
183
|
-
// for driving reserve/release/reverse lifecycle actions.
|
|
184
|
-
authority_scope: ["runtime.execute"],
|
|
185
|
-
allowed_consequence_families: ["commit"],
|
|
186
|
-
max_commit_units: quotedUnits,
|
|
187
|
-
max_reserve_units: quotedUnits,
|
|
188
|
-
max_reversal_units: quotedUnits,
|
|
189
|
-
...(agentPublicKey ? { agent_public_key: agentPublicKey } : {})
|
|
190
|
-
});
|
|
191
|
-
const credentialView = (binding && binding.spend_credential) || {};
|
|
192
|
-
|
|
193
|
-
return {
|
|
194
|
-
http_status: 200,
|
|
195
|
-
body: {
|
|
196
|
-
ok: true,
|
|
197
|
-
authorized: true,
|
|
198
|
-
authorityMode: "delegated_spend_credential",
|
|
199
|
-
authorityDecision: "authorized",
|
|
200
|
-
// The binding is the authority ref; its credential's bearer token is what the
|
|
201
|
-
// paying customer's agent presents to spend here. Opaque upstream.
|
|
202
|
-
spendAuthorityRef: binding.binding_id,
|
|
203
|
-
spendAuthorityToken: credentialView.bearer_token || null,
|
|
204
|
-
credentialRef: binding.credential_id || null,
|
|
205
|
-
identityBound: Boolean(credentialView.agent_key_ref),
|
|
206
|
-
boundUnits: quotedUnits,
|
|
207
|
-
proofMode: "credential_issued",
|
|
208
|
-
proofRef: binding.binding_id,
|
|
209
|
-
economicRef: binding.credential_id || null,
|
|
210
|
-
validUntil,
|
|
211
|
-
delegatedSpendAccepted: Boolean(b.delegatedSpend),
|
|
212
|
-
availableUnits: available,
|
|
213
|
-
quotedUnits,
|
|
214
|
-
capabilitySummary: [featureRef].filter(Boolean)
|
|
215
|
-
}
|
|
216
|
-
};
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
// POST /v1/commerce/settle
|
|
220
|
-
// Server-side settlement for the trusted upstream seam: burn units against an account
|
|
221
|
-
// after it has executed the paid work. The commerce bearer IS the authority here (this is
|
|
222
|
-
// not a delegated-agent path), so there is no per-action bound — the account balance is
|
|
223
|
-
// the hard cap (consumeAccountCredits refuses an overdraw). Returns the raw consume
|
|
224
|
-
// result so an upstream caller reads the same credit_spend/usage_meter shape as the
|
|
225
|
-
// direct consume route.
|
|
226
|
-
function settleCommerceConsumption(state, body) {
|
|
227
|
-
const b = ensureObject(body);
|
|
228
|
-
const accountRef = normalizeString(b.accountRef || b.account_id);
|
|
229
|
-
if (!accountRef) return { http_status: 400, body: { ok: false, reason: "account_ref_required" } };
|
|
230
|
-
const units = Number(b.units);
|
|
231
|
-
if (!Number.isFinite(units) || units <= 0) {
|
|
232
|
-
return { http_status: 400, body: { ok: false, reason: "units_required" } };
|
|
233
|
-
}
|
|
234
|
-
const result = consumeAccountCredits(state, {
|
|
235
|
-
account_id: accountRef,
|
|
236
|
-
units,
|
|
237
|
-
task_ref: normalizeString(b.taskRef || b.task_ref),
|
|
238
|
-
workflow_ref: normalizeString(b.workflowRef || b.workflow_ref),
|
|
239
|
-
transaction_id: normalizeString(b.transactionRef || b.transaction_id),
|
|
240
|
-
quote_id: normalizeString(b.quoteRef || b.quote_id),
|
|
241
|
-
pack_id: normalizeString(b.packId || b.pack_id),
|
|
242
|
-
reason: normalizeString(b.reason, "commerce_settle")
|
|
243
|
-
});
|
|
244
|
-
if (result && result.ok === false) {
|
|
245
|
-
const http_status = result.reason === "insufficient_credits" ? 409 : 403;
|
|
246
|
-
return { http_status, body: result };
|
|
247
|
-
}
|
|
248
|
-
return { http_status: 200, body: result };
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
// GET /v1/commerce/state
|
|
252
|
-
function inspectCommerceState(state, query) {
|
|
253
|
-
const accountRef = normalizeString(query && (query.accountRef || query.account_ref));
|
|
254
|
-
if (!accountRef) return { http_status: 400, body: { ok: false, reason: "account_ref_required" } };
|
|
255
|
-
const available = availableUnits(state, accountRef);
|
|
256
|
-
return {
|
|
257
|
-
http_status: 200,
|
|
258
|
-
body: {
|
|
259
|
-
ok: true,
|
|
260
|
-
accountRef,
|
|
261
|
-
account_ref: accountRef,
|
|
262
|
-
availableUnits: available,
|
|
263
|
-
available_units: available
|
|
264
|
-
}
|
|
265
|
-
};
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
module.exports = {
|
|
269
|
-
grantCommerceAllocation,
|
|
270
|
-
prepareCommerceExecution,
|
|
271
|
-
settleCommerceConsumption,
|
|
272
|
-
inspectCommerceState,
|
|
273
|
-
resolveCommerceUnits
|
|
274
|
-
};
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
// Generic external-commerce bridge — the name-neutral server-side contract an upstream
|
|
4
|
+
// fiat SaaS front calls after a confirmed payment. Two jobs:
|
|
5
|
+
// 1. /v1/commerce/grants -> mint internal units for a confirmed purchase
|
|
6
|
+
// (reuses the proven external-credit-grant primitive; idempotent per upstream event
|
|
7
|
+
// so a payment-webhook retry never double-mints).
|
|
8
|
+
// 2. /v1/commerce/prepare-execution -> issue a time-boxed DELEGATED-SPEND CREDENTIAL
|
|
9
|
+
// (the identity bridge) so the paying customer's agent can spend those units here,
|
|
10
|
+
// gated on sufficient balance.
|
|
11
|
+
// 3. /v1/commerce/state -> read-only unit balance for an account.
|
|
12
|
+
//
|
|
13
|
+
// This module names no upstream brand and the upstream names nothing here — the only
|
|
14
|
+
// things crossing the seam are opaque refs + units. Routes are gated by the commerce-
|
|
15
|
+
// bridge bearer (verifyCommerceBridgeAccess in server.js).
|
|
16
|
+
|
|
17
|
+
const { createExternalCreditGrant } = require("./external_credit_bridge");
|
|
18
|
+
const { createAuthorityBinding } = require("./account_auth");
|
|
19
|
+
const { normalizeAgentPublicKey } = require("./agent_identity");
|
|
20
|
+
const { buildCreditBalanceSummary, consumeAccountCredits } = require("./commerce_economics");
|
|
21
|
+
const { findCreditPack } = require("../fixtures/catalog");
|
|
22
|
+
|
|
23
|
+
function normalizeString(value, fallback = null) {
|
|
24
|
+
const s = typeof value === "string" ? value.trim() : "";
|
|
25
|
+
return s || fallback;
|
|
26
|
+
}
|
|
27
|
+
function ensureObject(value) {
|
|
28
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function loadCommercePackMap() {
|
|
32
|
+
const raw = String(process.env.XYTARA_COMMERCE_PACK_MAP_JSON || "").trim();
|
|
33
|
+
if (!raw) return {};
|
|
34
|
+
try {
|
|
35
|
+
const parsed = JSON.parse(raw);
|
|
36
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
37
|
+
} catch (_) {
|
|
38
|
+
return {};
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// How many internal units a package/plan grants: explicit pack map first
|
|
43
|
+
// (packageRef/planRef -> units), then a catalog credit pack's issued_units.
|
|
44
|
+
function resolveCommerceUnits(packageRef, planRef) {
|
|
45
|
+
const map = loadCommercePackMap();
|
|
46
|
+
const key = packageRef || planRef;
|
|
47
|
+
if (key && Object.prototype.hasOwnProperty.call(map, key)) {
|
|
48
|
+
const n = Number(map[key]);
|
|
49
|
+
if (Number.isFinite(n) && n > 0) return { units: n, pack_id: key };
|
|
50
|
+
}
|
|
51
|
+
const pack = key ? findCreditPack(key) : null;
|
|
52
|
+
if (pack && Number.isFinite(Number(pack.issued_units)) && Number(pack.issued_units) > 0) {
|
|
53
|
+
return { units: Number(pack.issued_units), pack_id: pack.pack_id };
|
|
54
|
+
}
|
|
55
|
+
return { units: null, pack_id: key || null };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function availableUnits(state, accountId) {
|
|
59
|
+
const summary = buildCreditBalanceSummary(state, accountId);
|
|
60
|
+
if (!summary) return 0;
|
|
61
|
+
if (typeof summary.available_units === "number") return summary.available_units;
|
|
62
|
+
if (summary.balance && typeof summary.balance.available_units === "number") return summary.balance.available_units;
|
|
63
|
+
if (summary.lifecycle_totals && typeof summary.lifecycle_totals.available_units === "number") return summary.lifecycle_totals.available_units;
|
|
64
|
+
return 0;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// POST /v1/commerce/grants
|
|
68
|
+
function grantCommerceAllocation(state, body) {
|
|
69
|
+
const b = ensureObject(body);
|
|
70
|
+
const accountRef = normalizeString(b.accountRef);
|
|
71
|
+
if (!accountRef) return { http_status: 400, body: { ok: false, reason: "account_ref_required" } };
|
|
72
|
+
// Require a single stable, globally-unique dedup anchor (the upstream event id). No
|
|
73
|
+
// fallback chain: an ambiguous anchor could either double-mint (retry omits eventRef)
|
|
74
|
+
// or wrongly dedup a distinct purchase whose ref collides with a prior eventRef.
|
|
75
|
+
const eventRef = normalizeString(b.eventRef);
|
|
76
|
+
if (!eventRef) return { http_status: 400, body: { ok: false, reason: "event_ref_required" } };
|
|
77
|
+
const { units, pack_id } = resolveCommerceUnits(normalizeString(b.packageRef), normalizeString(b.planRef));
|
|
78
|
+
if (!Number.isFinite(units) || units <= 0) {
|
|
79
|
+
return { http_status: 422, body: { ok: false, reason: "unknown_package", detail: "no unit mapping for the package/plan; set XYTARA_COMMERCE_PACK_MAP_JSON" } };
|
|
80
|
+
}
|
|
81
|
+
// Both the grant_id and the idempotency_key are account-namespaced so a shared eventRef
|
|
82
|
+
// across two accounts (upstreams whose event ids are per-account sequences) cannot
|
|
83
|
+
// collide on grant_id (checked first by createExternalCreditGrant) and under-mint one.
|
|
84
|
+
const dedupeAnchor = `${accountRef}:${eventRef}`;
|
|
85
|
+
const idempotencyKey = `commerce_grant:${dedupeAnchor}`;
|
|
86
|
+
const grant = createExternalCreditGrant(state, {
|
|
87
|
+
grant_id: `commerce_grant_${dedupeAnchor}`,
|
|
88
|
+
idempotency_key: idempotencyKey,
|
|
89
|
+
account_id: accountRef,
|
|
90
|
+
// units is explicit; do NOT pass pack_id (createExternalCreditGrant validates pack_id
|
|
91
|
+
// against the catalog and the package ref is an upstream key, not a catalog pack).
|
|
92
|
+
units,
|
|
93
|
+
source: "commerce_bridge",
|
|
94
|
+
rail_kind: "commerce_bridge",
|
|
95
|
+
reason: "commerce_grant",
|
|
96
|
+
provider_reference: normalizeString(b.providerRef),
|
|
97
|
+
purchase_reference: normalizeString(b.purchaseRef),
|
|
98
|
+
metadata: {
|
|
99
|
+
order_type: normalizeString(b.orderType),
|
|
100
|
+
checkout_surface: ensureObject(b.metadata).checkoutSurface || "public_checkout",
|
|
101
|
+
package_ref: pack_id || null,
|
|
102
|
+
event_ref: eventRef
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
if (grant && grant.ok === false) {
|
|
106
|
+
return { http_status: 422, body: { ok: false, reason: grant.reason || "commerce_grant_failed" } };
|
|
107
|
+
}
|
|
108
|
+
// Response fields mirror what the upstream client reads (camelCase) + snake aliases.
|
|
109
|
+
return {
|
|
110
|
+
http_status: 200,
|
|
111
|
+
body: {
|
|
112
|
+
ok: true,
|
|
113
|
+
status: "granted",
|
|
114
|
+
grantId: grant.grant_id,
|
|
115
|
+
grant_id: grant.grant_id,
|
|
116
|
+
accountRef,
|
|
117
|
+
account_ref: accountRef,
|
|
118
|
+
hiddenAccountRef: accountRef,
|
|
119
|
+
hidden_account_ref: accountRef,
|
|
120
|
+
units,
|
|
121
|
+
unitsGranted: units,
|
|
122
|
+
entitlementRef: grant.entitlement_id || null,
|
|
123
|
+
economicRef: grant.entitlement_id || null
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// POST /v1/commerce/prepare-execution
|
|
129
|
+
function prepareCommerceExecution(state, body) {
|
|
130
|
+
const b = ensureObject(body);
|
|
131
|
+
const accountRef = normalizeString(b.accountRef);
|
|
132
|
+
if (!accountRef) return { http_status: 400, body: { ok: false, reason: "account_ref_required" } };
|
|
133
|
+
const featureRef = normalizeString(b.featureRef);
|
|
134
|
+
const quotedUnits = Number.isFinite(Number(b.quotedUnits)) ? Number(b.quotedUnits) : 0;
|
|
135
|
+
const delegatedSpend = ensureObject(b.delegatedSpend);
|
|
136
|
+
const available = availableUnits(state, accountRef);
|
|
137
|
+
|
|
138
|
+
const refuse = (decision, extra) => ({
|
|
139
|
+
http_status: 200,
|
|
140
|
+
body: Object.assign({
|
|
141
|
+
ok: true,
|
|
142
|
+
authorized: false,
|
|
143
|
+
authorityMode: "delegated_spend_credential",
|
|
144
|
+
authorityDecision: decision,
|
|
145
|
+
spendAuthorityRef: null,
|
|
146
|
+
spendAuthorityToken: null,
|
|
147
|
+
validUntil: null,
|
|
148
|
+
delegatedSpendAccepted: false,
|
|
149
|
+
availableUnits: available,
|
|
150
|
+
quotedUnits,
|
|
151
|
+
capabilitySummary: []
|
|
152
|
+
}, extra || {})
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
// A bounded authorization requires a positive quote — the credential is capped to it.
|
|
156
|
+
if (!(quotedUnits > 0)) return refuse("quoted_units_required");
|
|
157
|
+
// Economic gate: only authorize when the account can cover the quote.
|
|
158
|
+
if (available < quotedUnits) return refuse("insufficient_units");
|
|
159
|
+
|
|
160
|
+
// Optional cryptographic agent-key binding. If an upstream intends identity binding
|
|
161
|
+
// but sends an unparseable key, REFUSE rather than silently downgrade to bearer-only
|
|
162
|
+
// (createSpendCredential would otherwise drop the key and still authorize).
|
|
163
|
+
const agentPublicKey = normalizeString(delegatedSpend.agent_public_key || delegatedSpend.agentPublicKey, null);
|
|
164
|
+
if (agentPublicKey && !normalizeAgentPublicKey(agentPublicKey)) {
|
|
165
|
+
return refuse("invalid_agent_key");
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const ttlMs = Math.max(60000, Number(process.env.XYTARA_COMMERCE_PREP_TTL_MS || 900000) || 900000);
|
|
169
|
+
const validUntil = new Date(Date.now() + ttlMs).toISOString();
|
|
170
|
+
|
|
171
|
+
// Issue a BOUND delegated-spend credential via an authority binding: each spend action
|
|
172
|
+
// is capped at quotedUnits (max_commit/reserve/reversal), so the token can never commit
|
|
173
|
+
// more than the quote in one action and cannot drain the whole balance. Total spend is
|
|
174
|
+
// additionally hard-capped by the account balance at commit time. (Without a binding the
|
|
175
|
+
// credential is open_spend and the quote is not enforced.)
|
|
176
|
+
const binding = createAuthorityBinding(state, {
|
|
177
|
+
account_id: accountRef,
|
|
178
|
+
scope: "runtime_spend",
|
|
179
|
+
labels: [featureRef, "commerce_prepared"].filter(Boolean),
|
|
180
|
+
expires_at_iso: validUntil,
|
|
181
|
+
issued_by: "commerce_bridge",
|
|
182
|
+
// Constrain to spend/commit only — this credential is for executing paid work, not
|
|
183
|
+
// for driving reserve/release/reverse lifecycle actions.
|
|
184
|
+
authority_scope: ["runtime.execute"],
|
|
185
|
+
allowed_consequence_families: ["commit"],
|
|
186
|
+
max_commit_units: quotedUnits,
|
|
187
|
+
max_reserve_units: quotedUnits,
|
|
188
|
+
max_reversal_units: quotedUnits,
|
|
189
|
+
...(agentPublicKey ? { agent_public_key: agentPublicKey } : {})
|
|
190
|
+
});
|
|
191
|
+
const credentialView = (binding && binding.spend_credential) || {};
|
|
192
|
+
|
|
193
|
+
return {
|
|
194
|
+
http_status: 200,
|
|
195
|
+
body: {
|
|
196
|
+
ok: true,
|
|
197
|
+
authorized: true,
|
|
198
|
+
authorityMode: "delegated_spend_credential",
|
|
199
|
+
authorityDecision: "authorized",
|
|
200
|
+
// The binding is the authority ref; its credential's bearer token is what the
|
|
201
|
+
// paying customer's agent presents to spend here. Opaque upstream.
|
|
202
|
+
spendAuthorityRef: binding.binding_id,
|
|
203
|
+
spendAuthorityToken: credentialView.bearer_token || null,
|
|
204
|
+
credentialRef: binding.credential_id || null,
|
|
205
|
+
identityBound: Boolean(credentialView.agent_key_ref),
|
|
206
|
+
boundUnits: quotedUnits,
|
|
207
|
+
proofMode: "credential_issued",
|
|
208
|
+
proofRef: binding.binding_id,
|
|
209
|
+
economicRef: binding.credential_id || null,
|
|
210
|
+
validUntil,
|
|
211
|
+
delegatedSpendAccepted: Boolean(b.delegatedSpend),
|
|
212
|
+
availableUnits: available,
|
|
213
|
+
quotedUnits,
|
|
214
|
+
capabilitySummary: [featureRef].filter(Boolean)
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// POST /v1/commerce/settle
|
|
220
|
+
// Server-side settlement for the trusted upstream seam: burn units against an account
|
|
221
|
+
// after it has executed the paid work. The commerce bearer IS the authority here (this is
|
|
222
|
+
// not a delegated-agent path), so there is no per-action bound — the account balance is
|
|
223
|
+
// the hard cap (consumeAccountCredits refuses an overdraw). Returns the raw consume
|
|
224
|
+
// result so an upstream caller reads the same credit_spend/usage_meter shape as the
|
|
225
|
+
// direct consume route.
|
|
226
|
+
function settleCommerceConsumption(state, body) {
|
|
227
|
+
const b = ensureObject(body);
|
|
228
|
+
const accountRef = normalizeString(b.accountRef || b.account_id);
|
|
229
|
+
if (!accountRef) return { http_status: 400, body: { ok: false, reason: "account_ref_required" } };
|
|
230
|
+
const units = Number(b.units);
|
|
231
|
+
if (!Number.isFinite(units) || units <= 0) {
|
|
232
|
+
return { http_status: 400, body: { ok: false, reason: "units_required" } };
|
|
233
|
+
}
|
|
234
|
+
const result = consumeAccountCredits(state, {
|
|
235
|
+
account_id: accountRef,
|
|
236
|
+
units,
|
|
237
|
+
task_ref: normalizeString(b.taskRef || b.task_ref),
|
|
238
|
+
workflow_ref: normalizeString(b.workflowRef || b.workflow_ref),
|
|
239
|
+
transaction_id: normalizeString(b.transactionRef || b.transaction_id),
|
|
240
|
+
quote_id: normalizeString(b.quoteRef || b.quote_id),
|
|
241
|
+
pack_id: normalizeString(b.packId || b.pack_id),
|
|
242
|
+
reason: normalizeString(b.reason, "commerce_settle")
|
|
243
|
+
});
|
|
244
|
+
if (result && result.ok === false) {
|
|
245
|
+
const http_status = result.reason === "insufficient_credits" ? 409 : 403;
|
|
246
|
+
return { http_status, body: result };
|
|
247
|
+
}
|
|
248
|
+
return { http_status: 200, body: result };
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// GET /v1/commerce/state
|
|
252
|
+
function inspectCommerceState(state, query) {
|
|
253
|
+
const accountRef = normalizeString(query && (query.accountRef || query.account_ref));
|
|
254
|
+
if (!accountRef) return { http_status: 400, body: { ok: false, reason: "account_ref_required" } };
|
|
255
|
+
const available = availableUnits(state, accountRef);
|
|
256
|
+
return {
|
|
257
|
+
http_status: 200,
|
|
258
|
+
body: {
|
|
259
|
+
ok: true,
|
|
260
|
+
accountRef,
|
|
261
|
+
account_ref: accountRef,
|
|
262
|
+
availableUnits: available,
|
|
263
|
+
available_units: available
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
module.exports = {
|
|
269
|
+
grantCommerceAllocation,
|
|
270
|
+
prepareCommerceExecution,
|
|
271
|
+
settleCommerceConsumption,
|
|
272
|
+
inspectCommerceState,
|
|
273
|
+
resolveCommerceUnits
|
|
274
|
+
};
|