@sohopay/agent-signer 0.0.0-stage → 0.3.1

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 (54) hide show
  1. package/README.md +239 -2
  2. package/dist/cli/args.d.ts +18 -0
  3. package/dist/cli/args.js +97 -0
  4. package/dist/cli/commands.d.ts +37 -0
  5. package/dist/cli/commands.js +228 -0
  6. package/dist/cli/index.d.ts +2 -0
  7. package/dist/cli/index.js +32 -0
  8. package/dist/cli/io-schema.d.ts +2 -0
  9. package/dist/cli/io-schema.js +55 -0
  10. package/dist/cli/io.d.ts +18 -0
  11. package/dist/cli/io.js +56 -0
  12. package/dist/cli/key-generate.d.ts +8 -0
  13. package/dist/cli/key-generate.js +77 -0
  14. package/dist/cli/key-path.d.ts +5 -0
  15. package/dist/cli/key-path.js +156 -0
  16. package/dist/cli/node-floor.d.ts +4 -0
  17. package/dist/cli/node-floor.js +11 -0
  18. package/dist/cli/run.d.ts +11 -0
  19. package/dist/cli/run.js +118 -0
  20. package/dist/cli/signer-config.d.ts +5 -0
  21. package/dist/cli/signer-config.js +84 -0
  22. package/dist/cli/verify-vectors.d.ts +8 -0
  23. package/dist/cli/verify-vectors.js +116 -0
  24. package/dist/constants.d.ts +24 -0
  25. package/dist/constants.js +34 -0
  26. package/dist/encoding.d.ts +5 -0
  27. package/dist/encoding.js +5 -0
  28. package/dist/envelope.d.ts +11 -0
  29. package/dist/envelope.js +20 -0
  30. package/dist/errors.d.ts +7 -0
  31. package/dist/errors.js +9 -0
  32. package/dist/flow.d.ts +70 -0
  33. package/dist/flow.js +62 -0
  34. package/dist/idempotency.d.ts +32 -0
  35. package/dist/idempotency.js +45 -0
  36. package/dist/index.d.ts +12 -0
  37. package/dist/index.js +12 -0
  38. package/dist/jcs.d.ts +8 -0
  39. package/dist/jcs.js +15 -0
  40. package/dist/keys.d.ts +28 -0
  41. package/dist/keys.js +64 -0
  42. package/dist/operations.d.ts +107 -0
  43. package/dist/operations.js +151 -0
  44. package/dist/pop.d.ts +19 -0
  45. package/dist/pop.js +27 -0
  46. package/dist/rotation.d.ts +41 -0
  47. package/dist/rotation.js +33 -0
  48. package/dist/storage.d.ts +38 -0
  49. package/dist/storage.js +116 -0
  50. package/dist/terminal.d.ts +18 -0
  51. package/dist/terminal.js +90 -0
  52. package/dist/voucher.d.ts +39 -0
  53. package/dist/voucher.js +86 -0
  54. package/package.json +42 -4
