@rine-network/cli 0.16.0 → 0.17.0

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 (2) hide show
  1. package/dist/main.js +98 -95
  2. package/package.json +2 -2
package/dist/main.js CHANGED
@@ -2,7 +2,7 @@ import { createRequire } from "node:module";
2
2
  import { Command, Option } from "commander";
3
3
  import * as fs from "node:fs";
4
4
  import { readFileSync } from "node:fs";
5
- import { FACILITATOR_PRESET, FUNNEL_TIERS, HttpClient, IdempotencyStore, RineApiError, UUID_RE, X402Error, X402FacilitatorError, X402_MESSAGE_TYPE, addMlsGroupMember, agentKeysExist, agentLabel, buildIssueCertDeps, buildPaymentMessage, buildPaymentPayload, buildPaymentRequiredMessage, buildReceiptMessage, cacheToken, connectTunnel, createWallet, decryptGroupMessage, decryptMessage, decryptThreadRow, deleteHookSecret, encryptGroupMessage, encryptMessage, encryptMlsGroupMessage, ensureCert, externalJoinMlsGroup, fetchAgents, fetchAndIngestPendingSKDistributions, fetchOAuthToken, fetchRecipientKeys, formatError, fromBase64Url, generateAgentKeys, generateHookSecret, generatePqKeyPair, getAgentPublicKeys, getCredentialEntry, getOrCreateSenderKey, getOrRefreshToken, getWalletAddress, handleWebhookRequest, hasSpiffeEndpoint, hookNameError, ingestSenderKeyDistribution, initMlsGroup, isAutoPayable, isBareAgentName, isX402MessageType, jitteredRefreshMargin, listMyInvites, loadAgentKeys, loadCredentials, loadHookSecret, loadMeta, loadMlsState, loadPolicy, loadTokenCache, loadWalletKey, makeEdgePipeFactory, normalizeHandle, parseX402Payload, performAgentCreation, performRegistration, processMlsWelcomes, readDailySpent, renewalDueWithJitter, reserveSpend, resolveAgent, resolveApiUrl, resolveConfigDir, resolveHandleViaWebFinger, resolveToUuid, saveAgentKeys, saveCredentials, saveHookSecret, savePolicy, savePqEncryptionKey, saveTokenCache, selectRequirement, sendGroupInviteNotification, settlePayment, startTlsListener, syncMlsGroup, toBase64Url, validateEncryptionKey, validateSigningKey, validateSlug, verifyIdentitySpiffe, verifyPayment, walletKeyExists } from "@rine-network/core";
5
+ import { FUNNEL_TIERS, HttpClient, IdempotencyStore, RineApiError, UUID_RE, X402Error, X402FacilitatorError, X402_MESSAGE_TYPE, addMlsGroupMember, agentKeysExist, agentLabel, buildIssueCertDeps, buildPaymentMessage, buildPaymentPayload, buildPaymentRequiredMessage, buildReceiptMessage, cacheToken, connectTunnel, createWallet, decryptGroupMessage, decryptMessage, decryptThreadRow, deleteHookSecret, encryptGroupMessage, encryptMessage, encryptMlsGroupMessage, ensureCert, externalJoinMlsGroup, fetchAgents, fetchAndIngestPendingSKDistributions, fetchOAuthToken, fetchRecipientKeys, formatError, fromBase64Url, generateAgentKeys, generateHookSecret, generatePqKeyPair, getAgentPublicKeys, getCredentialEntry, getOrCreateSenderKey, getOrRefreshToken, getWalletAddress, handleWebhookRequest, hasSpiffeEndpoint, hookNameError, ingestSenderKeyDistribution, initMlsGroup, isAutoPayable, isBareAgentName, isX402MessageType, jitteredRefreshMargin, listMyInvites, loadAgentKeys, loadCredentials, loadHookSecret, loadMeta, loadMlsState, loadPolicy, loadTokenCache, loadWalletKey, makeEdgePipeFactory, matchedQuoteToWire, normalizeHandle, parseFacilitatorHeaders, parseX402Payload, performAgentCreation, performRegistration, processMlsWelcomes, readDailySpent, refusalReceiptBody, renewalDueWithJitter, reserveSpend, resolveAgent, resolveApiUrl, resolveConfigDir, resolveFacilitatorConfig, resolveHandleViaWebFinger, resolvePayeeRequirement, resolveToUuid, saveAgentKeys, saveCredentials, saveHookSecret, savePolicy, savePqEncryptionKey, saveTokenCache, selectRequirement, sendGroupInviteNotification, sendReceipt, settleToReceipt, startTlsListener, syncMlsGroup, toBase64Url, validateEncryptionKey, validateSigningKey, validateSlug, verifyIdentitySpiffe, walletKeyExists } from "@rine-network/core";
6
6
  import readline from "node:readline";
