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.
Files changed (55) hide show
  1. package/.env.example +8 -1
  2. package/BSV_TERANODE_PLATFORM_DISCONTINUITY_RUNBOOK.md +126 -126
  3. package/RELEASE_NOTES.md +6 -4
  4. package/lib/a2a_rpc.js +280 -280
  5. package/lib/account_auth.js +585 -585
  6. package/lib/agent_identity.js +162 -162
  7. package/lib/bolt_adapter.js +187 -187
  8. package/lib/bolt_payment_front.js +224 -224
  9. package/lib/checkout_processor_adapter.js +217 -217
  10. package/lib/command_flow.js +722 -722
  11. package/lib/commerce_artifacts.js +591 -591
  12. package/lib/commerce_bridge.js +274 -274
  13. package/lib/commerce_cases.js +399 -399
  14. package/lib/commerce_client.js +7694 -7694
  15. package/lib/commerce_quotes.js +29 -0
  16. package/lib/commerce_runtime.js +322 -322
  17. package/lib/execution_dedupe.js +86 -86
  18. package/lib/external_credit_bridge.js +142 -142
  19. package/lib/http_transport.js +81 -81
  20. package/lib/l402_adapter.js +241 -241
  21. package/lib/l402_payment_front.js +265 -265
  22. package/lib/mpp_adapter.js +237 -237
  23. package/lib/payment_config.js +253 -253
  24. package/lib/payment_verification.js +357 -357
  25. package/lib/provider_payout_execution.js +155 -155
  26. package/lib/provider_registry.js +842 -842
  27. package/lib/rate_limiter.js +81 -81
  28. package/lib/runtime_state_store.js +491 -369
  29. package/lib/settlement_bsv_live.js +600 -600
  30. package/lib/settlement_bsv_teranode.js +117 -117
  31. package/lib/stripe_mpp_payment_front.js +258 -258
  32. package/lib/x402_facilitator.js +191 -191
  33. package/package.json +5 -3
  34. package/scripts/state_backup_offsite.js +196 -0
  35. package/scripts/verify_a2a_rpc.js +105 -105
  36. package/scripts/verify_agent_identity.js +153 -153
  37. package/scripts/verify_all.js +1 -1
  38. package/scripts/verify_bolt_adapter.js +128 -128
  39. package/scripts/verify_cdp_facilitator.js +110 -110
  40. package/scripts/verify_checkout_processor.js +109 -109
  41. package/scripts/verify_commerce_bridge.js +177 -177
  42. package/scripts/verify_execution_dedupe.js +189 -189
  43. package/scripts/verify_execution_surfacing.js +76 -76
  44. package/scripts/verify_final_activation.js +191 -191
  45. package/scripts/verify_l402_adapter.js +86 -86
  46. package/scripts/verify_mpp_adapter.js +128 -128
  47. package/scripts/verify_production_readiness.js +268 -268
  48. package/scripts/verify_rate_limiter.js +52 -52
  49. package/scripts/verify_refund_credit.js +106 -106
  50. package/scripts/verify_release_candidate.js +81 -81
  51. package/scripts/verify_runtime_state_guard.js +117 -0
  52. package/scripts/verify_service.js +15421 -15421
  53. package/scripts/verify_verify_execute_settle.js +208 -208
  54. package/scripts/verify_x402_facilitator.js +286 -286
  55. package/server.js +11976 -11974
