xytara 3.1.7 → 3.1.9

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 (47) hide show
  1. package/README.md +1230 -1228
  2. package/RELEASE_NOTES.md +6 -8
  3. package/examples/generated.carried-handoff.json +3 -3
  4. package/lib/a2a_rpc.js +280 -0
  5. package/lib/account_auth.js +585 -518
  6. package/lib/agent_identity.js +162 -0
  7. package/lib/bolt_adapter.js +187 -0
  8. package/lib/bolt_payment_front.js +224 -172
  9. package/lib/checkout_processor_adapter.js +217 -0
  10. package/lib/command_flow.js +561 -411
  11. package/lib/commerce_artifacts.js +530 -503
  12. package/lib/commerce_bridge.js +274 -0
  13. package/lib/commerce_cases.js +399 -317
  14. package/lib/commerce_client.js +7694 -7687
  15. package/lib/commerce_runtime.js +322 -315
  16. package/lib/execution_dedupe.js +86 -0
  17. package/lib/external_credit_bridge.js +142 -142
  18. package/lib/external_execution_runtime.js +82 -34
  19. package/lib/http_transport.js +81 -73
  20. package/lib/l402_adapter.js +241 -0
  21. package/lib/l402_payment_front.js +265 -192
  22. package/lib/mpp_adapter.js +237 -0
  23. package/lib/payment_verification.js +52 -9
  24. package/lib/provider_network_contract.js +143 -0
  25. package/lib/provider_payout_execution.js +137 -0
  26. package/lib/provider_registry.js +666 -0
  27. package/lib/rate_limiter.js +81 -0
  28. package/lib/runtime_state_store.js +369 -354
  29. package/lib/stripe_mpp_payment_front.js +258 -158
  30. package/package.json +18 -3
  31. package/scripts/verify_a2a_rpc.js +105 -0
  32. package/scripts/verify_agent_identity.js +153 -0
  33. package/scripts/verify_bolt_adapter.js +128 -0
  34. package/scripts/verify_checkout_processor.js +109 -0
  35. package/scripts/verify_commerce_bridge.js +177 -0
  36. package/scripts/verify_execution_dedupe.js +189 -0
  37. package/scripts/verify_execution_surfacing.js +76 -0
  38. package/scripts/verify_external_execution_retry.js +113 -0
  39. package/scripts/verify_l402_adapter.js +86 -0
  40. package/scripts/verify_mpp_adapter.js +128 -0
  41. package/scripts/verify_provider_network.js +567 -0
  42. package/scripts/verify_rate_limiter.js +52 -0
  43. package/scripts/verify_refund_credit.js +106 -0
  44. package/scripts/verify_service.js +15421 -15410
  45. package/scripts/verify_settlement.js +116 -0
  46. package/scripts/verify_verify_execute_settle.js +208 -0
  47. package/server.js +684 -16