package/README.md CHANGED
@@ -1,3 +1,240 @@
1
- # Temporary Holding Version
1
+ # @sohopay/agent-signer
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Deterministic client-side signer for SohoPay **Protocol V2** agent payments.
4
+
5
+ This is the small, exact-by-construction piece that must run on the agent side: it
6
+ produces the Ed25519 **voucher** and **proof-of-possession** signatures, the
7
+ `paymentId`, and the RFC 7638 key thumbprint — byte-for-byte compatible with the
8
+ SohoPay backend verifier. It replaces the hand-executed "signing recipe" that
9
+ previously lived in prose inside the agent skills.
10
+
11
+ It is **not** an MCP client. The agent host already provides transport, OAuth,
12
+ and tool invocation; this library only owns the crypto and key handling those
13
+ hosts cannot safely do for you.
14
+
15
+ ## Security boundary
16
+
17
+ - Holds the **agent workload key** only. It **never** touches a borrower key —
18
+ borrower authorization is an EIP-712 signature made off-device in the
19
+ borrower's own wallet.
20
+ - The server stays the authority for policy, idempotency, and settlement. This
21
+ library only signs; it does not decide whether a payment is allowed.
22
+ - A JWK carrying private material (`d`) is rejected. The server's advertised
23
+ `signing` block is validated against a compiled-in allowlist and never
24
+ substituted — the SDK will not sign under a scheme it does not implement.
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ npm install @sohopay/agent-signer
30
+ ```
31
+
32
+ ## Usage
33
+
34
+ ```ts
35
+ import {
36
+ generateWorkloadKey,
37
+ signPoP,
38
+ computePaymentId,
39
+ signVoucher,
40
+ buildPaymentSignatureHeader,
41
+ } from "@sohopay/agent-signer";
42
+
43
+ // 1. Once per terminal: generate and persist the workload key (private seed stays local).
44
+ const key = generateWorkloadKey();
45
+
46
+ // 2. Register it: sign the proof-of-possession challenge.
47
+ const { pop_signature } = signPoP(
48
+ { borrowerId, terminalId, jkt: key.jkt, nonce, iat: Math.floor(Date.now() / 1000) },
49
+ key.privateKeyBase64Url,
50
+ );
51
+
52
+ // 3. On VOUCHER_ISSUED from prepare_x402_payment: sign the voucher.
53
+ const { signature } = signVoucher({
54
+ voucher, // from the prepare response
55
+ signing, // the prepare response's `signing` block (validated)
56
+ privateKeyBase64Url: key.privateKeyBase64Url,
57
+ publicJwk: key.publicJwk, // optional: asserts voucher.agentKeyJkt matches this key
58
+ });
59
+
60
+ // 4. Build the merchant unlock header.
61
+ const { headerName, headerValue } = buildPaymentSignatureHeader(prepareResponse, signature);
62
+ ```
63
+
64
+ All signing is fail-closed: `signVoucher` recomputes and checks the `paymentId`
65
+ and the key thumbprint before producing a signature, and every failure throws a
66
+ `SignerError` with a stable `code`.
67
+
68
+ ## Parity testing
69
+
70
+ Correctness is defined by cross-language known-answer vectors generated from the
71
+ backend's own verifier. During development the test suite reads those vectors
72
+ from the backend repo; override the location with `SIGNER_VECTORS_PATH`.
73
+
74
+ ```bash
75
+ npm test # parity suite (node --test)
76
+ npm run build # emit dist/
77
+ ```
78
+
79
+ ## Install-free bundle (no npm registry required)
80
+
81
+ A single self-contained `sohopay-signer.mjs` runs on any host with Node >= 18 — no
82
+ `node_modules`, no network. Download it from the matching `js-bundle-v<version>` GitHub
83
+ Release, **verify**, then point `$SOHOPAY_SIGNER` at it.
84
+
85
+ ### Download and verify
86
+
87
+ 1. Download the exact version you want (never `latest`):
88
+
89
+ V=0.3.1 # the js-bundle-v<version> you intend to run
90
+ gh release download "js-bundle-v$V" --repo sohopay/sohopay-agent-signer \
91
+ --pattern 'sohopay-signer.mjs' --pattern 'sohopay-signer.mjs.sha256'
92
+
93
+ 2. Verify. **Online (preferred)** — ties the file to the build workflow + commit:
94
+
95
+ gh attestation verify sohopay-signer.mjs --repo sohopay/sohopay-agent-signer
96
+
97
+ **Offline / air-gapped** — compare against the expected hash for that exact version
98
+ published in the table below (updated per release). Note: the downloaded `.sha256` is
99
+ a convenience against file corruption in transit, **not the trust anchor**; a
100
+ compromised release could swap both files. Trust only the out-of-release table:
101
+
102
+ sha256sum sohopay-signer.mjs # compare to the table below
103
+
104
+ 3. Install and verify:
105
+
106
+ chmod +x sohopay-signer.mjs
107
+ export SOHOPAY_SIGNER="$PWD/sohopay-signer.mjs"
108
+ sohopay-signer capabilities # expect signer_protocol: sohopay-signer/1
109
+ sohopay-signer verify-vectors # expect exit 0
110
+
111
+ ### Expected hashes (trust anchor, out-of-release)
112
+
113
+ | Version | sha256 of `sohopay-signer.mjs` |
114
+ |---------|--------------------------------|
115
+ | _(add a row per release)_ | _(the hash from the release build)_ |
116
+
117
+ ### Supported invocation forms
118
+
119
+ The bundle supports three ways to run:
120
+
121
+ - **`node sohopay-signer.mjs <command> [args]`** — explicit Node invocation; always works
122
+ - **`./sohopay-signer.mjs <command> [args]`** — direct execution after `chmod +x`; works with Node >= 18.13 and modern shebangs
123
+ - **Symlink on PATH** — `ln -s /path/to/sohopay-signer.mjs ~/bin/sohopay-signer` → `sohopay-signer <command>` (Node resolves the `.mjs` extension)
124
+
125
+ **Not supported:** copying to an extensionless name (e.g. `cp sohopay-signer.mjs sohopay-signer`). On older Node versions this fails (Node parses an extensionless file as CommonJS and the ESM bundle errors); on Node >= 22.7 it may run via module auto-detection, but the behavior is version-dependent. Use the `.mjs` name or a symlink to it instead.
126
+
127
+ ### Releasing the bundle
128
+
129
+ **One-time repo setup (must be in place before the first release — these are the trust controls the install flow above relies on):**
130
+
131
+ - Make the repo **public** — required for token-free asset download and `gh attestation verify` support.
132
+ - Enable **immutable releases** and **`js-bundle-v*` tag protection** so published assets and tags cannot be replaced after the fact.
133
+
134
+ To release, once the above are enabled:
135
+
136
+ 1. Tag the commit: `git tag "js-bundle-v<version>"` where `<version>` matches `package.json`
137
+ 2. Push the tag: `git push origin "js-bundle-v<version>"` — GitHub Actions builds and publishes the release automatically
138
+ 3. Add the new version row to the "Expected hashes" table above on the `main` branch to record the trust anchor for future verifications.
139
+
140
+ With immutable releases enabled, a published release is permanent — its assets cannot be swapped.
141
+
142
+ ## CLI (sohopay-signer)
143
+
144
+ The package ships a `sohopay-signer` bin for shell-capable agent hosts. It is a
145
+ thin wrapper over the SDK above and is protocol-versioned as `sohopay-signer/1`.
146
+
147
+ ```bash
148
+ npx @sohopay/agent-signer capabilities --output json
149
+ ```
150
+
151
+ ### Machine interface
152
+
153
+ - `--input -` reads a JSON object from **stdin**; `--output json` emits a single
154
+ JSON object to **stdout** and nothing else.
155
+ - With `voucher sign --envelope --write-header <path>`, the opaque `header_value`
156
+ (and the `envelope`/`signature` that encode it) is written **only** to the 0600
157
+ file; stdout reports `header_file` and non-secret metadata (INV-1).
158
+ - `stderr` is diagnostics only. **A non-zero exit means failure.**
159
+ - Operational failures exit `1` with an error envelope on stderr:
160
+ ```json
161
+ { "error": { "code": "MALFORMED_ENVELOPE", "message": "..." } }
162
+ ```
163
+ Usage errors (unknown command or flag, missing flag value) exit `2` with a
164
+ plain one-line message.
165
+ - The CLI holds **agent workload keys only**; it never touches a borrower key,
166
+ and the seed is never logged.
167
+
168
+ ### Key input is reference-only
169
+
170
+ The signing key is supplied **by reference** with `--key <path>`; inline key
171
+ material in the stdin JSON (`"key": { ... }`) is rejected with
172
+ `INLINE_KEY_REJECTED`. Both `--key` and `--out` must name a file called
173
+ `secret.json` under an allowed key root (default `~/.agents/sohopay-agent-workload`;
174
+ `SOHOPAY_SIGNER_KEY_ROOTS` can only narrow it). The file must be mode `0600` and
175
+ may not be a symlink. Anything else fails with `KEY_PATH_INVALID`.
176
+
177
+ ### Commands
178
+
179
+ `key generate`: creates a new Ed25519 workload key.
180
+
181
+ ```bash
182
+ echo '{ "borrower_id": "...", "terminal_id": "..." }' \
183
+ | sohopay-signer key generate --out ~/.agents/sohopay-agent-workload/secret.json --input - --output json
184
+ # {"public_jwk":{...},"jkt":"...","borrower_id":"...","terminal_id":"...","created":true}
185
+ ```
186
+
187
+ The private key is written to `secret.json` with mode `0600` and is never
188
+ printed; stdout carries public material only.
189
+
190
+ `voucher sign`: signs the voucher issued by `prepare_x402_payment`.
191
+
192
+ ```bash
193
+ echo '{ "voucher": { ... }, "signing": { ... } }' \
194
+ | sohopay-signer voucher sign --key ~/.agents/sohopay-agent-workload/secret.json --input - --output json
195
+ # {"signer_protocol":"sohopay-signer/1","implementation":"@sohopay/agent-signer",
196
+ # "implementation_version":"0.x.y","payment_id":"0x...","agent_key_jkt":"...",
197
+ # "signature":"...","algorithm":"Ed25519"}
198
+ ```
199
+
200
+ `payment-id`: recomputes the `paymentId` from a voucher core.
201
+
202
+ ```bash
203
+ echo '{ "core": { ... } }' | sohopay-signer payment-id --input - --output json
204
+ # {"payment_id":"0x..."}
205
+ ```
206
+
207
+ `key jkt`: RFC 7638 thumbprint of a public JWK (or of the key derived from a seed).
208
+
209
+ ```bash
210
+ echo '{ "public_jwk": { ... } }' | sohopay-signer key jkt --input - --output json
211
+ # {"agent_key_jkt":"..."}
212
+ ```
213
+
214
+ `pop sign`: signs the proof-of-possession challenge for key registration.
215
+
216
+ ```bash
217
+ echo '{ "fields": { "borrowerId": "...", "terminalId": "...", "jkt": "...", "nonce": "...", "iat": 0 } }' \
218
+ | sohopay-signer pop sign --input - --key ~/.agents/sohopay-agent-workload/secret.json --output json
219
+ # {"signer_protocol":"sohopay-signer/1","implementation":"@sohopay/agent-signer",
220
+ # "implementation_version":"0.x.y","pop_signature":"...","algorithm":"Ed25519"}
221
+ ```
222
+
223
+ `verify-vectors`: runs the bundled known-answer vectors; exits `0` only if all pass.
224
+
225
+ ```bash
226
+ sohopay-signer verify-vectors --output json
227
+ # {"passed":N,"failed":0,"total":N}
228
+ ```
229
+
230
+ `capabilities`: what host routing probes to confirm a usable signer.
231
+
232
+ ```bash
233
+ sohopay-signer capabilities --output json
234
+ # {"signer_protocol":"sohopay-signer/1","implementation":"@sohopay/agent-signer",
235
+ # "implementation_version":"0.x.y","algorithms":["Ed25519"],"commands":[...]}
236
+ ```
237
+
238
+ ## License
239
+
240
+ Proprietary — SohoPay. Not for distribution.
@@ -0,0 +1,18 @@
1
+ /** Parsed CLI invocation. `input`/`key` are a path or "-" (stdin); undefined = absent. */
2
+ export interface ParsedArgs {
3
+ command: string;
4
+ input?: string;
5
+ key?: string;
6
+ out?: string;
7
+ output: "json" | "human";
8
+ envelope: boolean;
9
+ writeHeader?: string;
10
+ }
11
+ /** A caller mistake (unknown command/flag, missing value). Mapped to exit 2. */
12
+ export declare class UsageError extends Error {
13
+ constructor(message: string);
14
+ }
15
+ /** Splits argv into a known command (1–2 leading tokens) plus flags. */
16
+ export declare function parseArgs(argv: string[]): ParsedArgs;
17
+ /** True when this invocation reads stdin — "-" is the stdin sentinel for --input/--key (space- or `=`-separated). */
18
+ export declare function needsStdin(argv: string[]): boolean;
@@ -0,0 +1,97 @@
1
+ /** A caller mistake (unknown command/flag, missing value). Mapped to exit 2. */
2
+ export class UsageError extends Error {
3
+ constructor(message) {
4
+ super(message);
5
+ this.name = "UsageError";
6
+ }
7
+ }
8
+ const KNOWN_COMMANDS = new Set([
9
+ "voucher sign",
10
+ "payment-id",
11
+ "key jkt",
12
+ "key generate",
13
+ "pop sign",
14
+ "verify-vectors",
15
+ "capabilities",
16
+ ]);
17
+ function requireValue(argv, index, flag) {
18
+ const value = argv[index];
19
+ if (value === undefined) {
20
+ throw new UsageError(`${flag} requires a value`);
21
+ }
22
+ return value;
23
+ }
24
+ /** Splits argv into a known command (1–2 leading tokens) plus flags. */
25
+ export function parseArgs(argv) {
26
+ const positionals = [];
27
+ let input;
28
+ let key;
29
+ let out;
30
+ let output = "human";
31
+ let envelope = false;
32
+ let writeHeader;
33
+ for (let i = 0; i < argv.length; i++) {
34
+ const token = argv[i];
35
+ if (token === undefined) {
36
+ continue;
37
+ }
38
+ if (token.startsWith("--")) {
39
+ // Accept both `--flag value` and `--flag=value`.
40
+ const eq = token.indexOf("=");
41
+ const name = eq === -1 ? token : token.slice(0, eq);
42
+ const inlineValue = eq === -1 ? undefined : token.slice(eq + 1);
43
+ const valueOf = (flag) => inlineValue ?? requireValue(argv, ++i, flag);
44
+ if (name === "--input") {
45
+ input = valueOf("--input");
46
+ }
47
+ else if (name === "--key") {
48
+ key = valueOf("--key");
49
+ }
50
+ else if (name === "--out") {
51
+ out = valueOf("--out");
52
+ }
53
+ else if (name === "--output") {
54
+ const value = valueOf("--output");
55
+ if (value !== "json" && value !== "human") {
56
+ throw new UsageError(`--output must be "json" or "human", got "${value}"`);
57
+ }
58
+ output = value;
59
+ }
60
+ else if (name === "--envelope") {
61
+ envelope = true; // boolean flag; any inline value is ignored
62
+ }
63
+ else if (name === "--write-header") {
64
+ writeHeader = valueOf("--write-header");
65
+ }
66
+ else {
67
+ throw new UsageError(`unknown flag: ${name}`);
68
+ }
69
+ }
70
+ else {
71
+ positionals.push(token);
72
+ }
73
+ }
74
+ const twoToken = positionals.slice(0, 2).join(" ");
75
+ const oneToken = positionals[0] ?? "";
76
+ let command;
77
+ let commandTokens;
78
+ if (KNOWN_COMMANDS.has(twoToken)) {
79
+ command = twoToken;
80
+ commandTokens = 2;
81
+ }
82
+ else if (KNOWN_COMMANDS.has(oneToken)) {
83
+ command = oneToken;
84
+ commandTokens = 1;
85
+ }
86
+ else {
87
+ throw new UsageError(`unknown command: ${positionals.join(" ") || "(none)"}`);
88
+ }
89
+ if (positionals.length > commandTokens) {
90
+ throw new UsageError(`unexpected argument: ${positionals[commandTokens]}`);
91
+ }
92
+ return { command, input, key, out, output, envelope, writeHeader };
93
+ }
94
+ /** True when this invocation reads stdin — "-" is the stdin sentinel for --input/--key (space- or `=`-separated). */
95
+ export function needsStdin(argv) {
96
+ return argv.some((token) => token === "-" || token === "--input=-" || token === "--key=-");
97
+ }
@@ -0,0 +1,37 @@
1
+ import { type ResolvedKey } from "./io.js";
2
+ /** The signer's implementation version: build-injected in the bundle, else from package.json. */
3
+ export declare function implementationVersion(): string;
4
+ /** Static advertisement SP5 routing probes to confirm a usable signer. */
5
+ export declare function capabilitiesResult(): Record<string, unknown>;
6
+ /** `{ core } → { payment_id }`. */
7
+ export declare function paymentIdResult(input: unknown): Record<string, unknown>;
8
+ type KeyOpts = {
9
+ homeDir?: string;
10
+ env?: NodeJS.ProcessEnv;
11
+ };
12
+ /** `{ public_jwk } | { key: { public_jwk | private_key_base64url } } → { agent_key_jkt }`. */
13
+ export declare function keyJktResult(input: unknown): Record<string, unknown>;
14
+ /**
15
+ * Resolves the signing key from a validated `--key <path>` file only. Inline key
16
+ * material is rejected first (INV-3) so a secret never travels through input JSON.
17
+ */
18
+ export declare function resolveSigningKey(input: Record<string, unknown>, keyFileSource: string | undefined, stdin: string, opts?: KeyOpts): ResolvedKey;
19
+ /** `{ voucher, signing?, key? } (+ optional --key) → signed result`. */
20
+ export declare function voucherSignResult(input: unknown, keyFileSource: string | undefined, stdin: string, opts?: KeyOpts): Record<string, unknown>;
21
+ /**
22
+ * `--envelope`: `{ voucher, signing?, envelope, header_name, key? } (+ optional --key)`
23
+ * -> signed result plus the completed x402 envelope and PAYMENT-SIGNATURE header.
24
+ * Fills ONLY paymentPayload.payload.signature; never re-signs a filled envelope.
25
+ */
26
+ export declare function voucherSignEnvelopeResult(input: unknown, keyFileSource: string | undefined, stdin: string, opts?: KeyOpts): Record<string, unknown>;
27
+ /** `{ fields: { borrowerId, terminalId, jkt } } (+ --key <path>) → { …, pop_signature, nonce, iat }`. */
28
+ export declare function popSignResult(input: unknown, keyFileSource: string | undefined, _stdin: string, opts?: {
29
+ homeDir?: string;
30
+ env?: NodeJS.ProcessEnv;
31
+ }): Record<string, unknown>;
32
+ /** `verify-vectors → ({ passed, failed, total }, ok)`; ok drives the exit code. */
33
+ export declare function verifyVectorsResult(): {
34
+ result: Record<string, unknown>;
35
+ ok: boolean;
36
+ };
37
+ export {};
@@ -0,0 +1,228 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { readFileSync } from "node:fs";
3
+ import { IMPLEMENTATION, SIGNER_PROTOCOL, SUPPORTED_SIGNING } from "../constants.js";
4
+ import { toBase64Url } from "../encoding.js";
5
+ import { buildPaymentSignatureHeader } from "../envelope.js";
6
+ import { SignerError } from "../errors.js";
7
+ import { computeJkt, decodeWorkloadSeed, workloadKeyFromPrivate } from "../keys.js";
8
+ import { signPoP } from "../pop.js";
9
+ import { computePaymentId, signVoucher, } from "../voucher.js";
10
+ import { loadKeyFile } from "../storage.js";
11
+ import { validateKeyPath } from "./key-path.js";
12
+ import { readKeyFile, resolveKeyBlock } from "./io.js";
13
+ import { verifyVectors } from "./verify-vectors.js";
14
+ /** The signer's implementation version: build-injected in the bundle, else from package.json. */
15
+ export function implementationVersion() {
16
+ if (typeof __SIGNER_IMPL_VERSION__ !== "undefined" && __SIGNER_IMPL_VERSION__) {
17
+ return __SIGNER_IMPL_VERSION__;
18
+ }
19
+ // Below is the tsc/tsx path only. In the esbuild bundle the `define` above makes the
20
+ // first branch always true, so this package.json read is dead there — its relative
21
+ // `../../package.json` URL would not resolve from the single-file bundle if ever reached.
22
+ const pkg = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
23
+ if (!pkg.version) {
24
+ throw new Error("implementation_version could not be resolved from package.json");
25
+ }
26
+ return pkg.version;
27
+ }
28
+ const COMMANDS = ["voucher sign", "payment-id", "key jkt", "key generate", "pop sign", "verify-vectors", "capabilities"];
29
+ const COMMAND_CONTRACTS = {
30
+ "key generate": "workload-keygen/1",
31
+ "pop sign": "pop-sign/1",
32
+ };
33
+ /** Static advertisement SP5 routing probes to confirm a usable signer. */
34
+ export function capabilitiesResult() {
35
+ return {
36
+ signer_protocol: SIGNER_PROTOCOL,
37
+ implementation: IMPLEMENTATION,
38
+ implementation_version: implementationVersion(),
39
+ algorithms: [SUPPORTED_SIGNING.algorithm],
40
+ commands: COMMANDS,
41
+ command_contracts: COMMAND_CONTRACTS,
42
+ };
43
+ }
44
+ /** `{ core } → { payment_id }`. */
45
+ export function paymentIdResult(input) {
46
+ const core = input?.core;
47
+ if (core === null || typeof core !== "object") {
48
+ throw new SignerError("MALFORMED_ENVELOPE", "payment-id requires a `core` object");
49
+ }
50
+ return { payment_id: computePaymentId(core) };
51
+ }
52
+ /** `{ public_jwk } | { key: { public_jwk | private_key_base64url } } → { agent_key_jkt }`. */
53
+ export function keyJktResult(input) {
54
+ const record = (input ?? {});
55
+ const block = record.public_jwk !== undefined ? { public_jwk: record.public_jwk } : record.key;
56
+ if (block && typeof block === "object" && block.private_key_base64url !== undefined) {
57
+ throw new SignerError("INLINE_KEY_REJECTED", "key jkt does not accept inline private key material; pass public_jwk");
58
+ }
59
+ const key = resolveKeyBlock(block);
60
+ if (key.publicJwk) {
61
+ return { agent_key_jkt: computeJkt(key.publicJwk) };
62
+ }
63
+ if (key.privateKeyBase64Url) {
64
+ return { agent_key_jkt: workloadKeyFromPrivate(key.privateKeyBase64Url).jkt };
65
+ }
66
+ throw new SignerError("MALFORMED_ENVELOPE", "key jkt requires public_jwk or a key with private/public material");
67
+ }
68
+ /**
69
+ * Resolves the signing key from a validated `--key <path>` file only. Inline key
70
+ * material is rejected first (INV-3) so a secret never travels through input JSON.
71
+ */
72
+ export function resolveSigningKey(input, keyFileSource, stdin, opts = {}) {
73
+ if (input.key !== undefined) {
74
+ throw new SignerError("INLINE_KEY_REJECTED", "inline key material is not accepted; use --key <path>");
75
+ }
76
+ if (keyFileSource === undefined) {
77
+ throw new SignerError("MALFORMED_INPUT", "signing requires --key <path>");
78
+ }
79
+ const key = readKeyFile(keyFileSource, stdin, opts);
80
+ // Validate the seed here so a malformed key surfaces as INVALID_PRIVATE_KEY on
81
+ // every signing path — even when a public_jwk is supplied and the SDK would
82
+ // otherwise only decode the seed deep inside ed25519.sign.
83
+ if (key.privateKeyBase64Url !== undefined) {
84
+ decodeWorkloadSeed(key.privateKeyBase64Url);
85
+ }
86
+ return key;
87
+ }
88
+ /** `{ voucher, signing?, key? } (+ optional --key) → signed result`. */
89
+ export function voucherSignResult(input, keyFileSource, stdin, opts = {}) {
90
+ const record = (input ?? {});
91
+ const voucher = record.voucher;
92
+ if (voucher === null || typeof voucher !== "object") {
93
+ throw new SignerError("MALFORMED_ENVELOPE", "voucher sign requires a `voucher` object");
94
+ }
95
+ const key = resolveSigningKey(record, keyFileSource, stdin, opts);
96
+ if (!key.privateKeyBase64Url) {
97
+ throw new SignerError("MALFORMED_ENVELOPE", "signing key is missing private_key_base64url");
98
+ }
99
+ const { signature } = signVoucher({
100
+ voucher,
101
+ privateKeyBase64Url: key.privateKeyBase64Url,
102
+ signing: record.signing,
103
+ // Derive the public key from the seed when absent so the jkt-binding guard always runs.
104
+ publicJwk: key.publicJwk ?? workloadKeyFromPrivate(key.privateKeyBase64Url).publicJwk,
105
+ });
106
+ return {
107
+ signer_protocol: SIGNER_PROTOCOL,
108
+ implementation: IMPLEMENTATION,
109
+ implementation_version: implementationVersion(),
110
+ payment_id: voucher.paymentId,
111
+ agent_key_jkt: voucher.agentKeyJkt,
112
+ signature,
113
+ algorithm: SUPPORTED_SIGNING.algorithm,
114
+ };
115
+ }
116
+ /**
117
+ * `--envelope`: `{ voucher, signing?, envelope, header_name, key? } (+ optional --key)`
118
+ * -> signed result plus the completed x402 envelope and PAYMENT-SIGNATURE header.
119
+ * Fills ONLY paymentPayload.payload.signature; never re-signs a filled envelope.
120
+ */
121
+ export function voucherSignEnvelopeResult(input, keyFileSource, stdin, opts = {}) {
122
+ const record = (input ?? {});
123
+ const voucher = record.voucher;
124
+ if (voucher === null || typeof voucher !== "object") {
125
+ throw new SignerError("MALFORMED_ENVELOPE", "voucher sign --envelope requires a `voucher` object");
126
+ }
127
+ const prepareEnvelope = record.envelope;
128
+ if (prepareEnvelope === null || typeof prepareEnvelope !== "object") {
129
+ throw new SignerError("MALFORMED_ENVELOPE", "voucher sign --envelope requires an `envelope` object");
130
+ }
131
+ const headerName = record.header_name;
132
+ if (typeof headerName !== "string" || headerName.length === 0) {
133
+ throw new SignerError("MALFORMED_ENVELOPE", "voucher sign --envelope requires a non-empty string `header_name`");
134
+ }
135
+ // header_name is emitted into a curl-ready header line ("<name>: <value>\n"), so it
136
+ // must be a valid HTTP field-name (RFC 7230 token) — no CR/LF, colon, space, or control
137
+ // chars that could inject a second header. Fail closed on anything else.
138
+ if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(headerName)) {
139
+ throw new SignerError("MALFORMED_ENVELOPE", "header_name is not a valid HTTP header name");
140
+ }
141
+ const payload = prepareEnvelope.paymentPayload?.payload;
142
+ if (payload === null || typeof payload !== "object") {
143
+ throw new SignerError("MALFORMED_ENVELOPE", "input envelope is missing paymentPayload.payload");
144
+ }
145
+ // Guard: never re-sign an already-filled envelope.
146
+ if (payload.signature !== undefined && payload.signature !== null) {
147
+ throw new SignerError("MALFORMED_ENVELOPE", "input envelope already carries a signature");
148
+ }
149
+ // Guard: the voucher embedded in the envelope must be the voucher we sign (payment_id cross-check).
150
+ const embeddedPaymentId = payload.voucher?.paymentId;
151
+ if (typeof embeddedPaymentId !== "string") {
152
+ throw new SignerError("MALFORMED_ENVELOPE", "input envelope is missing paymentPayload.payload.voucher.paymentId");
153
+ }
154
+ if (embeddedPaymentId !== voucher.paymentId) {
155
+ throw new SignerError("PAYMENT_ID_MISMATCH", "voucher paymentId does not match the envelope's embedded voucher");
156
+ }
157
+ const key = resolveSigningKey(record, keyFileSource, stdin, opts);
158
+ if (!key.privateKeyBase64Url) {
159
+ throw new SignerError("MALFORMED_ENVELOPE", "signing key is missing private_key_base64url");
160
+ }
161
+ const { signature } = signVoucher({
162
+ voucher,
163
+ privateKeyBase64Url: key.privateKeyBase64Url,
164
+ signing: record.signing,
165
+ // Derive the public key from the seed when absent so the jkt-binding guard always runs.
166
+ publicJwk: key.publicJwk ?? workloadKeyFromPrivate(key.privateKeyBase64Url).publicJwk,
167
+ });
168
+ const { headerValue, envelope } = buildPaymentSignatureHeader(prepareEnvelope, signature);
169
+ return {
170
+ signer_protocol: SIGNER_PROTOCOL,
171
+ implementation: IMPLEMENTATION,
172
+ implementation_version: implementationVersion(),
173
+ payment_id: voucher.paymentId,
174
+ agent_key_jkt: voucher.agentKeyJkt,
175
+ signature,
176
+ algorithm: SUPPORTED_SIGNING.algorithm,
177
+ envelope,
178
+ header_name: headerName,
179
+ header_value: headerValue,
180
+ };
181
+ }
182
+ /** `{ fields: { borrowerId, terminalId, jkt } } (+ --key <path>) → { …, pop_signature, nonce, iat }`. */
183
+ export function popSignResult(input, keyFileSource, _stdin, opts = {}) {
184
+ const record = (input ?? {});
185
+ const fields = record.fields;
186
+ if (fields === null || fields === undefined || typeof fields !== "object") {
187
+ throw new SignerError("MALFORMED_INPUT", "pop sign requires a `fields` object");
188
+ }
189
+ if (keyFileSource === undefined) {
190
+ throw new SignerError("MALFORMED_INPUT", "pop sign requires --key <path>");
191
+ }
192
+ const { borrowerId, terminalId, jkt } = fields;
193
+ if (typeof borrowerId !== "string" || typeof terminalId !== "string" || typeof jkt !== "string") {
194
+ throw new SignerError("MALFORMED_INPUT", "pop sign fields require string borrowerId, terminalId, jkt");
195
+ }
196
+ // Bind the claimed identity to the stored key before signing anything.
197
+ const stored = loadKeyFile(validateKeyPath(keyFileSource, "read", opts));
198
+ if (stored.borrower_id !== borrowerId)
199
+ throw new SignerError("CROSS_BORROWER_KEY", "fields.borrowerId does not match the key file");
200
+ if (stored.terminal_id !== terminalId)
201
+ throw new SignerError("TERMINAL_MISMATCH", "fields.terminalId does not match the key file");
202
+ if (stored.jkt !== jkt)
203
+ throw new SignerError("AGENT_KEY_JKT_MISMATCH", "fields.jkt does not match the key file");
204
+ // Validate the stored seed up front so a tampered key file fails with a specific
205
+ // INVALID_PRIVATE_KEY (matching `voucher sign`) instead of a generic signing error.
206
+ decodeWorkloadSeed(stored.private_key_base64url);
207
+ // Nonce/iat are minted here, never accepted from the caller (replay defense).
208
+ const nonce = toBase64Url(randomBytes(32));
209
+ const iat = Math.floor(Date.now() / 1000);
210
+ const { pop_signature } = signPoP({ borrowerId, terminalId, jkt, nonce, iat }, stored.private_key_base64url);
211
+ return {
212
+ signer_protocol: SIGNER_PROTOCOL,
213
+ implementation: IMPLEMENTATION,
214
+ implementation_version: implementationVersion(),
215
+ pop_signature,
216
+ nonce,
217
+ iat,
218
+ algorithm: SUPPORTED_SIGNING.algorithm,
219
+ };
220
+ }
221
+ /** `verify-vectors → ({ passed, failed, total }, ok)`; ok drives the exit code. */
222
+ export function verifyVectorsResult() {
223
+ const summary = verifyVectors();
224
+ return {
225
+ result: { passed: summary.passed, failed: summary.failed, total: summary.total },
226
+ ok: summary.failed === 0,
227
+ };
228
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,32 @@
1
+ #!/usr/bin/env node
2
+ import { assertNodeFloor } from "./node-floor.js";
3
+ // ESM hoists static imports, so only the guard is imported statically; everything that may
4
+ // touch Node-18-only APIs is loaded dynamically after the check.
5
+ try {
6
+ assertNodeFloor(process.versions.node);
7
+ }
8
+ catch (e) {
9
+ const code = e.code ?? "NODE_VERSION_UNSUPPORTED";
10
+ process.stderr.write(JSON.stringify({ error: { code, message: e.message } }) + "\n");
11
+ process.exit(1);
12
+ }
13
+ const { readFileSync } = await import("node:fs");
14
+ const { needsStdin } = await import("./args.js");
15
+ const { run } = await import("./run.js");
16
+ /** Reads all of stdin synchronously (fd 0). Empty string when nothing is piped. */
17
+ function readStdin() {
18
+ try {
19
+ return readFileSync(0, "utf8");
20
+ }
21
+ catch {
22
+ return "";
23
+ }
24
+ }
25
+ const argv = process.argv.slice(2);
26
+ const stdin = needsStdin(argv) ? readStdin() : "";
27
+ const result = run(argv, stdin);
28
+ if (result.stdout)
29
+ process.stdout.write(result.stdout);
30
+ if (result.stderr)
31
+ process.stderr.write(result.stderr);
32
+ process.exitCode = result.exitCode;
@@ -0,0 +1,2 @@
1
+ export declare function assertInputSchema(command: string, input: unknown): void;
2
+ export declare function assertOutputSchema(command: string, output: Record<string, unknown>): void;