@sohopay/agent-signer 0.0.0-stage → 0.4.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 (54) hide show
  1. package/README.md +261 -2
  2. package/dist/cli/args.d.ts +20 -0
  3. package/dist/cli/args.js +106 -0
  4. package/dist/cli/commands.d.ts +37 -0
  5. package/dist/cli/commands.js +230 -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 +15 -0
  15. package/dist/cli/key-path.js +188 -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 +148 -0
  20. package/dist/cli/signer-config.d.ts +6 -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 +31 -0
  51. package/dist/terminal.js +142 -0
  52. package/dist/voucher.d.ts +39 -0
  53. package/dist/voucher.js +86 -0
  54. package/package.json +37 -4
package/README.md CHANGED
@@ -1,3 +1,262 @@
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
+ ### One key per terminal (`workload-terminal/1`)
178
+
179
+ Two installs on one machine need two terminals and two keys. `terminal id --harness <name>`
180
+ returns a stable `<name>:<uuid>` for that harness (persisted at `~/.sohopay/<name>/terminal_id`,
181
+ file `0600`, folder `0700`). `--harness` accepts only `antigravity`, `claude-code`, `codex`,
182
+ `cursor` or `hermes`; anything else fails with `INVALID_HARNESS`. `SOHO_TERMINAL_ID` is not
183
+ consulted here.
184
+
185
+ `key generate`, `pop sign` and `voucher sign` accept `--terminal <id>` in place of
186
+ `--out` / `--key`. The signer picks the key file itself:
187
+ `~/.agents/sohopay-agent-workload/<sha256-hex(id)>/secret.json`, so the raw id never
188
+ reaches the filesystem. All the checks above still apply. `key generate --terminal`
189
+ also requires `terminal_id` in the input to equal the flag (`TERMINAL_MISMATCH` otherwise).
190
+ An existing `--key .../secret.json` install keeps working unchanged.
191
+
192
+ ### Commands
193
+
194
+ `key generate`: creates a new Ed25519 workload key.
195
+
196
+ ```bash
197
+ echo '{ "borrower_id": "...", "terminal_id": "..." }' \
198
+ | sohopay-signer key generate --out ~/.agents/sohopay-agent-workload/secret.json --input - --output json
199
+ # {"public_jwk":{...},"jkt":"...","borrower_id":"...","terminal_id":"...","created":true}
200
+ ```
201
+
202
+ The private key is written to `secret.json` with mode `0600` and is never
203
+ printed; stdout carries public material only.
204
+
205
+ `voucher sign`: signs the voucher issued by `prepare_x402_payment`.
206
+
207
+ ```bash
208
+ echo '{ "voucher": { ... }, "signing": { ... } }' \
209
+ | sohopay-signer voucher sign --key ~/.agents/sohopay-agent-workload/secret.json --input - --output json
210
+ # {"signer_protocol":"sohopay-signer/1","implementation":"@sohopay/agent-signer",
211
+ # "implementation_version":"0.x.y","payment_id":"0x...","agent_key_jkt":"...",
212
+ # "signature":"...","algorithm":"Ed25519"}
213
+ ```
214
+
215
+ `payment-id`: recomputes the `paymentId` from a voucher core.
216
+
217
+ ```bash
218
+ echo '{ "core": { ... } }' | sohopay-signer payment-id --input - --output json
219
+ # {"payment_id":"0x..."}
220
+ ```
221
+
222
+ `key jkt`: RFC 7638 thumbprint of a public JWK (or of the key derived from a seed).
223
+
224
+ ```bash
225
+ echo '{ "public_jwk": { ... } }' | sohopay-signer key jkt --input - --output json
226
+ # {"agent_key_jkt":"..."}
227
+ ```
228
+
229
+ `pop sign`: signs the proof-of-possession challenge for key registration.
230
+
231
+ ```bash
232
+ echo '{ "fields": { "borrowerId": "...", "terminalId": "...", "jkt": "...", "nonce": "...", "iat": 0 } }' \
233
+ | sohopay-signer pop sign --input - --key ~/.agents/sohopay-agent-workload/secret.json --output json
234
+ # {"signer_protocol":"sohopay-signer/1","implementation":"@sohopay/agent-signer",
235
+ # "implementation_version":"0.x.y","pop_signature":"...","algorithm":"Ed25519"}
236
+ ```
237
+
238
+ `terminal id`: the stable terminal id for one harness (see above).
239
+
240
+ ```bash
241
+ sohopay-signer terminal id --harness claude-code --output json
242
+ # {"terminal_id":"claude-code:<uuid>"}
243
+ ```
244
+
245
+ `verify-vectors`: runs the bundled known-answer vectors; exits `0` only if all pass.
246
+
247
+ ```bash
248
+ sohopay-signer verify-vectors --output json
249
+ # {"passed":N,"failed":0,"total":N}
250
+ ```
251
+
252
+ `capabilities`: what host routing probes to confirm a usable signer.
253
+
254
+ ```bash
255
+ sohopay-signer capabilities --output json
256
+ # {"signer_protocol":"sohopay-signer/1","implementation":"@sohopay/agent-signer",
257
+ # "implementation_version":"0.x.y","algorithms":["Ed25519"],"commands":[...]}
258
+ ```
259
+
260
+ ## License
261
+
262
+ Proprietary — SohoPay. Not for distribution.
@@ -0,0 +1,20 @@
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
+ terminal?: string;
8
+ harness?: string;
9
+ output: "json" | "human";
10
+ envelope: boolean;
11
+ writeHeader?: string;
12
+ }
13
+ /** A caller mistake (unknown command/flag, missing value). Mapped to exit 2. */
14
+ export declare class UsageError extends Error {
15
+ constructor(message: string);
16
+ }
17
+ /** Splits argv into a known command (1–2 leading tokens) plus flags. */
18
+ export declare function parseArgs(argv: string[]): ParsedArgs;
19
+ /** True when this invocation reads stdin — "-" is the stdin sentinel for --input/--key (space- or `=`-separated). */
20
+ export declare function needsStdin(argv: string[]): boolean;
@@ -0,0 +1,106 @@
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
+ "terminal id",
17
+ ]);
18
+ function requireValue(argv, index, flag) {
19
+ const value = argv[index];
20
+ if (value === undefined) {
21
+ throw new UsageError(`${flag} requires a value`);
22
+ }
23
+ return value;
24
+ }
25
+ /** Splits argv into a known command (1–2 leading tokens) plus flags. */
26
+ export function parseArgs(argv) {
27
+ const positionals = [];
28
+ let input;
29
+ let key;
30
+ let out;
31
+ let terminal;
32
+ let harness;
33
+ let output = "human";
34
+ let envelope = false;
35
+ let writeHeader;
36
+ for (let i = 0; i < argv.length; i++) {
37
+ const token = argv[i];
38
+ if (token === undefined) {
39
+ continue;
40
+ }
41
+ if (token.startsWith("--")) {
42
+ // Accept both `--flag value` and `--flag=value`.
43
+ const eq = token.indexOf("=");
44
+ const name = eq === -1 ? token : token.slice(0, eq);
45
+ const inlineValue = eq === -1 ? undefined : token.slice(eq + 1);
46
+ const valueOf = (flag) => inlineValue ?? requireValue(argv, ++i, flag);
47
+ if (name === "--input") {
48
+ input = valueOf("--input");
49
+ }
50
+ else if (name === "--key") {
51
+ key = valueOf("--key");
52
+ }
53
+ else if (name === "--out") {
54
+ out = valueOf("--out");
55
+ }
56
+ else if (name === "--terminal") {
57
+ terminal = valueOf("--terminal");
58
+ }
59
+ else if (name === "--harness") {
60
+ harness = valueOf("--harness");
61
+ }
62
+ else if (name === "--output") {
63
+ const value = valueOf("--output");
64
+ if (value !== "json" && value !== "human") {
65
+ throw new UsageError(`--output must be "json" or "human", got "${value}"`);
66
+ }
67
+ output = value;
68
+ }
69
+ else if (name === "--envelope") {
70
+ envelope = true; // boolean flag; any inline value is ignored
71
+ }
72
+ else if (name === "--write-header") {
73
+ writeHeader = valueOf("--write-header");
74
+ }
75
+ else {
76
+ throw new UsageError(`unknown flag: ${name}`);
77
+ }
78
+ }
79
+ else {
80
+ positionals.push(token);
81
+ }
82
+ }
83
+ const twoToken = positionals.slice(0, 2).join(" ");
84
+ const oneToken = positionals[0] ?? "";
85
+ let command;
86
+ let commandTokens;
87
+ if (KNOWN_COMMANDS.has(twoToken)) {
88
+ command = twoToken;
89
+ commandTokens = 2;
90
+ }
91
+ else if (KNOWN_COMMANDS.has(oneToken)) {
92
+ command = oneToken;
93
+ commandTokens = 1;
94
+ }
95
+ else {
96
+ throw new UsageError(`unknown command: ${positionals.join(" ") || "(none)"}`);
97
+ }
98
+ if (positionals.length > commandTokens) {
99
+ throw new UsageError(`unexpected argument: ${positionals[commandTokens]}`);
100
+ }
101
+ return { command, input, key, out, terminal, harness, output, envelope, writeHeader };
102
+ }
103
+ /** True when this invocation reads stdin — "-" is the stdin sentinel for --input/--key (space- or `=`-separated). */
104
+ export function needsStdin(argv) {
105
+ return argv.some((token) => token === "-" || token === "--input=-" || token === "--key=-");
106
+ }
@@ -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,230 @@
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", "terminal id"];
29
+ const COMMAND_CONTRACTS = {
30
+ "key generate": "workload-keygen/1",
31
+ "pop sign": "pop-sign/1",
32
+ // `terminal id --harness` plus `--terminal <id>` on key generate / pop sign / voucher sign.
33
+ "terminal id": "workload-terminal/1",
34
+ };
35
+ /** Static advertisement SP5 routing probes to confirm a usable signer. */
36
+ export function capabilitiesResult() {
37
+ return {
38
+ signer_protocol: SIGNER_PROTOCOL,
39
+ implementation: IMPLEMENTATION,
40
+ implementation_version: implementationVersion(),
41
+ algorithms: [SUPPORTED_SIGNING.algorithm],
42
+ commands: COMMANDS,
43
+ command_contracts: COMMAND_CONTRACTS,
44
+ };
45
+ }
46
+ /** `{ core } → { payment_id }`. */
47
+ export function paymentIdResult(input) {
48
+ const core = input?.core;
49
+ if (core === null || typeof core !== "object") {
50
+ throw new SignerError("MALFORMED_ENVELOPE", "payment-id requires a `core` object");
51
+ }
52
+ return { payment_id: computePaymentId(core) };
53
+ }
54
+ /** `{ public_jwk } | { key: { public_jwk | private_key_base64url } } → { agent_key_jkt }`. */
55
+ export function keyJktResult(input) {
56
+ const record = (input ?? {});
57
+ const block = record.public_jwk !== undefined ? { public_jwk: record.public_jwk } : record.key;
58
+ if (block && typeof block === "object" && block.private_key_base64url !== undefined) {
59
+ throw new SignerError("INLINE_KEY_REJECTED", "key jkt does not accept inline private key material; pass public_jwk");
60
+ }
61
+ const key = resolveKeyBlock(block);
62
+ if (key.publicJwk) {
63
+ return { agent_key_jkt: computeJkt(key.publicJwk) };
64
+ }
65
+ if (key.privateKeyBase64Url) {
66
+ return { agent_key_jkt: workloadKeyFromPrivate(key.privateKeyBase64Url).jkt };
67
+ }
68
+ throw new SignerError("MALFORMED_ENVELOPE", "key jkt requires public_jwk or a key with private/public material");
69
+ }
70
+ /**
71
+ * Resolves the signing key from a validated `--key <path>` file only. Inline key
72
+ * material is rejected first (INV-3) so a secret never travels through input JSON.
73
+ */
74
+ export function resolveSigningKey(input, keyFileSource, stdin, opts = {}) {
75
+ if (input.key !== undefined) {
76
+ throw new SignerError("INLINE_KEY_REJECTED", "inline key material is not accepted; use --key <path>");
77
+ }
78
+ if (keyFileSource === undefined) {
79
+ throw new SignerError("MALFORMED_INPUT", "signing requires --key <path>");
80
+ }
81
+ const key = readKeyFile(keyFileSource, stdin, opts);
82
+ // Validate the seed here so a malformed key surfaces as INVALID_PRIVATE_KEY on
83
+ // every signing path — even when a public_jwk is supplied and the SDK would
84
+ // otherwise only decode the seed deep inside ed25519.sign.
85
+ if (key.privateKeyBase64Url !== undefined) {
86
+ decodeWorkloadSeed(key.privateKeyBase64Url);
87
+ }
88
+ return key;
89
+ }
90
+ /** `{ voucher, signing?, key? } (+ optional --key) → signed result`. */
91
+ export function voucherSignResult(input, keyFileSource, stdin, opts = {}) {
92
+ const record = (input ?? {});
93
+ const voucher = record.voucher;
94
+ if (voucher === null || typeof voucher !== "object") {
95
+ throw new SignerError("MALFORMED_ENVELOPE", "voucher sign requires a `voucher` object");
96
+ }
97
+ const key = resolveSigningKey(record, keyFileSource, stdin, opts);
98
+ if (!key.privateKeyBase64Url) {
99
+ throw new SignerError("MALFORMED_ENVELOPE", "signing key is missing private_key_base64url");
100
+ }
101
+ const { signature } = signVoucher({
102
+ voucher,
103
+ privateKeyBase64Url: key.privateKeyBase64Url,
104
+ signing: record.signing,
105
+ // Derive the public key from the seed when absent so the jkt-binding guard always runs.
106
+ publicJwk: key.publicJwk ?? workloadKeyFromPrivate(key.privateKeyBase64Url).publicJwk,
107
+ });
108
+ return {
109
+ signer_protocol: SIGNER_PROTOCOL,
110
+ implementation: IMPLEMENTATION,
111
+ implementation_version: implementationVersion(),
112
+ payment_id: voucher.paymentId,
113
+ agent_key_jkt: voucher.agentKeyJkt,
114
+ signature,
115
+ algorithm: SUPPORTED_SIGNING.algorithm,
116
+ };
117
+ }
118
+ /**
119
+ * `--envelope`: `{ voucher, signing?, envelope, header_name, key? } (+ optional --key)`
120
+ * -> signed result plus the completed x402 envelope and PAYMENT-SIGNATURE header.
121
+ * Fills ONLY paymentPayload.payload.signature; never re-signs a filled envelope.
122
+ */
123
+ export function voucherSignEnvelopeResult(input, keyFileSource, stdin, opts = {}) {
124
+ const record = (input ?? {});
125
+ const voucher = record.voucher;
126
+ if (voucher === null || typeof voucher !== "object") {
127
+ throw new SignerError("MALFORMED_ENVELOPE", "voucher sign --envelope requires a `voucher` object");
128
+ }
129
+ const prepareEnvelope = record.envelope;
130
+ if (prepareEnvelope === null || typeof prepareEnvelope !== "object") {
131
+ throw new SignerError("MALFORMED_ENVELOPE", "voucher sign --envelope requires an `envelope` object");
132
+ }
133
+ const headerName = record.header_name;
134
+ if (typeof headerName !== "string" || headerName.length === 0) {
135
+ throw new SignerError("MALFORMED_ENVELOPE", "voucher sign --envelope requires a non-empty string `header_name`");
136
+ }
137
+ // header_name is emitted into a curl-ready header line ("<name>: <value>\n"), so it
138
+ // must be a valid HTTP field-name (RFC 7230 token) — no CR/LF, colon, space, or control
139
+ // chars that could inject a second header. Fail closed on anything else.
140
+ if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(headerName)) {
141
+ throw new SignerError("MALFORMED_ENVELOPE", "header_name is not a valid HTTP header name");
142
+ }
143
+ const payload = prepareEnvelope.paymentPayload?.payload;
144
+ if (payload === null || typeof payload !== "object") {
145
+ throw new SignerError("MALFORMED_ENVELOPE", "input envelope is missing paymentPayload.payload");
146
+ }
147
+ // Guard: never re-sign an already-filled envelope.
148
+ if (payload.signature !== undefined && payload.signature !== null) {
149
+ throw new SignerError("MALFORMED_ENVELOPE", "input envelope already carries a signature");
150
+ }
151
+ // Guard: the voucher embedded in the envelope must be the voucher we sign (payment_id cross-check).
152
+ const embeddedPaymentId = payload.voucher?.paymentId;
153
+ if (typeof embeddedPaymentId !== "string") {
154
+ throw new SignerError("MALFORMED_ENVELOPE", "input envelope is missing paymentPayload.payload.voucher.paymentId");
155
+ }
156
+ if (embeddedPaymentId !== voucher.paymentId) {
157
+ throw new SignerError("PAYMENT_ID_MISMATCH", "voucher paymentId does not match the envelope's embedded voucher");
158
+ }
159
+ const key = resolveSigningKey(record, keyFileSource, stdin, opts);
160
+ if (!key.privateKeyBase64Url) {
161
+ throw new SignerError("MALFORMED_ENVELOPE", "signing key is missing private_key_base64url");
162
+ }
163
+ const { signature } = signVoucher({
164
+ voucher,
165
+ privateKeyBase64Url: key.privateKeyBase64Url,
166
+ signing: record.signing,
167
+ // Derive the public key from the seed when absent so the jkt-binding guard always runs.
168
+ publicJwk: key.publicJwk ?? workloadKeyFromPrivate(key.privateKeyBase64Url).publicJwk,
169
+ });
170
+ const { headerValue, envelope } = buildPaymentSignatureHeader(prepareEnvelope, signature);
171
+ return {
172
+ signer_protocol: SIGNER_PROTOCOL,
173
+ implementation: IMPLEMENTATION,
174
+ implementation_version: implementationVersion(),
175
+ payment_id: voucher.paymentId,
176
+ agent_key_jkt: voucher.agentKeyJkt,
177
+ signature,
178
+ algorithm: SUPPORTED_SIGNING.algorithm,
179
+ envelope,
180
+ header_name: headerName,
181
+ header_value: headerValue,
182
+ };
183
+ }
184
+ /** `{ fields: { borrowerId, terminalId, jkt } } (+ --key <path>) → { …, pop_signature, nonce, iat }`. */
185
+ export function popSignResult(input, keyFileSource, _stdin, opts = {}) {
186
+ const record = (input ?? {});
187
+ const fields = record.fields;
188
+ if (fields === null || fields === undefined || typeof fields !== "object") {
189
+ throw new SignerError("MALFORMED_INPUT", "pop sign requires a `fields` object");
190
+ }
191
+ if (keyFileSource === undefined) {
192
+ throw new SignerError("MALFORMED_INPUT", "pop sign requires --key <path>");
193
+ }
194
+ const { borrowerId, terminalId, jkt } = fields;
195
+ if (typeof borrowerId !== "string" || typeof terminalId !== "string" || typeof jkt !== "string") {
196
+ throw new SignerError("MALFORMED_INPUT", "pop sign fields require string borrowerId, terminalId, jkt");
197
+ }
198
+ // Bind the claimed identity to the stored key before signing anything.
199
+ const stored = loadKeyFile(validateKeyPath(keyFileSource, "read", opts));
200
+ if (stored.borrower_id !== borrowerId)
201
+ throw new SignerError("CROSS_BORROWER_KEY", "fields.borrowerId does not match the key file");
202
+ if (stored.terminal_id !== terminalId)
203
+ throw new SignerError("TERMINAL_MISMATCH", "fields.terminalId does not match the key file");
204
+ if (stored.jkt !== jkt)
205
+ throw new SignerError("AGENT_KEY_JKT_MISMATCH", "fields.jkt does not match the key file");
206
+ // Validate the stored seed up front so a tampered key file fails with a specific
207
+ // INVALID_PRIVATE_KEY (matching `voucher sign`) instead of a generic signing error.
208
+ decodeWorkloadSeed(stored.private_key_base64url);
209
+ // Nonce/iat are minted here, never accepted from the caller (replay defense).
210
+ const nonce = toBase64Url(randomBytes(32));
211
+ const iat = Math.floor(Date.now() / 1000);
212
+ const { pop_signature } = signPoP({ borrowerId, terminalId, jkt, nonce, iat }, stored.private_key_base64url);
213
+ return {
214
+ signer_protocol: SIGNER_PROTOCOL,
215
+ implementation: IMPLEMENTATION,
216
+ implementation_version: implementationVersion(),
217
+ pop_signature,
218
+ nonce,
219
+ iat,
220
+ algorithm: SUPPORTED_SIGNING.algorithm,
221
+ };
222
+ }
223
+ /** `verify-vectors → ({ passed, failed, total }, ok)`; ok drives the exit code. */
224
+ export function verifyVectorsResult() {
225
+ const summary = verifyVectors();
226
+ return {
227
+ result: { passed: summary.passed, failed: summary.failed, total: summary.total },
228
+ ok: summary.failed === 0,
229
+ };
230
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};