@@ -1,518 +1,585 @@
1
- "use strict";
2
-
3
- const crypto = require("crypto");
4
-
5
- function normalizeString(value, fallback = null) {
6
- const trimmed = typeof value === "string" ? value.trim() : "";
7
- return trimmed || fallback;
8
- }
9
-
10
- function ensureObject(value) {
11
- return value && typeof value === "object" && !Array.isArray(value) ? value : {};
12
- }
13
-
14
- function ensureArray(value) {
15
- return Array.isArray(value) ? value : [];
16
- }
17
-
18
- function nowIso() {
19
- return new Date().toISOString();
20
- }
21
-
22
- function buildCredentialPublicView(credential, includeToken = false) {
23
- if (!credential) return null;
24
- const view = {
25
- credential_id: credential.credential_id,
26
- account_id: credential.account_id,
27
- status: credential.status,
28
- spend_posture: credential.spend_posture,
29
- effective_pool_binding_mode: credential.entitlement_id ? "entitlement_bound" : credential.pack_id ? "pack_bound" : "unbound",
30
- scope: credential.scope,
31
- agent_id: credential.agent_id,
32
- budget_id: credential.budget_id,
33
- pack_id: credential.pack_id || null,
34
- entitlement_id: credential.entitlement_id || null,
35
- expires_at_iso: credential.expires_at_iso,
36
- created_at_iso: credential.created_at_iso,
37
- updated_at_iso: credential.updated_at_iso,
38
- issued_by: credential.issued_by || null,
39
- labels: ensureArray(credential.labels)
40
- };
41
- if (includeToken) {
42
- view.bearer_token = credential.bearer_token;
43
- }
44
- return view;
45
- }
46
-
47
- function buildAuthorityBindingPublicView(binding, credential, includeToken = false) {
48
- if (!binding) return null;
49
- const view = {
50
- binding_id: binding.binding_id,
51
- account_id: binding.account_id,
52
- status: binding.status,
53
- authority_kind: binding.authority_kind,
54
- spend_posture: binding.spend_posture,
55
- scope: binding.scope,
56
- authority_scope: ensureArray(binding.authority_scope),
57
- allowed_consequence_families: ensureArray(binding.allowed_consequence_families),
58
- consequence_bounds: binding.consequence_bounds || {
59
- max_commit_units: null,
60
- max_reserve_units: null,
61
- max_reversal_units: null
62
- },
63
- agent_id: binding.agent_id,
64
- budget_id: binding.budget_id,
65
- pack_id: binding.pack_id || null,
66
- entitlement_id: binding.entitlement_id || null,
67
- credential_id: binding.credential_id || null,
68
- issued_by: binding.issued_by || null,
69
- labels: ensureArray(binding.labels),
70
- expires_at_iso: binding.expires_at_iso || null,
71
- rotated_from_binding_id: binding.rotated_from_binding_id || null,
72
- replaced_by_binding_id: binding.replaced_by_binding_id || null,
73
- created_at_iso: binding.created_at_iso,
74
- updated_at_iso: binding.updated_at_iso,
75
- revoked_at_iso: binding.revoked_at_iso || null,
76
- revoke_reason: binding.revoke_reason || null,
77
- spend_credential: buildCredentialPublicView(credential, includeToken)
78
- };
79
- return view;
80
- }
81
-
82
- function buildAuthorityBindingContractSummary(binding, credential) {
83
- if (!binding) return null;
84
- const publicView = buildAuthorityBindingPublicView(binding, credential, false);
85
- return {
86
- summary_version: "xytara-authority-binding-contract-summary-v1",
87
- binding_id: binding.binding_id,
88
- account_id: binding.account_id,
89
- authority_kind: binding.authority_kind,
90
- spend_posture: binding.spend_posture,
91
- authority_scope: ensureArray(binding.authority_scope),
92
- allowed_consequence_families: ensureArray(binding.allowed_consequence_families),
93
- consequence_bounds: publicView.consequence_bounds,
94
- linked_credential_id: binding.credential_id || null,
95
- contract_state: binding.status === "active" ? "active_contract" : "inactive_contract",
96
- linked_surfaces: {
97
- binding_ref: `/v1/account-auth/authority-bindings/${encodeURIComponent(binding.binding_id)}`,
98
- spend_credential_ref: binding.credential_id ? `/v1/account-auth/spend-credentials/${encodeURIComponent(binding.credential_id)}` : null
99
- }
100
- };
101
- }
102
-
103
- function buildAuthorityBindingRotationSummary(binding, credential) {
104
- if (!binding) return null;
105
- const active = binding.status === "active";
106
- return {
107
- summary_version: "xytara-authority-binding-rotation-summary-v1",
108
- binding_id: binding.binding_id,
109
- account_id: binding.account_id,
110
- status: binding.status,
111
- renewable_state: active ? "renewable" : "inactive",
112
- rotatable_state: active ? "rotatable" : "inactive",
113
- expires_at_iso: binding.expires_at_iso || null,
114
- rotated_from_binding_id: binding.rotated_from_binding_id || null,
115
- replaced_by_binding_id: binding.replaced_by_binding_id || null,
116
- linked_credential_id: binding.credential_id || null,
117
- linked_surfaces: {
118
- binding_ref: `/v1/account-auth/authority-bindings/${encodeURIComponent(binding.binding_id)}`,
119
- contract_summary_ref: `/v1/account-auth/authority-bindings/${encodeURIComponent(binding.binding_id)}/contract-summary`,
120
- spend_credential_ref: binding.credential_id ? `/v1/account-auth/spend-credentials/${encodeURIComponent(binding.credential_id)}` : null
121
- }
122
- };
123
- }
124
-
125
- function isCredentialExpired(credential) {
126
- if (!credential || !credential.expires_at_iso) return false;
127
- const expiresAt = Date.parse(credential.expires_at_iso);
128
- return Number.isFinite(expiresAt) ? Date.now() >= expiresAt : false;
129
- }
130
-
131
- function createSpendCredential(state, body) {
132
- const payload = ensureObject(body);
133
- const credentialId = normalizeString(payload.credential_id, `spend_credential_${state.accountSpendCredentials.size + 1}`);
134
- const accountId = normalizeString(payload.account_id, "acct_demo");
135
- const agentId = normalizeString(payload.agent_id, null);
136
- const budgetId = normalizeString(payload.budget_id, null);
137
- const packId = normalizeString(payload.pack_id, null);
138
- const entitlementId = normalizeString(payload.entitlement_id, null);
139
- const createdAtIso = nowIso();
140
- const expiresAtIso = normalizeString(payload.expires_at_iso, null);
141
- const credential = {
142
- credential_id: credentialId,
143
- bearer_token: normalizeString(payload.bearer_token, `xytara_spend_${crypto.randomBytes(18).toString("hex")}`),
144
- account_id: accountId,
145
- agent_id: agentId,
146
- budget_id: budgetId,
147
- pack_id: packId,
148
- entitlement_id: entitlementId,
149
- spend_posture: agentId || budgetId ? "bounded_spend" : "open_spend",
150
- scope: normalizeString(payload.scope, "runtime_spend"),
151
- labels: ensureArray(payload.labels).map((value) => String(value || "").trim()).filter(Boolean),
152
- status: normalizeString(payload.status, "active"),
153
- issued_by: normalizeString(payload.issued_by, "operator"),
154
- expires_at_iso: expiresAtIso,
155
- created_at_iso: createdAtIso,
156
- updated_at_iso: createdAtIso,
157
- revoked_at_iso: null,
158
- revoke_reason: null
159
- };
160
- state.accountSpendCredentials.set(credentialId, credential);
161
- state.accountSpendCredentialsByToken.set(credential.bearer_token, credentialId);
162
- return buildCredentialPublicView(credential, true);
163
- }
164
-
165
- function createAuthorityBinding(state, body) {
166
- const payload = ensureObject(body);
167
- const bindingId = normalizeString(payload.binding_id, `authority_binding_${state.accountAuthorityBindings.size + 1}`);
168
- const credential = createSpendCredential(state, {
169
- credential_id: normalizeString(payload.credential_id, `spend_for_${bindingId}`),
170
- bearer_token: normalizeString(payload.bearer_token, null),
171
- account_id: normalizeString(payload.account_id, "acct_demo"),
172
- agent_id: normalizeString(payload.agent_id, null),
173
- budget_id: normalizeString(payload.budget_id, null),
174
- pack_id: normalizeString(payload.pack_id, null),
175
- entitlement_id: normalizeString(payload.entitlement_id, null),
176
- scope: normalizeString(payload.scope, "runtime_spend"),
177
- labels: ensureArray(payload.labels),
178
- status: normalizeString(payload.status, "active"),
179
- issued_by: normalizeString(payload.issued_by, "operator"),
180
- expires_at_iso: normalizeString(payload.expires_at_iso, null)
181
- });
182
- const createdAtIso = nowIso();
183
- const binding = {
184
- binding_id: bindingId,
185
- account_id: credential.account_id,
186
- credential_id: credential.credential_id,
187
- authority_kind: normalizeString(payload.authority_kind, "delegated_runtime_spend"),
188
- spend_posture: credential.spend_posture,
189
- scope: credential.scope,
190
- authority_scope: ensureArray(payload.authority_scope).map((value) => String(value || "").trim()).filter(Boolean),
191
- allowed_consequence_families: ensureArray(payload.allowed_consequence_families).map((value) => String(value || "").trim()).filter(Boolean),
192
- consequence_bounds: {
193
- max_commit_units: Number.isFinite(Number(payload.max_commit_units)) ? Number(payload.max_commit_units) : null,
194
- max_reserve_units: Number.isFinite(Number(payload.max_reserve_units)) ? Number(payload.max_reserve_units) : null,
195
- max_reversal_units: Number.isFinite(Number(payload.max_reversal_units)) ? Number(payload.max_reversal_units) : null
196
- },
197
- agent_id: credential.agent_id,
198
- budget_id: credential.budget_id,
199
- pack_id: credential.pack_id || null,
200
- entitlement_id: credential.entitlement_id || null,
201
- status: normalizeString(payload.status, "active"),
202
- issued_by: normalizeString(payload.issued_by, "operator"),
203
- labels: ensureArray(payload.labels),
204
- expires_at_iso: credential.expires_at_iso,
205
- rotated_from_binding_id: normalizeString(payload.rotated_from_binding_id, null),
206
- replaced_by_binding_id: normalizeString(payload.replaced_by_binding_id, null),
207
- created_at_iso: createdAtIso,
208
- updated_at_iso: createdAtIso,
209
- revoked_at_iso: null,
210
- revoke_reason: null
211
- };
212
- state.accountAuthorityBindings.set(bindingId, binding);
213
- return buildAuthorityBindingPublicView(binding, state.accountSpendCredentials.get(credential.credential_id), true);
214
- }
215
-
216
- function listSpendCredentials(state, filters) {
217
- const payload = ensureObject(filters);
218
- const accountId = normalizeString(payload.account_id, null);
219
- const status = normalizeString(payload.status, null);
220
- return Array.from(state.accountSpendCredentials.values())
221
- .filter((credential) => {
222
- if (accountId && credential.account_id !== accountId) return false;
223
- if (status && credential.status !== status) return false;
224
- return true;
225
- })
226
- .map((credential) => buildCredentialPublicView(credential, false));
227
- }
228
-
229
- function getSpendCredential(state, credentialId) {
230
- if (!credentialId || !state.accountSpendCredentials.has(credentialId)) return null;
231
- return buildCredentialPublicView(state.accountSpendCredentials.get(credentialId), false);
232
- }
233
-
234
- function listAuthorityBindings(state, filters) {
235
- const payload = ensureObject(filters);
236
- const accountId = normalizeString(payload.account_id, null);
237
- const status = normalizeString(payload.status, null);
238
- return Array.from(state.accountAuthorityBindings.values())
239
- .filter((binding) => {
240
- if (accountId && binding.account_id !== accountId) return false;
241
- if (status && binding.status !== status) return false;
242
- return true;
243
- })
244
- .map((binding) => buildAuthorityBindingPublicView(binding, state.accountSpendCredentials.get(binding.credential_id), false));
245
- }
246
-
247
- function getAuthorityBinding(state, bindingId) {
248
- if (!bindingId || !state.accountAuthorityBindings.has(bindingId)) return null;
249
- const binding = state.accountAuthorityBindings.get(bindingId);
250
- return buildAuthorityBindingPublicView(binding, state.accountSpendCredentials.get(binding.credential_id), false);
251
- }
252
-
253
- function getAuthorityBindingContractSummary(state, bindingId) {
254
- if (!bindingId || !state.accountAuthorityBindings.has(bindingId)) return null;
255
- const binding = state.accountAuthorityBindings.get(bindingId);
256
- return buildAuthorityBindingContractSummary(binding, state.accountSpendCredentials.get(binding.credential_id));
257
- }
258
-
259
- function getAuthorityBindingRotationSummary(state, bindingId) {
260
- if (!bindingId || !state.accountAuthorityBindings.has(bindingId)) return null;
261
- const binding = state.accountAuthorityBindings.get(bindingId);
262
- return buildAuthorityBindingRotationSummary(binding, state.accountSpendCredentials.get(binding.credential_id));
263
- }
264
-
265
- function evaluateAuthorityBindingAction(binding, action, units) {
266
- const target = binding && typeof binding === "object" ? binding : null;
267
- const numericUnits = Number.isFinite(Number(units)) ? Number(units) : 0;
268
- const allowedScopes = target ? ensureArray(target.authority_scope) : [];
269
- const allowedFamilies = target ? ensureArray(target.allowed_consequence_families) : [];
270
- const bounds = target && target.consequence_bounds ? target.consequence_bounds : {};
271
-
272
- if (!target) {
273
- return { ok: true };
274
- }
275
- if (target.status !== "active") {
276
- return { ok: false, reason: "authority_binding_inactive", binding_id: target.binding_id };
277
- }
278
-
279
- const scopeMap = {
280
- delegated_credit_spend: "runtime.execute",
281
- reserve: "economics.reserve",
282
- release: "economics.release",
283
- reverse: "economics.reverse"
284
- };
285
- const familyMap = {
286
- delegated_credit_spend: "commit",
287
- reserve: "reserve",
288
- release: "release",
289
- reverse: "reverse"
290
- };
291
- const boundKeyMap = {
292
- delegated_credit_spend: "max_commit_units",
293
- reserve: "max_reserve_units",
294
- reverse: "max_reversal_units"
295
- };
296
-
297
- const requiredScope = scopeMap[action] || null;
298
- if (requiredScope && allowedScopes.length > 0 && !allowedScopes.includes(requiredScope)) {
299
- return {
300
- ok: false,
301
- reason: "authority_scope_not_allowed",
302
- binding_id: target.binding_id,
303
- required_scope: requiredScope,
304
- authority_scope: allowedScopes
305
- };
306
- }
307
-
308
- const requiredFamily = familyMap[action] || null;
309
- if (requiredFamily && allowedFamilies.length > 0 && !allowedFamilies.includes(requiredFamily)) {
310
- return {
311
- ok: false,
312
- reason: "authority_consequence_family_not_allowed",
313
- binding_id: target.binding_id,
314
- required_consequence_family: requiredFamily,
315
- allowed_consequence_families: allowedFamilies
316
- };
317
- }
318
-
319
- const boundKey = boundKeyMap[action] || null;
320
- if (boundKey && Number.isFinite(Number(bounds[boundKey])) && numericUnits > Number(bounds[boundKey])) {
321
- return {
322
- ok: false,
323
- reason: "authority_consequence_bound_exceeded",
324
- binding_id: target.binding_id,
325
- bound_key: boundKey,
326
- max_units: Number(bounds[boundKey]),
327
- attempted_units: numericUnits
328
- };
329
- }
330
-
331
- return {
332
- ok: true,
333
- binding_id: target.binding_id,
334
- authority_scope: allowedScopes,
335
- allowed_consequence_families: allowedFamilies,
336
- consequence_bounds: {
337
- max_commit_units: Number.isFinite(Number(bounds.max_commit_units)) ? Number(bounds.max_commit_units) : null,
338
- max_reserve_units: Number.isFinite(Number(bounds.max_reserve_units)) ? Number(bounds.max_reserve_units) : null,
339
- max_reversal_units: Number.isFinite(Number(bounds.max_reversal_units)) ? Number(bounds.max_reversal_units) : null
340
- }
341
- };
342
- }
343
-
344
- function revokeSpendCredential(state, credentialId, body) {
345
- if (!credentialId || !state.accountSpendCredentials.has(credentialId)) return null;
346
- const payload = ensureObject(body);
347
- const current = state.accountSpendCredentials.get(credentialId);
348
- const next = {
349
- ...current,
350
- status: "revoked",
351
- revoked_at_iso: nowIso(),
352
- revoke_reason: normalizeString(payload.reason, "operator_revoked"),
353
- updated_at_iso: nowIso()
354
- };
355
- state.accountSpendCredentials.set(credentialId, next);
356
- return buildCredentialPublicView(next, false);
357
- }
358
-
359
- function revokeAuthorityBinding(state, bindingId, body) {
360
- if (!bindingId || !state.accountAuthorityBindings.has(bindingId)) return null;
361
- const payload = ensureObject(body);
362
- const current = state.accountAuthorityBindings.get(bindingId);
363
- const next = {
364
- ...current,
365
- status: "revoked",
366
- revoked_at_iso: nowIso(),
367
- revoke_reason: normalizeString(payload.reason, "operator_revoked"),
368
- updated_at_iso: nowIso()
369
- };
370
- state.accountAuthorityBindings.set(bindingId, next);
371
- if (current.credential_id) {
372
- revokeSpendCredential(state, current.credential_id, payload);
373
- }
374
- return buildAuthorityBindingPublicView(next, current.credential_id ? state.accountSpendCredentials.get(current.credential_id) : null, false);
375
- }
376
-
377
- function renewAuthorityBinding(state, bindingId, body) {
378
- if (!bindingId || !state.accountAuthorityBindings.has(bindingId)) return null;
379
- const payload = ensureObject(body);
380
- const current = state.accountAuthorityBindings.get(bindingId);
381
- const nextExpiresAtIso = normalizeString(payload.expires_at_iso, current.expires_at_iso || null);
382
- const updatedAtIso = nowIso();
383
- const next = {
384
- ...current,
385
- expires_at_iso: nextExpiresAtIso,
386
- updated_at_iso: updatedAtIso
387
- };
388
- state.accountAuthorityBindings.set(bindingId, next);
389
- if (current.credential_id && state.accountSpendCredentials.has(current.credential_id)) {
390
- const credential = state.accountSpendCredentials.get(current.credential_id);
391
- state.accountSpendCredentials.set(current.credential_id, {
392
- ...credential,
393
- expires_at_iso: nextExpiresAtIso,
394
- updated_at_iso: updatedAtIso
395
- });
396
- }
397
- return buildAuthorityBindingPublicView(next, current.credential_id ? state.accountSpendCredentials.get(current.credential_id) : null, false);
398
- }
399
-
400
- function rotateAuthorityBinding(state, bindingId, body) {
401
- if (!bindingId || !state.accountAuthorityBindings.has(bindingId)) return null;
402
- const payload = ensureObject(body);
403
- const current = state.accountAuthorityBindings.get(bindingId);
404
- const currentCredential = current.credential_id ? state.accountSpendCredentials.get(current.credential_id) : null;
405
- const successorBindingId = normalizeString(payload.successor_binding_id, `${bindingId}_rotated`);
406
- const successorCredentialId = normalizeString(payload.successor_credential_id, current.credential_id ? `${current.credential_id}_rotated` : `spend_for_${successorBindingId}`);
407
- const successor = createAuthorityBinding(state, {
408
- binding_id: successorBindingId,
409
- credential_id: successorCredentialId,
410
- bearer_token: normalizeString(payload.bearer_token, null),
411
- account_id: current.account_id,
412
- agent_id: normalizeString(payload.agent_id, current.agent_id),
413
- budget_id: normalizeString(payload.budget_id, current.budget_id),
414
- pack_id: normalizeString(payload.pack_id, current.pack_id),
415
- entitlement_id: normalizeString(payload.entitlement_id, current.entitlement_id),
416
- scope: normalizeString(payload.scope, current.scope),
417
- authority_kind: normalizeString(payload.authority_kind, current.authority_kind),
418
- authority_scope: ensureArray(payload.authority_scope).length > 0 ? ensureArray(payload.authority_scope) : ensureArray(current.authority_scope),
419
- allowed_consequence_families: ensureArray(payload.allowed_consequence_families).length > 0 ? ensureArray(payload.allowed_consequence_families) : ensureArray(current.allowed_consequence_families),
420
- max_commit_units: Number.isFinite(Number(payload.max_commit_units)) ? Number(payload.max_commit_units) : current.consequence_bounds.max_commit_units,
421
- max_reserve_units: Number.isFinite(Number(payload.max_reserve_units)) ? Number(payload.max_reserve_units) : current.consequence_bounds.max_reserve_units,
422
- max_reversal_units: Number.isFinite(Number(payload.max_reversal_units)) ? Number(payload.max_reversal_units) : current.consequence_bounds.max_reversal_units,
423
- labels: ensureArray(payload.labels).length > 0 ? ensureArray(payload.labels) : ensureArray(current.labels),
424
- issued_by: normalizeString(payload.issued_by, current.issued_by || "operator"),
425
- expires_at_iso: normalizeString(payload.expires_at_iso, current.expires_at_iso || (currentCredential ? currentCredential.expires_at_iso : null)),
426
- rotated_from_binding_id: current.binding_id
427
- });
428
- const revoked = revokeAuthorityBinding(state, bindingId, {
429
- reason: normalizeString(payload.reason, "rotated_to_successor")
430
- });
431
- const successorRecord = state.accountAuthorityBindings.get(successor.binding_id);
432
- state.accountAuthorityBindings.set(successor.binding_id, {
433
- ...successorRecord,
434
- rotated_from_binding_id: current.binding_id
435
- });
436
- state.accountAuthorityBindings.set(bindingId, {
437
- ...state.accountAuthorityBindings.get(bindingId),
438
- replaced_by_binding_id: successor.binding_id
439
- });
440
- return {
441
- rotated_binding: buildAuthorityBindingPublicView(state.accountAuthorityBindings.get(bindingId), current.credential_id ? state.accountSpendCredentials.get(current.credential_id) : null, false),
442
- successor_authority_binding: buildAuthorityBindingPublicView(state.accountAuthorityBindings.get(successor.binding_id), state.accountSpendCredentials.get(successor.credential_id), true),
443
- previous_view: revoked
444
- };
445
- }
446
-
447
- function resolveSpendCredential(state, bearerToken) {
448
- const token = normalizeString(bearerToken, null);
449
- if (!token) {
450
- return {
451
- ok: false,
452
- reason: "missing_spend_credential"
453
- };
454
- }
455
- const credentialId = state.accountSpendCredentialsByToken.get(token);
456
- if (!credentialId || !state.accountSpendCredentials.has(credentialId)) {
457
- return {
458
- ok: false,
459
- reason: "spend_credential_not_found"
460
- };
461
- }
462
- const credential = state.accountSpendCredentials.get(credentialId);
463
- if (credential.status !== "active") {
464
- return {
465
- ok: false,
466
- reason: "spend_credential_inactive",
467
- credential: buildCredentialPublicView(credential, false)
468
- };
469
- }
470
- if (isCredentialExpired(credential)) {
471
- return {
472
- ok: false,
473
- reason: "spend_credential_expired",
474
- credential: buildCredentialPublicView(credential, false)
475
- };
476
- }
477
- const binding = Array.from(state.accountAuthorityBindings.values()).find((entry) => entry && entry.credential_id === credentialId && entry.status === "active") || null;
478
- return {
479
- ok: true,
480
- credential,
481
- binding,
482
- authorization_context: {
483
- verification_mode: "delegated_spend_credential",
484
- wallet_id: credential.credential_id,
485
- payment_payload: {
486
- binding_id: binding ? binding.binding_id : null,
487
- credential_id: credential.credential_id,
488
- spend_posture: credential.spend_posture,
489
- pack_id: credential.pack_id || null,
490
- entitlement_id: credential.entitlement_id || null,
491
- authority_scope: binding ? ensureArray(binding.authority_scope) : [],
492
- allowed_consequence_families: binding ? ensureArray(binding.allowed_consequence_families) : [],
493
- consequence_bounds: binding && binding.consequence_bounds ? binding.consequence_bounds : {
494
- max_commit_units: null,
495
- max_reserve_units: null,
496
- max_reversal_units: null
497
- }
498
- }
499
- }
500
- };
501
- }
502
-
503
- module.exports = {
504
- createAuthorityBinding,
505
- createSpendCredential,
506
- evaluateAuthorityBindingAction,
507
- getAuthorityBinding,
508
- getAuthorityBindingContractSummary,
509
- getAuthorityBindingRotationSummary,
510
- getSpendCredential,
511
- listAuthorityBindings,
512
- listSpendCredentials,
513
- renewAuthorityBinding,
514
- resolveSpendCredential,
515
- rotateAuthorityBinding,
516
- revokeAuthorityBinding,
517
- revokeSpendCredential
518
- };
1
+ "use strict";
2
+
3
+ const crypto = require("crypto");
4
+ const { normalizeAgentPublicKey, verifySpendAuthProof } = require("./agent_identity");
5
+
6
+ function normalizeString(value, fallback = null) {
7
+ const trimmed = typeof value === "string" ? value.trim() : "";
8
+ return trimmed || fallback;
9
+ }
10
+
11
+ function ensureObject(value) {
12
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
13
+ }
14
+
15
+ function ensureArray(value) {
16
+ return Array.isArray(value) ? value : [];
17
+ }
18
+
19
+ function nowIso() {
20
+ return new Date().toISOString();
21
+ }
22
+
23
+ function buildCredentialPublicView(credential, includeToken = false) {
24
+ if (!credential) return null;
25
+ const view = {
26
+ credential_id: credential.credential_id,
27
+ account_id: credential.account_id,
28
+ status: credential.status,
29
+ spend_posture: credential.spend_posture,
30
+ effective_pool_binding_mode: credential.entitlement_id ? "entitlement_bound" : credential.pack_id ? "pack_bound" : "unbound",
31
+ scope: credential.scope,
32
+ agent_id: credential.agent_id,
33
+ budget_id: credential.budget_id,
34
+ pack_id: credential.pack_id || null,
35
+ entitlement_id: credential.entitlement_id || null,
36
+ expires_at_iso: credential.expires_at_iso,
37
+ created_at_iso: credential.created_at_iso,
38
+ updated_at_iso: credential.updated_at_iso,
39
+ issued_by: credential.issued_by || null,
40
+ labels: ensureArray(credential.labels),
41
+ // Cryptographic identity: when a credential is bound to an agent ed25519 key,
42
+ // using it requires a fresh signed proof (not just the bearer token).
43
+ identity_bound: Boolean(credential.agent_public_key),
44
+ agent_key_ref: credential.agent_key_ref || null
45
+ };
46
+ if (includeToken) {
47
+ view.bearer_token = credential.bearer_token;
48
+ }
49
+ return view;
50
+ }
51
+
52
+ function buildAuthorityBindingPublicView(binding, credential, includeToken = false) {
53
+ if (!binding) return null;
54
+ const view = {
55
+ binding_id: binding.binding_id,
56
+ account_id: binding.account_id,
57
+ status: binding.status,
58
+ authority_kind: binding.authority_kind,
59
+ spend_posture: binding.spend_posture,
60
+ scope: binding.scope,
61
+ authority_scope: ensureArray(binding.authority_scope),
62
+ allowed_consequence_families: ensureArray(binding.allowed_consequence_families),
63
+ consequence_bounds: binding.consequence_bounds || {
64
+ max_commit_units: null,
65
+ max_reserve_units: null,
66
+ max_reversal_units: null
67
+ },
68
+ agent_id: binding.agent_id,
69
+ budget_id: binding.budget_id,
70
+ pack_id: binding.pack_id || null,
71
+ entitlement_id: binding.entitlement_id || null,
72
+ credential_id: binding.credential_id || null,
73
+ issued_by: binding.issued_by || null,
74
+ labels: ensureArray(binding.labels),
75
+ expires_at_iso: binding.expires_at_iso || null,
76
+ rotated_from_binding_id: binding.rotated_from_binding_id || null,
77
+ replaced_by_binding_id: binding.replaced_by_binding_id || null,
78
+ created_at_iso: binding.created_at_iso,
79
+ updated_at_iso: binding.updated_at_iso,
80
+ revoked_at_iso: binding.revoked_at_iso || null,
81
+ revoke_reason: binding.revoke_reason || null,
82
+ spend_credential: buildCredentialPublicView(credential, includeToken)
83
+ };
84
+ return view;
85
+ }
86
+
87
+ function buildAuthorityBindingContractSummary(binding, credential) {
88
+ if (!binding) return null;
89
+ const publicView = buildAuthorityBindingPublicView(binding, credential, false);
90
+ return {
91
+ summary_version: "xytara-authority-binding-contract-summary-v1",
92
+ binding_id: binding.binding_id,
93
+ account_id: binding.account_id,
94
+ authority_kind: binding.authority_kind,
95
+ spend_posture: binding.spend_posture,
96
+ authority_scope: ensureArray(binding.authority_scope),
97
+ allowed_consequence_families: ensureArray(binding.allowed_consequence_families),
98
+ consequence_bounds: publicView.consequence_bounds,
99
+ linked_credential_id: binding.credential_id || null,
100
+ contract_state: binding.status === "active" ? "active_contract" : "inactive_contract",
101
+ linked_surfaces: {
102
+ binding_ref: `/v1/account-auth/authority-bindings/${encodeURIComponent(binding.binding_id)}`,
103
+ spend_credential_ref: binding.credential_id ? `/v1/account-auth/spend-credentials/${encodeURIComponent(binding.credential_id)}` : null
104
+ }
105
+ };
106
+ }
107
+
108
+ function buildAuthorityBindingRotationSummary(binding, credential) {
109
+ if (!binding) return null;
110
+ const active = binding.status === "active";
111
+ return {
112
+ summary_version: "xytara-authority-binding-rotation-summary-v1",
113
+ binding_id: binding.binding_id,
114
+ account_id: binding.account_id,
115
+ status: binding.status,
116
+ renewable_state: active ? "renewable" : "inactive",
117
+ rotatable_state: active ? "rotatable" : "inactive",
118
+ expires_at_iso: binding.expires_at_iso || null,
119
+ rotated_from_binding_id: binding.rotated_from_binding_id || null,
120
+ replaced_by_binding_id: binding.replaced_by_binding_id || null,
121
+ linked_credential_id: binding.credential_id || null,
122
+ linked_surfaces: {
123
+ binding_ref: `/v1/account-auth/authority-bindings/${encodeURIComponent(binding.binding_id)}`,
124
+ contract_summary_ref: `/v1/account-auth/authority-bindings/${encodeURIComponent(binding.binding_id)}/contract-summary`,
125
+ spend_credential_ref: binding.credential_id ? `/v1/account-auth/spend-credentials/${encodeURIComponent(binding.credential_id)}` : null
126
+ }
127
+ };
128
+ }
129
+
130
+ function isCredentialExpired(credential) {
131
+ if (!credential || !credential.expires_at_iso) return false;
132
+ const expiresAt = Date.parse(credential.expires_at_iso);
133
+ return Number.isFinite(expiresAt) ? Date.now() >= expiresAt : false;
134
+ }
135
+
136
+ function createSpendCredential(state, body) {
137
+ const payload = ensureObject(body);
138
+ const credentialId = normalizeString(payload.credential_id, `spend_credential_${state.accountSpendCredentials.size + 1}`);
139
+ const accountId = normalizeString(payload.account_id, "acct_demo");
140
+ const agentId = normalizeString(payload.agent_id, null);
141
+ const budgetId = normalizeString(payload.budget_id, null);
142
+ const packId = normalizeString(payload.pack_id, null);
143
+ const entitlementId = normalizeString(payload.entitlement_id, null);
144
+ const createdAtIso = nowIso();
145
+ const expiresAtIso = normalizeString(payload.expires_at_iso, null);
146
+ // Optional cryptographic identity binding: an ed25519 agent public key. When
147
+ // set, the credential can only be USED with a fresh signature from that key.
148
+ // Only a VALID key is bound — an unparseable key is ignored (no brick / no
149
+ // inconsistent identity_bound=true with a null ref); routes should reject an
150
+ // invalid key up front so the operator sees the error.
151
+ const agentPublicKeyRaw = normalizeString(payload.agent_public_key, null);
152
+ const agentKeyMaterial = agentPublicKeyRaw ? normalizeAgentPublicKey(agentPublicKeyRaw) : null;
153
+ const agentPublicKey = agentKeyMaterial ? agentPublicKeyRaw : null;
154
+ const agentKeyRef = agentKeyMaterial ? agentKeyMaterial.key_ref : null;
155
+ const credential = {
156
+ credential_id: credentialId,
157
+ bearer_token: normalizeString(payload.bearer_token, `xytara_spend_${crypto.randomBytes(18).toString("hex")}`),
158
+ agent_public_key: agentPublicKey,
159
+ agent_key_ref: agentKeyRef,
160
+ account_id: accountId,
161
+ agent_id: agentId,
162
+ budget_id: budgetId,
163
+ pack_id: packId,
164
+ entitlement_id: entitlementId,
165
+ spend_posture: agentId || budgetId ? "bounded_spend" : "open_spend",
166
+ scope: normalizeString(payload.scope, "runtime_spend"),
167
+ labels: ensureArray(payload.labels).map((value) => String(value || "").trim()).filter(Boolean),
168
+ status: normalizeString(payload.status, "active"),
169
+ issued_by: normalizeString(payload.issued_by, "operator"),
170
+ expires_at_iso: expiresAtIso,
171
+ created_at_iso: createdAtIso,
172
+ updated_at_iso: createdAtIso,
173
+ revoked_at_iso: null,
174
+ revoke_reason: null
175
+ };
176
+ state.accountSpendCredentials.set(credentialId, credential);
177
+ state.accountSpendCredentialsByToken.set(credential.bearer_token, credentialId);
178
+ return buildCredentialPublicView(credential, true);
179
+ }
180
+
181
+ function createAuthorityBinding(state, body) {
182
+ const payload = ensureObject(body);
183
+ const bindingId = normalizeString(payload.binding_id, `authority_binding_${state.accountAuthorityBindings.size + 1}`);
184
+ const credential = createSpendCredential(state, {
185
+ credential_id: normalizeString(payload.credential_id, `spend_for_${bindingId}`),
186
+ bearer_token: normalizeString(payload.bearer_token, null),
187
+ agent_public_key: normalizeString(payload.agent_public_key, null),
188
+ account_id: normalizeString(payload.account_id, "acct_demo"),
189
+ agent_id: normalizeString(payload.agent_id, null),
190
+ budget_id: normalizeString(payload.budget_id, null),
191
+ pack_id: normalizeString(payload.pack_id, null),
192
+ entitlement_id: normalizeString(payload.entitlement_id, null),
193
+ scope: normalizeString(payload.scope, "runtime_spend"),
194
+ labels: ensureArray(payload.labels),
195
+ status: normalizeString(payload.status, "active"),
196
+ issued_by: normalizeString(payload.issued_by, "operator"),
197
+ expires_at_iso: normalizeString(payload.expires_at_iso, null)
198
+ });
199
+ const createdAtIso = nowIso();
200
+ const binding = {
201
+ binding_id: bindingId,
202
+ account_id: credential.account_id,
203
+ credential_id: credential.credential_id,
204
+ authority_kind: normalizeString(payload.authority_kind, "delegated_runtime_spend"),
205
+ spend_posture: credential.spend_posture,
206
+ scope: credential.scope,
207
+ authority_scope: ensureArray(payload.authority_scope).map((value) => String(value || "").trim()).filter(Boolean),
208
+ allowed_consequence_families: ensureArray(payload.allowed_consequence_families).map((value) => String(value || "").trim()).filter(Boolean),
209
+ consequence_bounds: {
210
+ max_commit_units: Number.isFinite(Number(payload.max_commit_units)) ? Number(payload.max_commit_units) : null,
211
+ max_reserve_units: Number.isFinite(Number(payload.max_reserve_units)) ? Number(payload.max_reserve_units) : null,
212
+ max_reversal_units: Number.isFinite(Number(payload.max_reversal_units)) ? Number(payload.max_reversal_units) : null
213
+ },
214
+ agent_id: credential.agent_id,
215
+ budget_id: credential.budget_id,
216
+ pack_id: credential.pack_id || null,
217
+ entitlement_id: credential.entitlement_id || null,
218
+ status: normalizeString(payload.status, "active"),
219
+ issued_by: normalizeString(payload.issued_by, "operator"),
220
+ labels: ensureArray(payload.labels),
221
+ expires_at_iso: credential.expires_at_iso,
222
+ rotated_from_binding_id: normalizeString(payload.rotated_from_binding_id, null),
223
+ replaced_by_binding_id: normalizeString(payload.replaced_by_binding_id, null),
224
+ created_at_iso: createdAtIso,
225
+ updated_at_iso: createdAtIso,
226
+ revoked_at_iso: null,
227
+ revoke_reason: null
228
+ };
229
+ state.accountAuthorityBindings.set(bindingId, binding);
230
+ return buildAuthorityBindingPublicView(binding, state.accountSpendCredentials.get(credential.credential_id), true);
231
+ }
232
+
233
+ function listSpendCredentials(state, filters) {
234
+ const payload = ensureObject(filters);
235
+ const accountId = normalizeString(payload.account_id, null);
236
+ const status = normalizeString(payload.status, null);
237
+ return Array.from(state.accountSpendCredentials.values())
238
+ .filter((credential) => {
239
+ if (accountId && credential.account_id !== accountId) return false;
240
+ if (status && credential.status !== status) return false;
241
+ return true;
242
+ })
243
+ .map((credential) => buildCredentialPublicView(credential, false));
244
+ }
245
+
246
+ function getSpendCredential(state, credentialId) {
247
+ if (!credentialId || !state.accountSpendCredentials.has(credentialId)) return null;
248
+ return buildCredentialPublicView(state.accountSpendCredentials.get(credentialId), false);
249
+ }
250
+
251
+ function listAuthorityBindings(state, filters) {
252
+ const payload = ensureObject(filters);
253
+ const accountId = normalizeString(payload.account_id, null);
254
+ const status = normalizeString(payload.status, null);
255
+ return Array.from(state.accountAuthorityBindings.values())
256
+ .filter((binding) => {
257
+ if (accountId && binding.account_id !== accountId) return false;
258
+ if (status && binding.status !== status) return false;
259
+ return true;
260
+ })
261
+ .map((binding) => buildAuthorityBindingPublicView(binding, state.accountSpendCredentials.get(binding.credential_id), false));
262
+ }
263
+
264
+ function getAuthorityBinding(state, bindingId) {
265
+ if (!bindingId || !state.accountAuthorityBindings.has(bindingId)) return null;
266
+ const binding = state.accountAuthorityBindings.get(bindingId);
267
+ return buildAuthorityBindingPublicView(binding, state.accountSpendCredentials.get(binding.credential_id), false);
268
+ }
269
+
270
+ function getAuthorityBindingContractSummary(state, bindingId) {
271
+ if (!bindingId || !state.accountAuthorityBindings.has(bindingId)) return null;
272
+ const binding = state.accountAuthorityBindings.get(bindingId);
273
+ return buildAuthorityBindingContractSummary(binding, state.accountSpendCredentials.get(binding.credential_id));
274
+ }
275
+
276
+ function getAuthorityBindingRotationSummary(state, bindingId) {
277
+ if (!bindingId || !state.accountAuthorityBindings.has(bindingId)) return null;
278
+ const binding = state.accountAuthorityBindings.get(bindingId);
279
+ return buildAuthorityBindingRotationSummary(binding, state.accountSpendCredentials.get(binding.credential_id));
280
+ }
281
+
282
+ function evaluateAuthorityBindingAction(binding, action, units) {
283
+ const target = binding && typeof binding === "object" ? binding : null;
284
+ const numericUnits = Number.isFinite(Number(units)) ? Number(units) : 0;
285
+ const allowedScopes = target ? ensureArray(target.authority_scope) : [];
286
+ const allowedFamilies = target ? ensureArray(target.allowed_consequence_families) : [];
287
+ const bounds = target && target.consequence_bounds ? target.consequence_bounds : {};
288
+
289
+ if (!target) {
290
+ return { ok: true };
291
+ }
292
+ if (target.status !== "active") {
293
+ return { ok: false, reason: "authority_binding_inactive", binding_id: target.binding_id };
294
+ }
295
+
296
+ const scopeMap = {
297
+ delegated_credit_spend: "runtime.execute",
298
+ reserve: "economics.reserve",
299
+ release: "economics.release",
300
+ reverse: "economics.reverse"
301
+ };
302
+ const familyMap = {
303
+ delegated_credit_spend: "commit",
304
+ reserve: "reserve",
305
+ release: "release",
306
+ reverse: "reverse"
307
+ };
308
+ const boundKeyMap = {
309
+ delegated_credit_spend: "max_commit_units",
310
+ reserve: "max_reserve_units",
311
+ reverse: "max_reversal_units"
312
+ };
313
+
314
+ const requiredScope = scopeMap[action] || null;
315
+ if (requiredScope && allowedScopes.length > 0 && !allowedScopes.includes(requiredScope)) {
316
+ return {
317
+ ok: false,
318
+ reason: "authority_scope_not_allowed",
319
+ binding_id: target.binding_id,
320
+ required_scope: requiredScope,
321
+ authority_scope: allowedScopes
322
+ };
323
+ }
324
+
325
+ const requiredFamily = familyMap[action] || null;
326
+ if (requiredFamily && allowedFamilies.length > 0 && !allowedFamilies.includes(requiredFamily)) {
327
+ return {
328
+ ok: false,
329
+ reason: "authority_consequence_family_not_allowed",
330
+ binding_id: target.binding_id,
331
+ required_consequence_family: requiredFamily,
332
+ allowed_consequence_families: allowedFamilies
333
+ };
334
+ }
335
+
336
+ const boundKey = boundKeyMap[action] || null;
337
+ if (boundKey && Number.isFinite(Number(bounds[boundKey])) && numericUnits > Number(bounds[boundKey])) {
338
+ return {
339
+ ok: false,
340
+ reason: "authority_consequence_bound_exceeded",
341
+ binding_id: target.binding_id,
342
+ bound_key: boundKey,
343
+ max_units: Number(bounds[boundKey]),
344
+ attempted_units: numericUnits
345
+ };
346
+ }
347
+
348
+ return {
349
+ ok: true,
350
+ binding_id: target.binding_id,
351
+ authority_scope: allowedScopes,
352
+ allowed_consequence_families: allowedFamilies,
353
+ consequence_bounds: {
354
+ max_commit_units: Number.isFinite(Number(bounds.max_commit_units)) ? Number(bounds.max_commit_units) : null,
355
+ max_reserve_units: Number.isFinite(Number(bounds.max_reserve_units)) ? Number(bounds.max_reserve_units) : null,
356
+ max_reversal_units: Number.isFinite(Number(bounds.max_reversal_units)) ? Number(bounds.max_reversal_units) : null
357
+ }
358
+ };
359
+ }
360
+
361
+ function revokeSpendCredential(state, credentialId, body) {
362
+ if (!credentialId || !state.accountSpendCredentials.has(credentialId)) return null;
363
+ const payload = ensureObject(body);
364
+ const current = state.accountSpendCredentials.get(credentialId);
365
+ const next = {
366
+ ...current,
367
+ status: "revoked",
368
+ revoked_at_iso: nowIso(),
369
+ revoke_reason: normalizeString(payload.reason, "operator_revoked"),
370
+ updated_at_iso: nowIso()
371
+ };
372
+ state.accountSpendCredentials.set(credentialId, next);
373
+ return buildCredentialPublicView(next, false);
374
+ }
375
+
376
+ function revokeAuthorityBinding(state, bindingId, body) {
377
+ if (!bindingId || !state.accountAuthorityBindings.has(bindingId)) return null;
378
+ const payload = ensureObject(body);
379
+ const current = state.accountAuthorityBindings.get(bindingId);
380
+ const next = {
381
+ ...current,
382
+ status: "revoked",
383
+ revoked_at_iso: nowIso(),
384
+ revoke_reason: normalizeString(payload.reason, "operator_revoked"),
385
+ updated_at_iso: nowIso()
386
+ };
387
+ state.accountAuthorityBindings.set(bindingId, next);
388
+ if (current.credential_id) {
389
+ revokeSpendCredential(state, current.credential_id, payload);
390
+ }
391
+ return buildAuthorityBindingPublicView(next, current.credential_id ? state.accountSpendCredentials.get(current.credential_id) : null, false);
392
+ }
393
+
394
+ function renewAuthorityBinding(state, bindingId, body) {
395
+ if (!bindingId || !state.accountAuthorityBindings.has(bindingId)) return null;
396
+ const payload = ensureObject(body);
397
+ const current = state.accountAuthorityBindings.get(bindingId);
398
+ const nextExpiresAtIso = normalizeString(payload.expires_at_iso, current.expires_at_iso || null);
399
+ const updatedAtIso = nowIso();
400
+ const next = {
401
+ ...current,
402
+ expires_at_iso: nextExpiresAtIso,
403
+ updated_at_iso: updatedAtIso
404
+ };
405
+ state.accountAuthorityBindings.set(bindingId, next);
406
+ if (current.credential_id && state.accountSpendCredentials.has(current.credential_id)) {
407
+ const credential = state.accountSpendCredentials.get(current.credential_id);
408
+ state.accountSpendCredentials.set(current.credential_id, {
409
+ ...credential,
410
+ expires_at_iso: nextExpiresAtIso,
411
+ updated_at_iso: updatedAtIso
412
+ });
413
+ }
414
+ return buildAuthorityBindingPublicView(next, current.credential_id ? state.accountSpendCredentials.get(current.credential_id) : null, false);
415
+ }
416
+
417
+ function rotateAuthorityBinding(state, bindingId, body) {
418
+ if (!bindingId || !state.accountAuthorityBindings.has(bindingId)) return null;
419
+ const payload = ensureObject(body);
420
+ const current = state.accountAuthorityBindings.get(bindingId);
421
+ const currentCredential = current.credential_id ? state.accountSpendCredentials.get(current.credential_id) : null;
422
+ const successorBindingId = normalizeString(payload.successor_binding_id, `${bindingId}_rotated`);
423
+ const successorCredentialId = normalizeString(payload.successor_credential_id, current.credential_id ? `${current.credential_id}_rotated` : `spend_for_${successorBindingId}`);
424
+ const successor = createAuthorityBinding(state, {
425
+ binding_id: successorBindingId,
426
+ credential_id: successorCredentialId,
427
+ bearer_token: normalizeString(payload.bearer_token, null),
428
+ // Carry the cryptographic identity binding forward on rotation — otherwise a
429
+ // key-bound credential would silently downgrade to bearer-only.
430
+ agent_public_key: normalizeString(payload.agent_public_key, currentCredential ? currentCredential.agent_public_key : null),
431
+ account_id: current.account_id,
432
+ agent_id: normalizeString(payload.agent_id, current.agent_id),
433
+ budget_id: normalizeString(payload.budget_id, current.budget_id),
434
+ pack_id: normalizeString(payload.pack_id, current.pack_id),
435
+ entitlement_id: normalizeString(payload.entitlement_id, current.entitlement_id),
436
+ scope: normalizeString(payload.scope, current.scope),
437
+ authority_kind: normalizeString(payload.authority_kind, current.authority_kind),
438
+ authority_scope: ensureArray(payload.authority_scope).length > 0 ? ensureArray(payload.authority_scope) : ensureArray(current.authority_scope),
439
+ allowed_consequence_families: ensureArray(payload.allowed_consequence_families).length > 0 ? ensureArray(payload.allowed_consequence_families) : ensureArray(current.allowed_consequence_families),
440
+ max_commit_units: Number.isFinite(Number(payload.max_commit_units)) ? Number(payload.max_commit_units) : current.consequence_bounds.max_commit_units,
441
+ max_reserve_units: Number.isFinite(Number(payload.max_reserve_units)) ? Number(payload.max_reserve_units) : current.consequence_bounds.max_reserve_units,
442
+ max_reversal_units: Number.isFinite(Number(payload.max_reversal_units)) ? Number(payload.max_reversal_units) : current.consequence_bounds.max_reversal_units,
443
+ labels: ensureArray(payload.labels).length > 0 ? ensureArray(payload.labels) : ensureArray(current.labels),
444
+ issued_by: normalizeString(payload.issued_by, current.issued_by || "operator"),
445
+ expires_at_iso: normalizeString(payload.expires_at_iso, current.expires_at_iso || (currentCredential ? currentCredential.expires_at_iso : null)),
446
+ rotated_from_binding_id: current.binding_id
447
+ });
448
+ const revoked = revokeAuthorityBinding(state, bindingId, {
449
+ reason: normalizeString(payload.reason, "rotated_to_successor")
450
+ });
451
+ const successorRecord = state.accountAuthorityBindings.get(successor.binding_id);
452
+ state.accountAuthorityBindings.set(successor.binding_id, {
453
+ ...successorRecord,
454
+ rotated_from_binding_id: current.binding_id
455
+ });
456
+ state.accountAuthorityBindings.set(bindingId, {
457
+ ...state.accountAuthorityBindings.get(bindingId),
458
+ replaced_by_binding_id: successor.binding_id
459
+ });
460
+ return {
461
+ rotated_binding: buildAuthorityBindingPublicView(state.accountAuthorityBindings.get(bindingId), current.credential_id ? state.accountSpendCredentials.get(current.credential_id) : null, false),
462
+ successor_authority_binding: buildAuthorityBindingPublicView(state.accountAuthorityBindings.get(successor.binding_id), state.accountSpendCredentials.get(successor.credential_id), true),
463
+ previous_view: revoked
464
+ };
465
+ }
466
+
467
+ function resolveSpendCredential(state, bearerToken, proof, requestBinding) {
468
+ const token = normalizeString(bearerToken, null);
469
+ if (!token) {
470
+ return {
471
+ ok: false,
472
+ reason: "missing_spend_credential"
473
+ };
474
+ }
475
+ const credentialId = state.accountSpendCredentialsByToken.get(token);
476
+ if (!credentialId || !state.accountSpendCredentials.has(credentialId)) {
477
+ return {
478
+ ok: false,
479
+ reason: "spend_credential_not_found"
480
+ };
481
+ }
482
+ const credential = state.accountSpendCredentials.get(credentialId);
483
+ if (credential.status !== "active") {
484
+ return {
485
+ ok: false,
486
+ reason: "spend_credential_inactive",
487
+ credential: buildCredentialPublicView(credential, false)
488
+ };
489
+ }
490
+ if (isCredentialExpired(credential)) {
491
+ return {
492
+ ok: false,
493
+ reason: "spend_credential_expired",
494
+ credential: buildCredentialPublicView(credential, false)
495
+ };
496
+ }
497
+ // Cryptographic identity gate: a key-bound credential requires a fresh signed
498
+ // proof of control of the agent key — the bearer token alone is not enough.
499
+ if (credential.agent_public_key) {
500
+ // Bind the proof to the actual request (account/amount/task) when the caller supplies a
501
+ // request binding. `require` is set BY THE CALLER (requestBinding.require) so strict mode
502
+ // applies only where a binding is actually supplied — the execute path. The reserve/
503
+ // release/reverse lifecycle paths pass no binding, so they are unaffected by strict mode
504
+ // (and remain capped by the authority-binding bounds). Default keeps back-compat: an
505
+ // unbound proof still authorizes.
506
+ const requireBinding = Boolean(requestBinding && requestBinding.require);
507
+ const verdict = verifySpendAuthProof(credential.agent_public_key, credential.credential_id, proof || {}, {
508
+ requestBinding: requestBinding || null,
509
+ requireBinding
510
+ });
511
+ if (!verdict.ok) {
512
+ return {
513
+ ok: false,
514
+ reason: verdict.reason,
515
+ credential: buildCredentialPublicView(credential, false)
516
+ };
517
+ }
518
+ // Replay protection is MANDATORY for a key-bound credential — fail closed if
519
+ // the replay store is unavailable rather than silently skipping it.
520
+ const replayStore = state && state.acceptedAgentSignatures instanceof Map ? state.acceptedAgentSignatures : null;
521
+ if (!replayStore) {
522
+ return {
523
+ ok: false,
524
+ reason: "agent_replay_store_unavailable",
525
+ credential: buildCredentialPublicView(credential, false)
526
+ };
527
+ }
528
+ const now = Date.now();
529
+ // Opportunistic prune: a signature past its freshness window can never be a
530
+ // valid replay again, so forget it (bounds memory + snapshot size). The key is
531
+ // the canonical decoded-signature fingerprint (re-encoding cannot evade it).
532
+ for (const [key, expiresAt] of replayStore) {
533
+ if (!Number.isFinite(expiresAt) || expiresAt <= now) replayStore.delete(key);
534
+ }
535
+ if (replayStore.has(verdict.canonical)) {
536
+ return {
537
+ ok: false,
538
+ reason: "agent_signature_replayed",
539
+ credential: buildCredentialPublicView(credential, false)
540
+ };
541
+ }
542
+ replayStore.set(verdict.canonical, Number.isFinite(verdict.expires_at_ms) ? verdict.expires_at_ms : now + 120000);
543
+ }
544
+ const binding = Array.from(state.accountAuthorityBindings.values()).find((entry) => entry && entry.credential_id === credentialId && entry.status === "active") || null;
545
+ return {
546
+ ok: true,
547
+ credential,
548
+ binding,
549
+ authorization_context: {
550
+ verification_mode: "delegated_spend_credential",
551
+ wallet_id: credential.credential_id,
552
+ payment_payload: {
553
+ binding_id: binding ? binding.binding_id : null,
554
+ credential_id: credential.credential_id,
555
+ spend_posture: credential.spend_posture,
556
+ pack_id: credential.pack_id || null,
557
+ entitlement_id: credential.entitlement_id || null,
558
+ authority_scope: binding ? ensureArray(binding.authority_scope) : [],
559
+ allowed_consequence_families: binding ? ensureArray(binding.allowed_consequence_families) : [],
560
+ consequence_bounds: binding && binding.consequence_bounds ? binding.consequence_bounds : {
561
+ max_commit_units: null,
562
+ max_reserve_units: null,
563
+ max_reversal_units: null
564
+ }
565
+ }
566
+ }
567
+ };
568
+ }
569
+
570
+ module.exports = {
571
+ createAuthorityBinding,
572
+ createSpendCredential,
573
+ evaluateAuthorityBindingAction,
574
+ getAuthorityBinding,
575
+ getAuthorityBindingContractSummary,
576
+ getAuthorityBindingRotationSummary,
577
+ getSpendCredential,
578
+ listAuthorityBindings,
579
+ listSpendCredentials,
580
+ renewAuthorityBinding,
581
+ resolveSpendCredential,
582
+ rotateAuthorityBinding,
583
+ revokeAuthorityBinding,
584
+ revokeSpendCredential
585
+ };