@@ -1,105 +1,105 @@
1
- "use strict";
2
-
3
- // Verifies the A2A JSON-RPC endpoint with the in-band x402 payment extension
4
- // (lib/a2a_rpc.js). The facilitator verify/settle and the command executor are
5
- // injected as mocks so this runs offline and moves no money.
6
-
7
- const assert = require("assert");
8
- const {
9
- handleA2ARpc,
10
- META_PAYLOAD,
11
- META_STATUS,
12
- META_REQUIRED
13
- } = require("../lib/a2a_rpc");
14
-
15
- const accepts = [
16
- { scheme: "exact", network: "eip155:84532", asset: "0xUSDC", amount: "1000", payTo: "0xPAYTO", extra: { name: "USDC", version: "2" } }
17
- ];
18
- const config = { verification_mode: "x402_facilitator", x402: { accepts, facilitator_url: "https://facilitator", settle: true } };
19
-
20
- function deps(overrides) {
21
- return Object.assign(
22
- {
23
- createFacilitator: () => ({}),
24
- verifyX402Payment: async () => ({ ok: true, authorization: { payer: "0xPAYER", paymentRequirements: accepts[0] } }),
25
- settleX402Payment: async () => ({ ok: true, settlement: { success: true, transaction: "0xTX", network: "eip155:84532" } }),
26
- encodeReceipt: (s) => Buffer.from(JSON.stringify(s), "utf8").toString("base64"),
27
- executeAuthorized: async (state, payload, authz) => ({ status: 200, payload: { ok: true, ran: payload.task_ref, azmode: authz.verification_mode } }),
28
- buildNamedTaskPayload: (ref, body) => ({ command: ref, task_ref: ref, body }),
29
- state: {}
30
- },
31
- overrides || {}
32
- );
33
- }
34
-
35
- function send(params, ctxOverrides) {
36
- return handleA2ARpc(
37
- { jsonrpc: "2.0", id: 1, method: "message/send", params },
38
- Object.assign({ config, resourceUrl: "https://xytara.onrender.com/v1/a2a", deps: deps() }, ctxOverrides || {})
39
- );
40
- }
41
-
42
- async function main() {
43
- // 1. Unpaid -> input-required + x402 requirements in-band.
44
- let out = await send({ message: { metadata: { task_ref: "a2a.negotiate" } } });
45
- assert.strictEqual(out.http, 200);
46
- assert.strictEqual(out.body.result.status.state, "input-required");
47
- assert.strictEqual(out.body.result.status.message.metadata[META_STATUS], "payment-required");
48
- assert.deepStrictEqual(out.body.result.status.message.metadata[META_REQUIRED].accepts, accepts);
49
-
50
- // 2. Paid -> completed + PAYMENT-RESPONSE + executed through the x402 authz context.
51
- out = await send({ message: { metadata: { task_ref: "a2a.negotiate", [META_PAYLOAD]: "BASE64PAYLOAD" } } });
52
- assert.strictEqual(out.body.result.status.state, "completed");
53
- assert.strictEqual(out.body.result.status.message.metadata[META_STATUS], "payment-completed");
54
- assert.ok(out.headers && out.headers["PAYMENT-RESPONSE"], "settled 200 must carry PAYMENT-RESPONSE");
55
- assert.strictEqual(out.body.result.artifacts[0].parts[0].data.ran, "a2a.negotiate");
56
- assert.strictEqual(out.body.result.artifacts[0].parts[0].data.azmode, "x402_facilitator");
57
-
58
- // 2b. Paid but the skill execution fails -> task is reported "failed" (not
59
- // "completed"), still carries the settlement receipt (money moved).
60
- out = await send(
61
- { message: { metadata: { task_ref: "a2a.negotiate", [META_PAYLOAD]: "B64" } } },
62
- { deps: deps({ executeAuthorized: async () => ({ status: 500, payload: { ok: false, reason: "boom" } }) }) }
63
- );
64
- assert.strictEqual(out.body.result.status.state, "failed");
65
- assert.strictEqual(out.body.result.status.message.metadata[META_STATUS], "payment-completed");
66
- assert.ok(out.headers && out.headers["PAYMENT-RESPONSE"], "failed-after-payment still carries receipt");
67
- assert.strictEqual(out.body.result.artifacts.length, 0);
68
-
69
- // 3. Verify fails -> payment-rejected.
70
- out = await send(
71
- { message: { metadata: { [META_PAYLOAD]: "BAD" } } },
72
- { deps: deps({ verifyX402Payment: async () => ({ ok: false, reason: "payment_verification_failed", detail: "insufficient_balance" }) }) }
73
- );
74
- assert.strictEqual(out.body.result.status.state, "failed");
75
- assert.strictEqual(out.body.result.status.message.metadata[META_STATUS], "payment-rejected");
76
-
77
- // 4. Settle fails -> payment-failed.
78
- out = await send(
79
- { message: { metadata: { [META_PAYLOAD]: "OK" } } },
80
- { deps: deps({ settleX402Payment: async () => ({ ok: false, reason: "payment_settlement_failed", detail: "facilitator" }) }) }
81
- );
82
- assert.strictEqual(out.body.result.status.message.metadata[META_STATUS], "payment-failed");
83
-
84
- // 5. Unknown method -> -32601.
85
- out = await handleA2ARpc({ jsonrpc: "2.0", id: 9, method: "tasks/cancel" }, { config, resourceUrl: "x", deps: deps() });
86
- assert.strictEqual(out.body.error.code, -32601);
87
-
88
- // 6. x402 mode off -> -32010.
89
- out = await handleA2ARpc(
90
- { jsonrpc: "2.0", id: 9, method: "message/send", params: { message: {} } },
91
- { config: { verification_mode: "local_signed", x402: { accepts } }, resourceUrl: "x", deps: deps() }
92
- );
93
- assert.strictEqual(out.body.error.code, -32010);
94
-
95
- // 7. Non-2.0 envelope -> -32600.
96
- out = await handleA2ARpc({ id: 1, method: "message/send" }, { config, resourceUrl: "x", deps: deps() });
97
- assert.strictEqual(out.body.error.code, -32600);
98
-
99
- console.log("verify_a2a_rpc: all A2A x402 JSON-RPC checks passed");
100
- }
101
-
102
- main().catch((error) => {
103
- console.error("verify_a2a_rpc failed:", error && error.message ? error.message : error);
104
- process.exitCode = 1;
105
- });
1
+ "use strict";
2
+
3
+ // Verifies the A2A JSON-RPC endpoint with the in-band x402 payment extension
4
+ // (lib/a2a_rpc.js). The facilitator verify/settle and the command executor are
5
+ // injected as mocks so this runs offline and moves no money.
6
+
7
+ const assert = require("assert");
8
+ const {
9
+ handleA2ARpc,
10
+ META_PAYLOAD,
11
+ META_STATUS,
12
+ META_REQUIRED
13
+ } = require("../lib/a2a_rpc");
14
+
15
+ const accepts = [
16
+ { scheme: "exact", network: "eip155:84532", asset: "0xUSDC", amount: "1000", payTo: "0xPAYTO", extra: { name: "USDC", version: "2" } }
17
+ ];
18
+ const config = { verification_mode: "x402_facilitator", x402: { accepts, facilitator_url: "https://facilitator", settle: true } };
19
+
20
+ function deps(overrides) {
21
+ return Object.assign(
22
+ {
23
+ createFacilitator: () => ({}),
24
+ verifyX402Payment: async () => ({ ok: true, authorization: { payer: "0xPAYER", paymentRequirements: accepts[0] } }),
25
+ settleX402Payment: async () => ({ ok: true, settlement: { success: true, transaction: "0xTX", network: "eip155:84532" } }),
26
+ encodeReceipt: (s) => Buffer.from(JSON.stringify(s), "utf8").toString("base64"),
27
+ executeAuthorized: async (state, payload, authz) => ({ status: 200, payload: { ok: true, ran: payload.task_ref, azmode: authz.verification_mode } }),
28
+ buildNamedTaskPayload: (ref, body) => ({ command: ref, task_ref: ref, body }),
29
+ state: {}
30
+ },
31
+ overrides || {}
32
+ );
33
+ }
34
+
35
+ function send(params, ctxOverrides) {
36
+ return handleA2ARpc(
37
+ { jsonrpc: "2.0", id: 1, method: "message/send", params },
38
+ Object.assign({ config, resourceUrl: "https://xytara.onrender.com/v1/a2a", deps: deps() }, ctxOverrides || {})
39
+ );
40
+ }
41
+
42
+ async function main() {
43
+ // 1. Unpaid -> input-required + x402 requirements in-band.
44
+ let out = await send({ message: { metadata: { task_ref: "a2a.negotiate" } } });
45
+ assert.strictEqual(out.http, 200);
46
+ assert.strictEqual(out.body.result.status.state, "input-required");
47
+ assert.strictEqual(out.body.result.status.message.metadata[META_STATUS], "payment-required");
48
+ assert.deepStrictEqual(out.body.result.status.message.metadata[META_REQUIRED].accepts, accepts);
49
+
50
+ // 2. Paid -> completed + PAYMENT-RESPONSE + executed through the x402 authz context.
51
+ out = await send({ message: { metadata: { task_ref: "a2a.negotiate", [META_PAYLOAD]: "BASE64PAYLOAD" } } });
52
+ assert.strictEqual(out.body.result.status.state, "completed");
53
+ assert.strictEqual(out.body.result.status.message.metadata[META_STATUS], "payment-completed");
54
+ assert.ok(out.headers && out.headers["PAYMENT-RESPONSE"], "settled 200 must carry PAYMENT-RESPONSE");
55
+ assert.strictEqual(out.body.result.artifacts[0].parts[0].data.ran, "a2a.negotiate");
56
+ assert.strictEqual(out.body.result.artifacts[0].parts[0].data.azmode, "x402_facilitator");
57
+
58
+ // 2b. Paid but the skill execution fails -> task is reported "failed" (not
59
+ // "completed"), still carries the settlement receipt (money moved).
60
+ out = await send(
61
+ { message: { metadata: { task_ref: "a2a.negotiate", [META_PAYLOAD]: "B64" } } },
62
+ { deps: deps({ executeAuthorized: async () => ({ status: 500, payload: { ok: false, reason: "boom" } }) }) }
63
+ );
64
+ assert.strictEqual(out.body.result.status.state, "failed");
65
+ assert.strictEqual(out.body.result.status.message.metadata[META_STATUS], "payment-completed");
66
+ assert.ok(out.headers && out.headers["PAYMENT-RESPONSE"], "failed-after-payment still carries receipt");
67
+ assert.strictEqual(out.body.result.artifacts.length, 0);
68
+
69
+ // 3. Verify fails -> payment-rejected.
70
+ out = await send(
71
+ { message: { metadata: { [META_PAYLOAD]: "BAD" } } },
72
+ { deps: deps({ verifyX402Payment: async () => ({ ok: false, reason: "payment_verification_failed", detail: "insufficient_balance" }) }) }
73
+ );
74
+ assert.strictEqual(out.body.result.status.state, "failed");
75
+ assert.strictEqual(out.body.result.status.message.metadata[META_STATUS], "payment-rejected");
76
+
77
+ // 4. Settle fails -> payment-failed.
78
+ out = await send(
79
+ { message: { metadata: { [META_PAYLOAD]: "OK" } } },
80
+ { deps: deps({ settleX402Payment: async () => ({ ok: false, reason: "payment_settlement_failed", detail: "facilitator" }) }) }
81
+ );
82
+ assert.strictEqual(out.body.result.status.message.metadata[META_STATUS], "payment-failed");
83
+
84
+ // 5. Unknown method -> -32601.
85
+ out = await handleA2ARpc({ jsonrpc: "2.0", id: 9, method: "tasks/cancel" }, { config, resourceUrl: "x", deps: deps() });
86
+ assert.strictEqual(out.body.error.code, -32601);
87
+
88
+ // 6. x402 mode off -> -32010.
89
+ out = await handleA2ARpc(
90
+ { jsonrpc: "2.0", id: 9, method: "message/send", params: { message: {} } },
91
+ { config: { verification_mode: "local_signed", x402: { accepts } }, resourceUrl: "x", deps: deps() }
92
+ );
93
+ assert.strictEqual(out.body.error.code, -32010);
94
+
95
+ // 7. Non-2.0 envelope -> -32600.
96
+ out = await handleA2ARpc({ id: 1, method: "message/send" }, { config, resourceUrl: "x", deps: deps() });
97
+ assert.strictEqual(out.body.error.code, -32600);
98
+
99
+ console.log("verify_a2a_rpc: all A2A x402 JSON-RPC checks passed");
100
+ }
101
+
102
+ main().catch((error) => {
103
+ console.error("verify_a2a_rpc failed:", error && error.message ? error.message : error);
104
+ process.exitCode = 1;
105
+ });
@@ -1,153 +1,153 @@
1
- "use strict";
2
-
3
- // Verifies cryptographic agent identity for delegated-spend credentials:
4
- // ed25519 key binding + fresh signed-proof enforcement with replay (encoding-
5
- // agnostic, mandatory/fail-closed), expiry and future-dating guards; key binding
6
- // carried through rotation; invalid keys not bricking; and byte-for-byte backward
7
- // compatibility when no key is bound.
8
-
9
- const crypto = require("crypto");
10
- const assert = require("assert");
11
- const ai = require("../lib/agent_identity");
12
- const { createSpendCredential, resolveSpendCredential, createAuthorityBinding, rotateAuthorityBinding } = require("../lib/account_auth");
13
-
14
- function mkState() {
15
- return {
16
- accountSpendCredentials: new Map(),
17
- accountSpendCredentialsByToken: new Map(),
18
- accountAuthorityBindings: new Map(),
19
- acceptedAgentSignatures: new Map()
20
- };
21
- }
22
-
23
- function signAuth(privateKey, credentialId, timestamp) {
24
- const msg = ai.buildSpendAuthMessage(credentialId, String(timestamp));
25
- return crypto.sign(null, Buffer.from(msg, "utf8"), privateKey).toString("base64");
26
- }
27
-
28
- function main() {
29
- const { publicKey, privateKey } = crypto.generateKeyPairSync("ed25519");
30
- const pubPem = publicKey.export({ type: "spki", format: "pem" });
31
- const pubDerB64 = publicKey.export({ type: "spki", format: "der" }).toString("base64");
32
-
33
- // 1. Key helpers: ref stable across PEM/DER; invalid -> null; sign/verify.
34
- const ref = ai.deriveAgentKeyRef(pubPem);
35
- assert.ok(ref && ref.startsWith("ed25519-spki-sha256:"), "ref format");
36
- assert.strictEqual(ai.deriveAgentKeyRef(pubDerB64), ref, "PEM and DER give the same ref");
37
- assert.strictEqual(ai.deriveAgentKeyRef("not a key"), null, "invalid key -> null");
38
- const m = "hello";
39
- const sig = crypto.sign(null, Buffer.from(m), privateKey).toString("base64");
40
- assert.strictEqual(ai.verifyAgentSignature(pubPem, m, sig), true, "valid sig verifies");
41
- assert.strictEqual(ai.verifyAgentSignature(pubPem, "tampered", sig), false, "tampered msg fails");
42
-
43
- // 2. No key bound -> bearer-only, unchanged behavior.
44
- let state = mkState();
45
- const cred0 = createSpendCredential(state, { credential_id: "c0", account_id: "acct" });
46
- assert.strictEqual(cred0.identity_bound, false);
47
- assert.strictEqual(cred0.agent_key_ref, null);
48
- assert.strictEqual(resolveSpendCredential(state, cred0.bearer_token).ok, true, "bearer-only resolves");
49
-
50
- // 3. Invalid key provided -> NOT bricked: stored as bearer-only (consistent view).
51
- state = mkState();
52
- const credBad = createSpendCredential(state, { credential_id: "cbad", account_id: "acct", agent_public_key: "garbage-not-a-key" });
53
- assert.strictEqual(credBad.identity_bound, false, "invalid key is ignored");
54
- assert.strictEqual(credBad.agent_key_ref, null);
55
- assert.strictEqual(resolveSpendCredential(state, credBad.bearer_token).ok, true, "falls back to bearer-only");
56
-
57
- // 4. Key bound -> signed proof required + enforced.
58
- state = mkState();
59
- const cred = createSpendCredential(state, { credential_id: "c1", account_id: "acct", agent_public_key: pubPem });
60
- assert.strictEqual(cred.identity_bound, true);
61
- assert.strictEqual(cred.agent_key_ref, ref);
62
-
63
- assert.strictEqual(resolveSpendCredential(state, cred.bearer_token).reason, "agent_signature_required", "no proof -> required");
64
-
65
- const ts = Date.now();
66
- assert.strictEqual(resolveSpendCredential(state, cred.bearer_token, { signature: signAuth(privateKey, "c1", ts), timestamp: String(ts) }).ok, true, "valid proof authorizes");
67
-
68
- // 5. Replay is encoding-agnostic (canonical decoded-signature key).
69
- const ts2 = Date.now() + 1;
70
- const sig2 = signAuth(privateKey, "c1", ts2);
71
- assert.strictEqual(resolveSpendCredential(state, cred.bearer_token, { signature: sig2, timestamp: String(ts2) }).ok, true);
72
- const sig2UrlSafe = sig2.replace(/\+/g, "-").replace(/\//g, "_"); // re-encoded, same bytes
73
- assert.strictEqual(resolveSpendCredential(state, cred.bearer_token, { signature: sig2UrlSafe, timestamp: String(ts2) }).reason, "agent_signature_replayed", "re-encoded replay is caught");
74
-
75
- // 6. Expired (too old) and future-dated proofs rejected.
76
- const oldTs = Date.now() - 10 * 60 * 1000;
77
- assert.strictEqual(resolveSpendCredential(state, cred.bearer_token, { signature: signAuth(privateKey, "c1", oldTs), timestamp: String(oldTs) }).reason, "agent_signature_expired");
78
- const futureTs = Date.now() + 10 * 60 * 1000;
79
- assert.strictEqual(resolveSpendCredential(state, cred.bearer_token, { signature: signAuth(privateKey, "c1", futureTs), timestamp: String(futureTs) }).reason, "agent_signature_future");
80
-
81
- // 7. Wrong key -> invalid.
82
- const other = crypto.generateKeyPairSync("ed25519");
83
- const ts3 = Date.now();
84
- assert.strictEqual(resolveSpendCredential(state, cred.bearer_token, { signature: signAuth(other.privateKey, "c1", ts3), timestamp: String(ts3) }).reason, "agent_signature_invalid");
85
-
86
- // 8. Fail closed if the replay store is unavailable.
87
- const stateNoStore = { accountSpendCredentials: state.accountSpendCredentials, accountSpendCredentialsByToken: state.accountSpendCredentialsByToken, accountAuthorityBindings: new Map() };
88
- const ts4 = Date.now();
89
- assert.strictEqual(resolveSpendCredential(stateNoStore, cred.bearer_token, { signature: signAuth(privateKey, "c1", ts4), timestamp: String(ts4) }).reason, "agent_replay_store_unavailable");
90
-
91
- // 9. Authority binding threads the key through; rotation preserves it.
92
- state = mkState();
93
- const binding = createAuthorityBinding(state, { binding_id: "b1", account_id: "acct", agent_public_key: pubPem, max_commit_units: 100 });
94
- assert.strictEqual(binding.spend_credential.identity_bound, true, "binding credential key-bound");
95
- assert.strictEqual(binding.spend_credential.agent_key_ref, ref);
96
- const rotated = rotateAuthorityBinding(state, "b1", {});
97
- assert.strictEqual(rotated.successor_authority_binding.spend_credential.identity_bound, true, "rotation preserves key binding");
98
- assert.strictEqual(rotated.successor_authority_binding.spend_credential.agent_key_ref, ref, "rotation preserves the same key ref");
99
-
100
- // 10. Request binding (amount/task) — additive, back-compat with everything above.
101
- state = mkState();
102
- const credB = createSpendCredential(state, { credential_id: "cb", account_id: "acct", agent_public_key: pubPem });
103
- const bindReq = { account_id: "acct", units: 10, task_ref: "doc.analyze" };
104
- const signBound = (ts, binding) =>
105
- crypto.sign(null, Buffer.from(ai.buildSpendAuthMessage("cb", String(ts), ai.buildSpendBindingDigest(binding)), "utf8"), privateKey).toString("base64");
106
-
107
- // 10a. A bound proof matching the request authorizes.
108
- let tsb = Date.now();
109
- let res = resolveSpendCredential(state, credB.bearer_token, { signature: signBound(tsb, bindReq), timestamp: String(tsb) }, bindReq);
110
- assert.strictEqual(res.ok, true, "bound proof matching the request authorizes");
111
-
112
- // 10b. A proof bound to 10 units cannot authorize a 999-unit request (amount tampering).
113
- tsb = Date.now() + 1;
114
- res = resolveSpendCredential(state, credB.bearer_token,
115
- { signature: signBound(tsb, { account_id: "acct", units: 10, task_ref: "doc.analyze" }), timestamp: String(tsb) },
116
- { account_id: "acct", units: 999, task_ref: "doc.analyze" });
117
- assert.strictEqual(res.reason, "agent_signature_invalid", "amount-bound proof rejects a different amount");
118
-
119
- // 10c. A proof bound to one task cannot authorize another.
120
- tsb = Date.now() + 2;
121
- res = resolveSpendCredential(state, credB.bearer_token,
122
- { signature: signBound(tsb, { account_id: "acct", units: 10, task_ref: "doc.analyze" }), timestamp: String(tsb) },
123
- { account_id: "acct", units: 10, task_ref: "image.render" });
124
- assert.strictEqual(res.reason, "agent_signature_invalid", "task-bound proof rejects a different task");
125
-
126
- // 10d. An unbound proof still authorizes by default even when a binding is supplied.
127
- tsb = Date.now() + 3;
128
- res = resolveSpendCredential(state, credB.bearer_token, { signature: signAuth(privateKey, "cb", tsb), timestamp: String(tsb) }, bindReq);
129
- assert.strictEqual(res.ok, true, "unbound proof still authorizes by default (back-compat)");
130
-
131
- // 10e. Strict binding is CALLER-scoped (requestBinding.require=true), not a global flag — so
132
- // it applies only where a binding is supplied (execute path), never the lifecycle paths.
133
- const strictBind = { ...bindReq, require: true };
134
- tsb = Date.now() + 4;
135
- res = resolveSpendCredential(state, credB.bearer_token, { signature: signAuth(privateKey, "cb", tsb), timestamp: String(tsb) }, strictBind);
136
- assert.strictEqual(res.reason, "agent_signature_binding_required_or_invalid", "strict refuses an unbound proof");
137
- tsb = Date.now() + 5;
138
- res = resolveSpendCredential(state, credB.bearer_token, { signature: signBound(tsb, bindReq), timestamp: String(tsb) }, strictBind);
139
- assert.strictEqual(res.ok, true, "strict accepts a matching bound proof");
140
- tsb = Date.now() + 6;
141
- res = resolveSpendCredential(state, credB.bearer_token, { signature: signBound(tsb, bindReq), timestamp: String(tsb) }, { require: true });
142
- assert.strictEqual(res.reason, "spend_binding_required", "strict requires a request binding");
143
-
144
- // 10f. A key-bound credential on a NON-binding caller (no requestBinding) is unaffected by
145
- // strict mode — the lifecycle paths (reserve/release/reverse) keep working.
146
- tsb = Date.now() + 7;
147
- res = resolveSpendCredential(state, credB.bearer_token, { signature: signAuth(privateKey, "cb", tsb), timestamp: String(tsb) });
148
- assert.strictEqual(res.ok, true, "no-binding caller still authorizes under back-compat");
149
-
150
- console.log("verify_agent_identity: all checks passed");
151
- }
152
-
153
- main();
1
+ "use strict";
2
+
3
+ // Verifies cryptographic agent identity for delegated-spend credentials:
4
+ // ed25519 key binding + fresh signed-proof enforcement with replay (encoding-
5
+ // agnostic, mandatory/fail-closed), expiry and future-dating guards; key binding
6
+ // carried through rotation; invalid keys not bricking; and byte-for-byte backward
7
+ // compatibility when no key is bound.
8
+
9
+ const crypto = require("crypto");
10
+ const assert = require("assert");
11
+ const ai = require("../lib/agent_identity");
12
+ const { createSpendCredential, resolveSpendCredential, createAuthorityBinding, rotateAuthorityBinding } = require("../lib/account_auth");
13
+
14
+ function mkState() {
15
+ return {
16
+ accountSpendCredentials: new Map(),
17
+ accountSpendCredentialsByToken: new Map(),
18
+ accountAuthorityBindings: new Map(),
19
+ acceptedAgentSignatures: new Map()
20
+ };
21
+ }
22
+
23
+ function signAuth(privateKey, credentialId, timestamp) {
24
+ const msg = ai.buildSpendAuthMessage(credentialId, String(timestamp));
25
+ return crypto.sign(null, Buffer.from(msg, "utf8"), privateKey).toString("base64");
26
+ }
27
+
28
+ function main() {
29
+ const { publicKey, privateKey } = crypto.generateKeyPairSync("ed25519");
30
+ const pubPem = publicKey.export({ type: "spki", format: "pem" });
31
+ const pubDerB64 = publicKey.export({ type: "spki", format: "der" }).toString("base64");
32
+
33
+ // 1. Key helpers: ref stable across PEM/DER; invalid -> null; sign/verify.
34
+ const ref = ai.deriveAgentKeyRef(pubPem);
35
+ assert.ok(ref && ref.startsWith("ed25519-spki-sha256:"), "ref format");
36
+ assert.strictEqual(ai.deriveAgentKeyRef(pubDerB64), ref, "PEM and DER give the same ref");
37
+ assert.strictEqual(ai.deriveAgentKeyRef("not a key"), null, "invalid key -> null");
38
+ const m = "hello";
39
+ const sig = crypto.sign(null, Buffer.from(m), privateKey).toString("base64");
40
+ assert.strictEqual(ai.verifyAgentSignature(pubPem, m, sig), true, "valid sig verifies");
41
+ assert.strictEqual(ai.verifyAgentSignature(pubPem, "tampered", sig), false, "tampered msg fails");
42
+
43
+ // 2. No key bound -> bearer-only, unchanged behavior.
44
+ let state = mkState();
45
+ const cred0 = createSpendCredential(state, { credential_id: "c0", account_id: "acct" });
46
+ assert.strictEqual(cred0.identity_bound, false);
47
+ assert.strictEqual(cred0.agent_key_ref, null);
48
+ assert.strictEqual(resolveSpendCredential(state, cred0.bearer_token).ok, true, "bearer-only resolves");
49
+
50
+ // 3. Invalid key provided -> NOT bricked: stored as bearer-only (consistent view).
51
+ state = mkState();
52
+ const credBad = createSpendCredential(state, { credential_id: "cbad", account_id: "acct", agent_public_key: "garbage-not-a-key" });
53
+ assert.strictEqual(credBad.identity_bound, false, "invalid key is ignored");
54
+ assert.strictEqual(credBad.agent_key_ref, null);
55
+ assert.strictEqual(resolveSpendCredential(state, credBad.bearer_token).ok, true, "falls back to bearer-only");
56
+
57
+ // 4. Key bound -> signed proof required + enforced.
58
+ state = mkState();
59
+ const cred = createSpendCredential(state, { credential_id: "c1", account_id: "acct", agent_public_key: pubPem });
60
+ assert.strictEqual(cred.identity_bound, true);
61
+ assert.strictEqual(cred.agent_key_ref, ref);
62
+
63
+ assert.strictEqual(resolveSpendCredential(state, cred.bearer_token).reason, "agent_signature_required", "no proof -> required");
64
+
65
+ const ts = Date.now();
66
+ assert.strictEqual(resolveSpendCredential(state, cred.bearer_token, { signature: signAuth(privateKey, "c1", ts), timestamp: String(ts) }).ok, true, "valid proof authorizes");
67
+
68
+ // 5. Replay is encoding-agnostic (canonical decoded-signature key).
69
+ const ts2 = Date.now() + 1;
70
+ const sig2 = signAuth(privateKey, "c1", ts2);
71
+ assert.strictEqual(resolveSpendCredential(state, cred.bearer_token, { signature: sig2, timestamp: String(ts2) }).ok, true);
72
+ const sig2UrlSafe = sig2.replace(/\+/g, "-").replace(/\//g, "_"); // re-encoded, same bytes
73
+ assert.strictEqual(resolveSpendCredential(state, cred.bearer_token, { signature: sig2UrlSafe, timestamp: String(ts2) }).reason, "agent_signature_replayed", "re-encoded replay is caught");
74
+
75
+ // 6. Expired (too old) and future-dated proofs rejected.
76
+ const oldTs = Date.now() - 10 * 60 * 1000;
77
+ assert.strictEqual(resolveSpendCredential(state, cred.bearer_token, { signature: signAuth(privateKey, "c1", oldTs), timestamp: String(oldTs) }).reason, "agent_signature_expired");
78
+ const futureTs = Date.now() + 10 * 60 * 1000;
79
+ assert.strictEqual(resolveSpendCredential(state, cred.bearer_token, { signature: signAuth(privateKey, "c1", futureTs), timestamp: String(futureTs) }).reason, "agent_signature_future");
80
+
81
+ // 7. Wrong key -> invalid.
82
+ const other = crypto.generateKeyPairSync("ed25519");
83
+ const ts3 = Date.now();
84
+ assert.strictEqual(resolveSpendCredential(state, cred.bearer_token, { signature: signAuth(other.privateKey, "c1", ts3), timestamp: String(ts3) }).reason, "agent_signature_invalid");
85
+
86
+ // 8. Fail closed if the replay store is unavailable.
87
+ const stateNoStore = { accountSpendCredentials: state.accountSpendCredentials, accountSpendCredentialsByToken: state.accountSpendCredentialsByToken, accountAuthorityBindings: new Map() };
88
+ const ts4 = Date.now();
89
+ assert.strictEqual(resolveSpendCredential(stateNoStore, cred.bearer_token, { signature: signAuth(privateKey, "c1", ts4), timestamp: String(ts4) }).reason, "agent_replay_store_unavailable");
90
+
91
+ // 9. Authority binding threads the key through; rotation preserves it.
92
+ state = mkState();
93
+ const binding = createAuthorityBinding(state, { binding_id: "b1", account_id: "acct", agent_public_key: pubPem, max_commit_units: 100 });
94
+ assert.strictEqual(binding.spend_credential.identity_bound, true, "binding credential key-bound");
95
+ assert.strictEqual(binding.spend_credential.agent_key_ref, ref);
96
+ const rotated = rotateAuthorityBinding(state, "b1", {});
97
+ assert.strictEqual(rotated.successor_authority_binding.spend_credential.identity_bound, true, "rotation preserves key binding");
98
+ assert.strictEqual(rotated.successor_authority_binding.spend_credential.agent_key_ref, ref, "rotation preserves the same key ref");
99
+
100
+ // 10. Request binding (amount/task) — additive, back-compat with everything above.
101
+ state = mkState();
102
+ const credB = createSpendCredential(state, { credential_id: "cb", account_id: "acct", agent_public_key: pubPem });
103
+ const bindReq = { account_id: "acct", units: 10, task_ref: "doc.analyze" };
104
+ const signBound = (ts, binding) =>
105
+ crypto.sign(null, Buffer.from(ai.buildSpendAuthMessage("cb", String(ts), ai.buildSpendBindingDigest(binding)), "utf8"), privateKey).toString("base64");
106
+
107
+ // 10a. A bound proof matching the request authorizes.
108
+ let tsb = Date.now();
109
+ let res = resolveSpendCredential(state, credB.bearer_token, { signature: signBound(tsb, bindReq), timestamp: String(tsb) }, bindReq);
110
+ assert.strictEqual(res.ok, true, "bound proof matching the request authorizes");
111
+
112
+ // 10b. A proof bound to 10 units cannot authorize a 999-unit request (amount tampering).
113
+ tsb = Date.now() + 1;
114
+ res = resolveSpendCredential(state, credB.bearer_token,
115
+ { signature: signBound(tsb, { account_id: "acct", units: 10, task_ref: "doc.analyze" }), timestamp: String(tsb) },
116
+ { account_id: "acct", units: 999, task_ref: "doc.analyze" });
117
+ assert.strictEqual(res.reason, "agent_signature_invalid", "amount-bound proof rejects a different amount");
118
+
119
+ // 10c. A proof bound to one task cannot authorize another.
120
+ tsb = Date.now() + 2;
121
+ res = resolveSpendCredential(state, credB.bearer_token,
122
+ { signature: signBound(tsb, { account_id: "acct", units: 10, task_ref: "doc.analyze" }), timestamp: String(tsb) },
123
+ { account_id: "acct", units: 10, task_ref: "image.render" });
124
+ assert.strictEqual(res.reason, "agent_signature_invalid", "task-bound proof rejects a different task");
125
+
126
+ // 10d. An unbound proof still authorizes by default even when a binding is supplied.
127
+ tsb = Date.now() + 3;
128
+ res = resolveSpendCredential(state, credB.bearer_token, { signature: signAuth(privateKey, "cb", tsb), timestamp: String(tsb) }, bindReq);
129
+ assert.strictEqual(res.ok, true, "unbound proof still authorizes by default (back-compat)");
130
+
131
+ // 10e. Strict binding is CALLER-scoped (requestBinding.require=true), not a global flag — so
132
+ // it applies only where a binding is supplied (execute path), never the lifecycle paths.
133
+ const strictBind = { ...bindReq, require: true };
134
+ tsb = Date.now() + 4;
135
+ res = resolveSpendCredential(state, credB.bearer_token, { signature: signAuth(privateKey, "cb", tsb), timestamp: String(tsb) }, strictBind);
136
+ assert.strictEqual(res.reason, "agent_signature_binding_required_or_invalid", "strict refuses an unbound proof");
137
+ tsb = Date.now() + 5;
138
+ res = resolveSpendCredential(state, credB.bearer_token, { signature: signBound(tsb, bindReq), timestamp: String(tsb) }, strictBind);
139
+ assert.strictEqual(res.ok, true, "strict accepts a matching bound proof");
140
+ tsb = Date.now() + 6;
141
+ res = resolveSpendCredential(state, credB.bearer_token, { signature: signBound(tsb, bindReq), timestamp: String(tsb) }, { require: true });
142
+ assert.strictEqual(res.reason, "spend_binding_required", "strict requires a request binding");
143
+
144
+ // 10f. A key-bound credential on a NON-binding caller (no requestBinding) is unaffected by
145
+ // strict mode — the lifecycle paths (reserve/release/reverse) keep working.
146
+ tsb = Date.now() + 7;
147
+ res = resolveSpendCredential(state, credB.bearer_token, { signature: signAuth(privateKey, "cb", tsb), timestamp: String(tsb) });
148
+ assert.strictEqual(res.ok, true, "no-binding caller still authorizes under back-compat");
149
+
150
+ console.log("verify_agent_identity: all checks passed");
151
+ }
152
+
153
+ main();
@@ -4960,4 +4960,4 @@ main().catch((error) => {
4960
4960
  console.error(error);
4961
4961
  process.exit(1);
4962
4962
  });
4963
-
4963
+