7
7
  import { join } from "node:path";
8
8
  import { resolve4 } from "node:dns/promises";
@@ -236,7 +236,7 @@ function registerAgentProfile(program) {
236
236
  });
237
237
  printMutationOk("Skill added", gOpts.json);
238
238
  }));
239
- agent.command("set-pricing").description("Set agent pricing model and/or x402 payment terms (rine.x402.terms)").argument("<agent-id>", "Agent ID").option("--model <model>", `Pricing model (${VALID_PRICING.join("|")})`).option("--x402-terms <json>", "x402 card terms as a JSON array (REQ-P03 shape); advisory only").option("--x402-terms-file <path>", "Read the x402 terms JSON array from a file (use - for stdin)").action(withClient(program, async ({ client, gOpts }, agentId, opts) => {
239
+ agent.command("set-pricing").description("Set agent pricing model and/or x402 payment terms (rine.x402.terms)").argument("<agent-id>", "Agent ID").option("--model <model>", `Pricing model (${VALID_PRICING.join("|")})`).option("--x402-terms <json>", "x402 card terms as a JSON array; advisory only").option("--x402-terms-file <path>", "Read the x402 terms JSON array from a file (use - for stdin)").action(withClient(program, async ({ client, gOpts }, agentId, opts) => {
240
240
  if (opts.model === void 0 && opts.x402Terms === void 0 && opts.x402TermsFile === void 0) {
241
241
  printError("Nothing to set. Provide --model and/or --x402-terms/--x402-terms-file.");
242
242
  process.exitCode = 2;
@@ -736,93 +736,17 @@ function registerDiscover(program) {
736
736
  registerDiscoverGroups(discover, program);
737
737
  }
738
738
  //#endregion
739
- //#region src/x402-facilitator.ts
740
- /**
741
- * Resolve a facilitator spec into a config. `spec` is either a preset key
742
- * (`cdp` / `payai` / `x402-rs`) or an explicit `http(s)://` base URL. Optional
743
- * auth headers (`"Key: Value"` strings) and verify/settle path overrides are
744
- * merged in. Throws on an unrecognised spec so the caller fails loudly.
745
- */
746
- function resolveFacilitator(spec, opts = {}) {
747
- const base = FACILITATOR_PRESET[spec] ?? (/^https?:\/\//.test(spec) ? { url: spec } : void 0);
748
- if (!base) throw new Error(`Unknown facilitator '${spec}'. Use a preset (${Object.keys(FACILITATOR_PRESET).join(" | ")}) or an http(s):// base URL.`);
749
- const cfg = { url: base.url };
750
- const headers = parseHeaders(opts.headers);
751
- if (headers) cfg.headers = headers;
752
- if (opts.verifyPath) cfg.verifyPath = opts.verifyPath;
753
- if (opts.settlePath) cfg.settlePath = opts.settlePath;
754
- return cfg;
755
- }
756
- function parseHeaders(raw) {
757
- if (!raw || raw.length === 0) return void 0;
758
- const headers = {};
759
- for (const entry of raw) {
760
- const idx = entry.indexOf(":");
761
- if (idx === -1) throw new Error(`Malformed facilitator header '${entry}' (expected 'Key: Value').`);
762
- headers[entry.slice(0, idx).trim()] = entry.slice(idx + 1).trim();
763
- }
764
- return headers;
765
- }
766
- /**
767
- * The settle-first ladder: verify the signed payment, and — only when valid —
768
- * settle it. On an invalid verification, settlement is skipped and a
769
- * `success:false` receipt body is synthesised so the payer still reaches a
770
- * terminal `payment-failed`. A facilitator HTTP failure throws
771
- * `X402FacilitatorError` (the caller surfaces it as a typed outcome).
772
- */
773
- async function settleToReceipt(pp, facilitator, signal) {
774
- const verification = await verifyPayment(pp, {
775
- facilitator,
776
- signal
777
- });
778
- if (verification.isValid) {
779
- const settlement = await settlePayment(pp, {
780
- facilitator,
781
- signal
782
- });
783
- return {
784
- status: settlement.success ? "settled" : "settlement-failed",
785
- receiptBody: settlement
786
- };
787
- }
788
- return {
789
- status: "verification-failed",
790
- receiptBody: {
791
- success: false,
792
- transaction: "",
793
- network: pp.accepted.network,
794
- payer: pp.payload.authorization.from,
795
- errorReason: verification.invalidReason ?? "verification_failed"
796
- }
797
- };
798
- }
799
- //#endregion
800
739
  //#region src/x402-receipt.ts
801
740
  /**
802
- * Build the `x402_receipt` message from the settlement body, HPKE-encrypt it to the
803
- * PAYER (the payment's original sender), and reply in-thread as the payee. Returns
804
- * the sent message. `emitMarker` toggles the cleartext `{status,rail}` marker.
805
- */
806
- async function sendReceipt(params) {
807
- const built = buildReceiptMessage(params.receiptBody, { emitMarker: params.emitMarker });
808
- const recipientKeys = await fetchRecipientKeys(params.client, params.payerAgentId);
809
- const encrypted = await encryptMessage(params.configDir, params.payeeAgentId, recipientKeys.encryption, built.payload, recipientKeys.pqEncryption);
810
- const body = {
811
- type: built.type,
812
- content_type: built.content_type,
813
- payload_schema: built.payload_schema,
814
- ...encrypted
815
- };
816
- if (built.metadata) body.metadata = built.metadata;
817
- return await params.client.post(`/messages/${params.messageId}/reply`, body, { "X-Rine-Agent": params.payeeAgentId });
818
- }
819
- /**
820
741
  * Render the terminal fulfill outcome — JSON (machine) or a human table. The typed
821
742
  * `status` (`settled` / `settlement-failed` / `verification-failed`) is authoritative;
822
- * `sent` is the receipt message the payer will read.
743
+ * `sent` is the receipt message the payer will read. The `matchedQuote` (the
744
+ * payee-issued quote the payment answered — `message_id` `null` for an operator
745
+ * override) is surfaced so an integration can bind the good it delivers to the
746
+ * quote that was actually reconciled + settled.
823
747
  */
824
748
  function reportFulfill(json, outcome, sent) {
825
- const { status, receiptBody } = outcome;
749
+ const { status, receiptBody, matchedQuote } = outcome;
826
750
  if (json) {
827
751
  printJson({
828
752
  status,
@@ -831,7 +755,8 @@ function reportFulfill(json, outcome, sent) {
831
755
  success: receiptBody.success,
832
756
  transaction: receiptBody.transaction || null,
833
757
  network: receiptBody.network,
834
- payer: receiptBody.payer
758
+ payer: receiptBody.payer,
759
+ matched_quote: matchedQuoteToWire(matchedQuote)
835
760
  });
836
761
  return;
837
762
  }
@@ -859,6 +784,14 @@ function reportFulfill(json, outcome, sent) {
859
784
  {
860
785
  Field: "Network",
861
786
  Value: receiptBody.network
787
+ },
788
+ {
789
+ Field: "Quote",
790
+ Value: matchedQuote.quoteMessageId ?? "(operator override)"
791
+ },
792
+ {
793
+ Field: "Quote amount",
794
+ Value: `${matchedQuote.amount} ${matchedQuote.asset}`
862
795
  }
863
796
  ]);
864
797
  }
@@ -869,7 +802,7 @@ function collectHeader(v, acc) {
869
802
  return acc;
870
803
  }
871
804
  function registerFulfill(program) {
872
- program.command("fulfill").description("Settle a received x402_payment via the facilitator and reply with an x402_receipt").argument("<message-id>", "ID of the received rine.v1.x402_payment").option("--agent <id>", "Payee agent ID (defaults to your agent)").option("--facilitator <preset|url>", "Facilitator preset (cdp | payai | x402-rs) or an http(s):// base URL", "payai").option("--facilitator-header <k:v>", "Auth header for the facilitator (repeatable), e.g. 'Authorization: Bearer …'", collectHeader, []).option("--verify-path <path>", "Override the facilitator /verify path").option("--settle-path <path>", "Override the facilitator /settle path").option("--no-marker", "Omit the cleartext status marker (fully sealed)").action(withClient(program, async ({ client, gOpts, configDir, apiUrl }, messageId, opts) => {
805
+ program.command("fulfill").description("Settle a received x402_payment via the facilitator and reply with an x402_receipt. The payment is bound to the ONE payee-issued x402_payment_required quote it references (the signed quoteMessageId) and reconciled against THAT quote (payTo/amount/asset/network/scheme) — the payer's echoed terms are never trusted. A payment carrying no/forged/cross-conversation quote reference REFUSES to settle (fail closed) unless explicit expected terms (--pay-to/--expect-amount/--expect-asset/--expect-network) authorise an out-of-band quote.").argument("<message-id>", "ID of the received rine.v1.x402_payment").option("--agent <id>", "Payee agent ID (defaults to your agent)").option("--facilitator <preset|url>", "Facilitator preset (cdp | payai | x402-rs) or an http(s):// base URL", "payai").option("--facilitator-header <k:v>", "Auth header for the facilitator (repeatable), e.g. 'Authorization: Bearer …'", collectHeader, []).option("--verify-path <path>", "Override the facilitator /verify path").option("--settle-path <path>", "Override the facilitator /settle path").option("--pay-to <address>", "Out-of-band quote: expected payee wallet (0x). Requires --expect-amount/--expect-asset/--expect-network; overrides the referenced quote (no quoteMessageId needed)").option("--expect-amount <major>", "Out-of-band quote: expected amount in MAJOR units (e.g. 1.00). Overpayment is accepted, underpayment refused").option("--expect-asset <address>", "Out-of-band quote: expected token contract (0x)").option("--expect-network <caip2>", "Out-of-band quote: expected CAIP-2 network (e.g. eip155:8453)").option("--no-marker", "Omit the cleartext status marker (fully sealed)").action(withClient(program, async ({ client, gOpts, configDir, apiUrl }, messageId, opts) => {
873
806
  const message = await client.get(`/messages/${messageId}`);
874
807
  if (message.type !== X402_MESSAGE_TYPE.PAYMENT) {
875
808
  printError(`Message ${messageId} is '${message.type}', not ${X402_MESSAGE_TYPE.PAYMENT}. Nothing to fulfill.`);
@@ -895,8 +828,8 @@ function registerFulfill(program) {
895
828
  }
896
829
  let facilitator;
897
830
  try {
898
- facilitator = resolveFacilitator(opts.facilitator, {
899
- headers: opts.facilitatorHeader,
831
+ facilitator = resolveFacilitatorConfig(opts.facilitator, {
832
+ headers: parseFacilitatorHeaders(opts.facilitatorHeader),
900
833
  verifyPath: opts.verifyPath,
901
834
  settlePath: opts.settlePath
902
835
  });
@@ -906,10 +839,69 @@ function registerFulfill(program) {
906
839
  return;
907
840
  }
908
841
  const decrypted = await decryptMessage(configDir, payeeAgentId, message.encrypted_payload, client);
909
- const pp = parseX402Payload(message.type, decrypted.plaintext);
842
+ let pp;
843
+ try {
844
+ pp = parseX402Payload(message.type, decrypted.plaintext);
845
+ } catch (err) {
846
+ if (!(err instanceof X402Error)) throw err;
847
+ const sent = await sendReceipt({
848
+ client,
849
+ configDir,
850
+ payeeAgentId,
851
+ payerAgentId,
852
+ messageId,
853
+ receiptBody: refusalReceiptBody("", "", err.code),
854
+ emitMarker: opts.marker !== false
855
+ });
856
+ printError(`Malformed payment payload: ${err.message}`);
857
+ if (gOpts.json) printJson({
858
+ status: "malformed-payload",
859
+ code: err.code,
860
+ detail: err.message,
861
+ receipt_id: sent.id
862
+ });
863
+ process.exitCode = 1;
864
+ return;
865
+ }
866
+ let resolved;
867
+ try {
868
+ resolved = await resolvePayeeRequirement({
869
+ payment: pp,
870
+ expected: {
871
+ payTo: opts.payTo,
872
+ expectAmount: opts.expectAmount,
873
+ expectAsset: opts.expectAsset,
874
+ expectNetwork: opts.expectNetwork
875
+ },
876
+ client,
877
+ configDir,
878
+ payeeAgentId,
879
+ conversationId: message.conversation_id
880
+ });
881
+ } catch (err) {
882
+ if (!(err instanceof X402Error)) throw err;
883
+ const sent = await sendReceipt({
884
+ client,
885
+ configDir,
886
+ payeeAgentId,
887
+ payerAgentId,
888
+ messageId,
889
+ receiptBody: refusalReceiptBody(pp.accepted.network, pp.payload.authorization.from, err.code),
890
+ emitMarker: opts.marker !== false
891
+ });
892
+ printError(`Refusing to settle: ${err.message}`);
893
+ if (gOpts.json) printJson({
894
+ status: "payment-refused",
895
+ code: err.code,
896
+ detail: err.message,
897
+ receipt_id: sent.id
898
+ });
899
+ process.exitCode = 1;
900
+ return;
901
+ }
910
902
  let outcome;
911
903
  try {
912
- outcome = await settleToReceipt(pp, facilitator);
904
+ outcome = await settleToReceipt(pp, resolved, facilitator);
913
905
  } catch (err) {
914
906
  if (err instanceof X402FacilitatorError) {
915
907
  printError(`Facilitator error${err.status ? ` (${err.status})` : ""}: ${err.message}`);
@@ -1938,7 +1930,7 @@ function registerPay(program) {
1938
1930
  return;
1939
1931
  }
1940
1932
  }
1941
- const built = buildPaymentMessage(buildPaymentPayload(pr, requirement, loadWalletKey(configDir, payerAgentId)), { emitMarker: opts.marker !== false });
1933
+ const built = buildPaymentMessage(buildPaymentPayload(pr, requirement, loadWalletKey(configDir, payerAgentId), { quoteMessageId: messageId }), { emitMarker: opts.marker !== false });
1942
1934
  const recipientKeys = await fetchRecipientKeys(client, payeeAgentId);
1943
1935
  const encrypted = await encryptMessage(configDir, payerAgentId, recipientKeys.encryption, built.payload, recipientKeys.pqEncryption);
1944
1936
  const body = {
@@ -2371,9 +2363,9 @@ var UnsupportedTierError = class extends Error {
2371
2363
  }
2372
2364
  };
2373
2365
  /**
2374
- * (AUD-A1) Assert the zero-trust hostname resolves to an A record before
2366
+ * Assert the zero-trust hostname resolves to an A record before
2375
2367
  * declaring the listener ready. The per-agent `*.{agentLabel}.hook` A is a
2376
- * DELIVERY prerequisite written best-effort by the backend (REQ-OPS-04); a
2368
+ * DELIVERY prerequisite written best-effort by the backend; a
2377
2369
  * healthy cert does NOT imply a routable name (DNS-01 validates the independent
2378
2370
  * challenge TXT). Non-fatal — emit a loud `dns_a_missing` event and continue (the
2379
2371
  * cert is valid and the backend self-heals the A on the next ZT-hook create), so
@@ -2445,6 +2437,17 @@ function emitLifecycle(gOpts, monitor, data) {
2445
2437
  function jitteredDelayMs(backoffSeconds) {
2446
2438
  return Math.round(backoffSeconds * (.5 + Math.random()) * 1e3);
2447
2439
  }
2440
+ /**
2441
+ * Encryption versions the stream preview can decrypt. A payload carrying one of
2442
+ * these that still fails is reported as "[decrypt failed]" rather than the
2443
+ * misleading "[encrypted]", which is reserved for versions we never attempt.
2444
+ */
2445
+ const DECRYPTABLE_VERSIONS = new Set([
2446
+ "hpke-v1",
2447
+ "hpke-hybrid-v1",
2448
+ "sender-key-v1",
2449
+ "mls-v1"
2450
+ ]);
2448
2451
  async function formatMessageLine(dataStr, agentId, configDir, client) {
2449
2452
  try {
2450
2453
  const data = JSON.parse(dataStr);
@@ -2455,7 +2458,7 @@ async function formatMessageLine(dataStr, agentId, configDir, client) {
2455
2458
  let preview = "[encrypted]";
2456
2459
  if (data.encrypted_payload && agentKeysExist(configDir, agentId)) {
2457
2460
  let result;
2458
- if (data.encryption_version === "sender-key-v1" && data.group_id) try {
2461
+ if ((data.encryption_version === "sender-key-v1" || data.encryption_version === "mls-v1") && data.group_id) try {
2459
2462
  result = await decryptGroupMessage(configDir, agentId, data.group_id, data.encrypted_payload, client);
2460
2463
  } catch (err) {
2461
2464
  const match = err instanceof Error && err.message.match(/^unknown sender key id: (.+)$/);
@@ -2465,13 +2468,13 @@ async function formatMessageLine(dataStr, agentId, configDir, client) {
2465
2468
  } catch {}
2466
2469
  }
2467
2470
  }
2468
- else if (data.encryption_version === "hpke-v1") try {
2471
+ else if (data.encryption_version === "hpke-v1" || data.encryption_version === "hpke-hybrid-v1") try {
2469
2472
  result = await decryptMessage(configDir, agentId, data.encrypted_payload, client);
2470
2473
  } catch {}
2471
2474
  if (result) {
2472
2475
  ingestSenderKeyDistribution(configDir, agentId, data.type ?? "", result);
2473
2476
  preview = `[${result.verified ? "✓" : "?"}] ${result.plaintext.slice(0, 60)}`;
2474
- } else if (data.encryption_version === "hpke-v1" || data.encryption_version === "sender-key-v1") preview = "[decrypt failed]";
2477
+ } else if (DECRYPTABLE_VERSIONS.has(data.encryption_version ?? "")) preview = "[decrypt failed]";
2475
2478
  }
2476
2479
  return `[${ts}] ${sender} \u2192 ${target}: ${preview}`;
2477
2480
  } catch {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rine-network/cli",
3
- "version": "0.16.0",
3
+ "version": "0.17.0",
4
4
  "description": "CLI client for rine.network \u2014 EU-first messaging infrastructure for AI agents",
5
5
  "author": "mmmbs <mmmbs@proton.me>",
6
6
  "license": "EUPL-1.2",
@@ -28,7 +28,7 @@
28
28
  "dev": "tsx src/main.ts"
29
29
  },
30
30
  "dependencies": {
31
- "@rine-network/core": "^0.11.0",
31
+ "@rine-network/core": "^0.12.0",
32
32
  "commander": "^12.0.0",
33
33
  "eventsource-client": "^1.1.0"
34
34
  },