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
@@ -0,0 +1,162 @@
1
+ "use strict";
2
+
3
+ // Cryptographic agent identity for delegated-spend credentials.
4
+ //
5
+ // A spend credential may be bound to an agent's ed25519 public key (the same
6
+ // SPKI scheme xoonya's proof engine uses). When it is, presenting the bearer
7
+ // token is no longer sufficient: the caller must also prove control of the
8
+ // private key by signing a fresh challenge. This turns the credential from a
9
+ // pure bearer secret into a key-bound, verifiable delegated authority.
10
+ //
11
+ // Backward-compatible: a credential with no bound key keeps the existing
12
+ // bearer-only behavior. Dependency-free (node crypto; ed25519 verify is native).
13
+
14
+ const crypto = require("crypto");
15
+
16
+ // Accept an ed25519 public key as SPKI PEM or base64-encoded SPKI DER.
17
+ // Returns { key: KeyObject, spki_der_b64, key_ref } or null.
18
+ function normalizeAgentPublicKey(input) {
19
+ if (typeof input !== "string" || !input.trim()) return null;
20
+ const s = input.trim();
21
+ let key = null;
22
+ try {
23
+ if (s.includes("BEGIN PUBLIC KEY")) {
24
+ key = crypto.createPublicKey({ key: s, format: "pem" });
25
+ } else {
26
+ const der = Buffer.from(s.replace(/\s+/g, ""), "base64");
27
+ if (der.length === 0) return null;
28
+ key = crypto.createPublicKey({ key: der, format: "der", type: "spki" });
29
+ }
30
+ } catch (_) {
31
+ return null;
32
+ }
33
+ if (!key || key.asymmetricKeyType !== "ed25519") return null;
34
+ const spki = key.export({ type: "spki", format: "der" });
35
+ const keyRef = "ed25519-spki-sha256:" + crypto.createHash("sha256").update(spki).digest("hex");
36
+ return { key, spki_der_b64: spki.toString("base64"), key_ref: keyRef };
37
+ }
38
+
39
+ // The stable, public fingerprint of an agent key (matches xoonya's ref format).
40
+ function deriveAgentKeyRef(input) {
41
+ const m = normalizeAgentPublicKey(input);
42
+ return m ? m.key_ref : null;
43
+ }
44
+
45
+ // A deterministic digest committing a spend proof to the specific request it authorizes
46
+ // (account + units + task). A signature over a message carrying this digest can only be
47
+ // used for that exact account/amount/task — closing the "fresh signature repurposed for a
48
+ // different (within-cap) action" gap. Returns null when there is nothing to bind.
49
+ function buildSpendBindingDigest(binding) {
50
+ if (!binding || typeof binding !== "object") return null;
51
+ const toStr = (v) => (v === undefined || v === null ? "" : String(v).trim());
52
+ const account = toStr(binding.account_id);
53
+ const units = toStr(binding.units);
54
+ const task = toStr(binding.task_ref);
55
+ if (!account && !units && !task) return null;
56
+ // JSON array of fixed-order fields: unambiguous / injection-free (JSON escapes the field
57
+ // values), unlike a delimiter-joined string where a value containing the delimiter could
58
+ // collide two different (account, units, task) tuples onto the same digest.
59
+ const canonical = JSON.stringify(["naxytra-spend-binding/v1", account, units, task]);
60
+ return crypto.createHash("sha256").update(canonical, "utf8").digest("hex");
61
+ }
62
+
63
+ // The canonical challenge an agent signs to prove key control for a spend action. When a
64
+ // bindingDigest is supplied the message additionally commits to the request (account/amount/
65
+ // task); without it, the legacy unbound message (credential id + timestamp) is produced.
66
+ function buildSpendAuthMessage(credentialId, timestamp, bindingDigest) {
67
+ const base = `naxytra-spend-auth:${credentialId}:${timestamp}`;
68
+ return bindingDigest ? `${base}:${bindingDigest}` : base;
69
+ }
70
+
71
+ // Verify an ed25519 signature (base64) over `message` against the bound key.
72
+ function verifyAgentSignature(publicKeyInput, message, signatureB64) {
73
+ const m = normalizeAgentPublicKey(publicKeyInput);
74
+ if (!m) return false;
75
+ let sig;
76
+ try {
77
+ sig = Buffer.from(String(signatureB64 || ""), "base64");
78
+ } catch (_) {
79
+ return false;
80
+ }
81
+ if (sig.length === 0) return false;
82
+ try {
83
+ return crypto.verify(null, Buffer.from(String(message), "utf8"), m.key, sig);
84
+ } catch (_) {
85
+ return false;
86
+ }
87
+ }
88
+
89
+ // Verify a spend-auth proof for a credential that is key-bound.
90
+ // proof = { signature, timestamp(ms) }. Returns
91
+ // { ok:true, canonical, message } | { ok:false, reason }.
92
+ // Freshness is bounded in BOTH directions (too old, or too far in the future).
93
+ // `canonical` is the decoded-signature fingerprint callers MUST use as the
94
+ // single-use replay key (so a re-encoded base64 of the same bytes cannot slip
95
+ // past the guard).
96
+ //
97
+ // options = { maxPastSeconds=120, maxFutureSeconds=30, requestBinding, requireBinding }.
98
+ // Freshness is bounded in BOTH directions. When options.requestBinding is supplied, a proof
99
+ // that signed the BOUND message (credential + timestamp + request digest) verifies and is
100
+ // reported as bound:true — that signature is usable ONLY for this exact account/amount/task,
101
+ // so a captured fresh signature cannot be repurposed for a different (even within-cap)
102
+ // request. An unbound signature still verifies (back-compat) UNLESS options.requireBinding is
103
+ // set (strict mode), which refuses anything not request-bound. `canonical` is the decoded-
104
+ // signature fingerprint callers MUST use as the single-use replay key.
105
+ function verifySpendAuthProof(agentPublicKey, credentialId, proof, options = {}) {
106
+ const opts = options && typeof options === "object" ? options : {};
107
+ const maxPastSeconds = Number.isFinite(opts.maxPastSeconds) ? opts.maxPastSeconds : 120;
108
+ const maxFutureSeconds = Number.isFinite(opts.maxFutureSeconds) ? opts.maxFutureSeconds : 30;
109
+ const requireBinding = Boolean(opts.requireBinding);
110
+ const bindingDigest = buildSpendBindingDigest(opts.requestBinding);
111
+
112
+ const signature = proof && typeof proof.signature === "string" ? proof.signature.trim() : "";
113
+ const timestampRaw = proof && (proof.timestamp !== undefined && proof.timestamp !== null) ? String(proof.timestamp).trim() : "";
114
+ if (!signature || !timestampRaw) return { ok: false, reason: "agent_signature_required" };
115
+ const timestamp = Number(timestampRaw);
116
+ if (!Number.isFinite(timestamp)) return { ok: false, reason: "agent_signature_timestamp_invalid" };
117
+ // Timestamp is milliseconds since epoch. Positive age = in the past.
118
+ const ageSeconds = (Date.now() - timestamp) / 1000;
119
+ if (ageSeconds > Math.max(1, maxPastSeconds)) return { ok: false, reason: "agent_signature_expired" };
120
+ if (ageSeconds < -Math.max(0, maxFutureSeconds)) return { ok: false, reason: "agent_signature_future" };
121
+ if (requireBinding && !bindingDigest) return { ok: false, reason: "spend_binding_required" };
122
+
123
+ // Prefer the request-bound message; fall back to the unbound message only when binding is
124
+ // not strictly required. A bound signature whose digest mismatches the actual request
125
+ // verifies against neither message -> rejected.
126
+ let message = null;
127
+ let bound = false;
128
+ if (bindingDigest) {
129
+ const boundMessage = buildSpendAuthMessage(credentialId, timestampRaw, bindingDigest);
130
+ if (verifyAgentSignature(agentPublicKey, boundMessage, signature)) {
131
+ message = boundMessage;
132
+ bound = true;
133
+ }
134
+ }
135
+ if (!message && !requireBinding) {
136
+ const unboundMessage = buildSpendAuthMessage(credentialId, timestampRaw);
137
+ if (verifyAgentSignature(agentPublicKey, unboundMessage, signature)) {
138
+ message = unboundMessage;
139
+ bound = false;
140
+ }
141
+ }
142
+ if (!message) {
143
+ return { ok: false, reason: requireBinding ? "agent_signature_binding_required_or_invalid" : "agent_signature_invalid" };
144
+ }
145
+ // Canonical replay key = hex of the decoded signature bytes (encoding-agnostic).
146
+ let canonical;
147
+ try {
148
+ canonical = Buffer.from(signature, "base64").toString("hex");
149
+ } catch (_) {
150
+ return { ok: false, reason: "agent_signature_invalid" };
151
+ }
152
+ return { ok: true, canonical, message, bound, expires_at_ms: timestamp + Math.max(1, maxPastSeconds) * 1000 };
153
+ }
154
+
155
+ module.exports = {
156
+ normalizeAgentPublicKey,
157
+ deriveAgentKeyRef,
158
+ buildSpendAuthMessage,
159
+ buildSpendBindingDigest,
160
+ verifyAgentSignature,
161
+ verifySpendAuthProof
162
+ };
@@ -0,0 +1,187 @@
1
+ "use strict";
2
+
3
+ // Provider-agnostic BSV / UTXO (BOLT) adapter.
4
+ //
5
+ // Makes the BOLT lane a REAL on-chain rail: it verifies that a presented BSV
6
+ // transaction (txid) pays the operator's address for at least the required
7
+ // amount, by fetching the transaction from a configured BSV chain API. The txid
8
+ // is the proof of payment; replay is prevented by treating each txid as
9
+ // single-use. Engages only when env configures a provider; otherwise the caller
10
+ // preserves the existing bespoke token scheme. Dependency-free (node http/https).
11
+ //
12
+ // Env:
13
+ // XYTARA_BOLT_PROVIDER = "whatsonchain" | "generic" (unset => not configured)
14
+ // XYTARA_BOLT_PAYTO_ADDRESS (operator BSV address that must be paid)
15
+ // XYTARA_BOLT_PRICE_SATS (minimum amount, satoshis)
16
+ // XYTARA_BOLT_MIN_CONFIRMATIONS (default 0 => accept mempool)
17
+ // XYTARA_BOLT_NETWORK = "main" | "test" (default main)
18
+ // XYTARA_BOLT_ROOT_KEY | XYTARA_BOLT_SHARED_SECRET (HMAC key for the per-quote
19
+ // amount offset; recommended)
20
+ // whatsonchain: API base defaults to https://api.whatsonchain.com/v1/bsv/<network>
21
+ // generic: XYTARA_BOLT_API_URL (tx-by-hash base; "/tx/hash/<txid>" appended)
22
+
23
+ // REQUEST BINDING (production-safe) & LIMITATIONS:
24
+ // - FLAT-RATE lane: the base price is a flat XYTARA_BOLT_PRICE_SATS (BSV sats
25
+ // cannot be derived from a USD quote without a rate oracle). Use for flat-priced
26
+ // calls; do not expose high-value, variably-priced commands on this lane.
27
+ // - Per-quote binding: the front advertises a UNIQUE required amount
28
+ // (priceSats + an unpredictable HMAC-derived offset) per quote and asks the
29
+ // payer to pay it EXACTLY. verifyBsvPayment with options.requiredSats then
30
+ // requires paidSats === requiredSats, so a pre-existing/unrelated payment to
31
+ // the operator address cannot be reused. Each txid is also single-use.
32
+ // (When called without requiredSats the legacy ">= priceSats" check applies.)
33
+
34
+ const https = require("https");
35
+ const http = require("http");
36
+ const crypto = require("crypto");
37
+ const { URL } = require("url");
38
+
39
+ function env(name) {
40
+ const v = process.env[name];
41
+ return typeof v === "string" && v.trim() ? v.trim() : "";
42
+ }
43
+
44
+ function loadBoltConfig() {
45
+ const provider = env("XYTARA_BOLT_PROVIDER").toLowerCase();
46
+ if (provider !== "whatsonchain" && provider !== "generic") return { provider: null };
47
+ const network = (env("XYTARA_BOLT_NETWORK") || env("XYTARA_BSV_TERANODE_NETWORK") || "main")
48
+ .replace("mainnet", "main")
49
+ .replace("testnet", "test");
50
+ return {
51
+ provider,
52
+ network,
53
+ apiUrl: env("XYTARA_BOLT_API_URL") || (provider === "whatsonchain" ? `https://api.whatsonchain.com/v1/bsv/${network}` : ""),
54
+ payToAddress: env("XYTARA_BOLT_PAYTO_ADDRESS"),
55
+ priceSats: Number(env("XYTARA_BOLT_PRICE_SATS") || "") || null,
56
+ // Default to 1 confirmation so an unconfirmed (double-spendable) mempool tx is
57
+ // not accepted as proof of payment. An operator may explicitly set 0 to accept
58
+ // 0-conf at their own risk.
59
+ minConfirmations: env("XYTARA_BOLT_MIN_CONFIRMATIONS") === "" ? 1 : Math.max(0, Number(env("XYTARA_BOLT_MIN_CONFIRMATIONS")) || 0),
60
+ // Secret + window for the per-quote amount offset (request binding). A secret
61
+ // key is recommended so the offset is unpredictable; it falls back to the
62
+ // (public) payToAddress, which still binds via exact-amount + single-use.
63
+ bindingSecret: env("XYTARA_BOLT_ROOT_KEY") || env("XYTARA_BOLT_SHARED_SECRET") || (env("XYTARA_BOLT_PAYTO_ADDRESS") + "|" + network),
64
+ bindingWindowSats: Math.max(1, Number(env("XYTARA_BOLT_BINDING_WINDOW_SATS")) || 10000)
65
+ };
66
+ }
67
+
68
+ function isConfigured(config) {
69
+ return Boolean(config && config.provider);
70
+ }
71
+
72
+ // Deterministic unique required amount for a quote: base price + an HMAC-derived
73
+ // offset in [0, bindingWindowSats). Both challenge and verify derive the same
74
+ // value from the (stored, stable) quote, so the payer is told an exact amount and
75
+ // the tx must pay it precisely.
76
+ function computeRequiredSats(config, quote) {
77
+ const base = Number(config && config.priceSats) || 0;
78
+ if (!quote || !quote.quote_id) return base;
79
+ const mac = crypto.createHmac("sha256", String(config.bindingSecret || "")).update(String(quote.quote_id)).digest("hex");
80
+ const offset = parseInt(mac.slice(0, 8), 16) % Math.max(1, Number(config.bindingWindowSats) || 10000);
81
+ return base + offset;
82
+ }
83
+
84
+ function httpGetJson(urlStr, timeoutMs) {
85
+ return new Promise((resolve, reject) => {
86
+ let u;
87
+ try {
88
+ u = new URL(urlStr);
89
+ } catch (e) {
90
+ return reject(new Error("invalid_url"));
91
+ }
92
+ const lib = u.protocol === "http:" ? http : https;
93
+ const req = lib.request(
94
+ { method: "GET", hostname: u.hostname, port: u.port || (u.protocol === "http:" ? 80 : 443), path: u.pathname + u.search, headers: { Accept: "application/json" } },
95
+ (res) => {
96
+ let d = "";
97
+ res.on("data", (c) => (d += c));
98
+ res.on("end", () => {
99
+ let j = null;
100
+ try {
101
+ j = d ? JSON.parse(d) : null;
102
+ } catch (_) {
103
+ j = null;
104
+ }
105
+ resolve({ status: res.statusCode, json: j, raw: d });
106
+ });
107
+ }
108
+ );
109
+ req.on("error", reject);
110
+ req.setTimeout(timeoutMs || 15000, () => req.destroy(new Error("bolt_api_timeout")));
111
+ req.end();
112
+ });
113
+ }
114
+
115
+ // Collect the payout addresses declared on a vout's scriptPubKey across the
116
+ // shapes different BSV APIs use.
117
+ function voutAddresses(vout) {
118
+ const spk = (vout && vout.scriptPubKey) || {};
119
+ if (Array.isArray(spk.addresses)) return spk.addresses;
120
+ if (spk.address) return [spk.address];
121
+ if (Array.isArray(vout && vout.addresses)) return vout.addresses;
122
+ return [];
123
+ }
124
+
125
+ // Verify a BSV txid pays >= priceSats to payToAddress. Returns
126
+ // { ok, txid, paid_sats, confirmations, network } | { ok:false, reason, detail? }.
127
+ async function verifyBsvPayment(config, txid, fetchTxOverride, options) {
128
+ if (!isConfigured(config)) return { ok: false, reason: "bolt_provider_not_configured" };
129
+ if (!config.payToAddress || !config.priceSats) return { ok: false, reason: "bolt_payto_or_price_missing" };
130
+ if (!config.apiUrl) return { ok: false, reason: "bolt_api_url_missing" };
131
+ if (!/^[0-9a-fA-F]{64}$/.test(String(txid || ""))) return { ok: false, reason: "bolt_txid_invalid" };
132
+ const fetchTx = typeof fetchTxOverride === "function" ? fetchTxOverride : (u) => httpGetJson(u, 15000);
133
+ let res;
134
+ try {
135
+ res = await fetchTx(config.apiUrl.replace(/\/$/, "") + "/tx/hash/" + txid);
136
+ } catch (e) {
137
+ return { ok: false, reason: "bolt_api_unreachable", detail: e && e.message ? e.message : "request_error" };
138
+ }
139
+ if (!res.json || res.status >= 400) return { ok: false, reason: "bolt_tx_not_found", detail: `HTTP ${res.status}` };
140
+ const j = res.json;
141
+ const confirmations = Number(j.confirmations || 0);
142
+ if (config.minConfirmations > 0 && confirmations < config.minConfirmations) {
143
+ return { ok: false, reason: "bolt_insufficient_confirmations", detail: `${confirmations}/${config.minConfirmations}` };
144
+ }
145
+ const vouts = Array.isArray(j.vout) ? j.vout : [];
146
+ let paidSats = 0;
147
+ for (const o of vouts) {
148
+ if (voutAddresses(o).includes(config.payToAddress)) {
149
+ // BSV APIs report value in BSV; convert to satoshis.
150
+ paidSats += Math.round(Number(o.value || 0) * 1e8);
151
+ }
152
+ }
153
+ // Per-quote binding: when a unique required amount is supplied, the tx must pay
154
+ // it EXACTLY (not merely >=), so an unrelated payment to the address cannot be
155
+ // reused. Without it, fall back to the flat ">= priceSats" check.
156
+ const requiredSats = options && Number.isFinite(Number(options.requiredSats)) ? Math.round(Number(options.requiredSats)) : null;
157
+ if (requiredSats !== null) {
158
+ if (paidSats !== requiredSats) {
159
+ return { ok: false, reason: "bolt_amount_mismatch", detail: `${paidSats}/${requiredSats}` };
160
+ }
161
+ } else if (paidSats < config.priceSats) {
162
+ return { ok: false, reason: "bolt_amount_insufficient", detail: `${paidSats}/${config.priceSats}` };
163
+ }
164
+ return { ok: true, txid: String(txid), paid_sats: paidSats, confirmations, network: config.network, required_sats: requiredSats };
165
+ }
166
+
167
+ // Parse "BOLT <txid>" (64-hex). Returns { txid } | null.
168
+ function parseBoltHeader(authorization) {
169
+ const m = String(authorization || "").match(/^BOLT\s+([0-9a-fA-F]{64})\s*$/);
170
+ return m ? { txid: m[1] } : null;
171
+ }
172
+
173
+ // The challenge an unpaid caller needs: where to pay and how much. When a
174
+ // per-quote required amount is supplied, advertise that exact amount (the payer
175
+ // must pay it precisely) instead of the flat base price.
176
+ function buildBoltChallenge(config, options) {
177
+ const requiredSats = options && Number.isFinite(Number(options.requiredSats)) ? Math.round(Number(options.requiredSats)) : null;
178
+ return {
179
+ address: config.payToAddress,
180
+ amount_sats: requiredSats !== null ? requiredSats : config.priceSats,
181
+ exact: requiredSats !== null,
182
+ network: config.network,
183
+ min_confirmations: config.minConfirmations
184
+ };
185
+ }
186
+
187
+ module.exports = { loadBoltConfig, isConfigured, verifyBsvPayment, parseBoltHeader, buildBoltChallenge, computeRequiredSats };