@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
@@ -0,0 +1,142 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { chmodSync, linkSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { homedir, hostname } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ import { SignerError } from "./errors.js";
6
+ /** Backend `RegisterBorrowerDto.terminal_id` charset / length. */
7
+ export const TERMINAL_ID_PATTERN = /^[A-Za-z0-9._:@-]+$/;
8
+ export const TERMINAL_ID_MAX_LENGTH = 128;
9
+ /** Backend sentinel for adopted terminal-1 rows — never accepted as input. */
10
+ const ADOPTED_TERMINAL_SENTINEL = "__adopted__";
11
+ /** Validates a terminal id against the backend's charset/length rules. */
12
+ export function assertValidTerminalId(terminalId) {
13
+ const trimmed = terminalId.trim();
14
+ if (!trimmed) {
15
+ throw new SignerError("INVALID_TERMINAL_ID", "terminal_id must be a non-empty string");
16
+ }
17
+ if (trimmed.length > TERMINAL_ID_MAX_LENGTH) {
18
+ throw new SignerError("INVALID_TERMINAL_ID", `terminal_id must be at most ${TERMINAL_ID_MAX_LENGTH} characters`);
19
+ }
20
+ if (!TERMINAL_ID_PATTERN.test(trimmed)) {
21
+ throw new SignerError("INVALID_TERMINAL_ID", "terminal_id must contain only letters, digits, and . _ : @ - (no whitespace)");
22
+ }
23
+ if (trimmed === ADOPTED_TERMINAL_SENTINEL) {
24
+ throw new SignerError("INVALID_TERMINAL_ID", "terminal_id is reserved and cannot be used");
25
+ }
26
+ return trimmed;
27
+ }
28
+ /** The SDK data directory: explicit → `SOHO_DATA_DIR` → `~/.sohopay`. */
29
+ export function resolveDataDir(dataDir) {
30
+ const explicit = (dataDir ?? process.env.SOHO_DATA_DIR ?? "").trim();
31
+ return explicit || join(homedir(), ".sohopay");
32
+ }
33
+ function terminalIdPath(dataDir) {
34
+ return join(resolveDataDir(dataDir), "terminal_id");
35
+ }
36
+ function hostLabel() {
37
+ const raw = hostname().trim().toLowerCase() || "host";
38
+ const sanitized = raw.replace(/[^a-z0-9._:@-]+/gi, "-").replace(/^-+|-+$/g, "") || "host";
39
+ return sanitized.slice(0, 48);
40
+ }
41
+ function readPersistedTerminalId(filePath) {
42
+ let raw;
43
+ try {
44
+ raw = readFileSync(filePath, "utf8").trim();
45
+ }
46
+ catch (error) {
47
+ if (error.code === "ENOENT") {
48
+ return undefined;
49
+ }
50
+ // Never silently regenerate on an unexpected IO error (EACCES, EISDIR, …):
51
+ // that would rotate this host's terminal identity and mint a new
52
+ // OperationalAgent on the next register. Surface it instead.
53
+ throw error;
54
+ }
55
+ if (!raw) {
56
+ return undefined;
57
+ }
58
+ try {
59
+ return assertValidTerminalId(raw);
60
+ }
61
+ catch {
62
+ return undefined;
63
+ }
64
+ }
65
+ function persistTerminalId(filePath, terminalId) {
66
+ mkdirSync(dirname(filePath), { recursive: true });
67
+ writeFileSync(filePath, `${terminalId}\n`, { encoding: "utf8", mode: 0o600 });
68
+ }
69
+ /**
70
+ * Resolves a stable per-host `terminal_id`. Precedence:
71
+ * 1. explicit argument, 2. `SOHO_TERMINAL_ID`, 3. persisted `{hostname}:{uuid}`
72
+ * under the data dir (minted + persisted on first use).
73
+ */
74
+ export function resolveTerminalId(options = {}) {
75
+ if (options.explicit) {
76
+ return assertValidTerminalId(options.explicit);
77
+ }
78
+ const envValue = (process.env.SOHO_TERMINAL_ID ?? "").trim();
79
+ if (envValue) {
80
+ return assertValidTerminalId(envValue);
81
+ }
82
+ const filePath = terminalIdPath(options.dataDir);
83
+ const persisted = readPersistedTerminalId(filePath);
84
+ if (persisted) {
85
+ return persisted;
86
+ }
87
+ const minted = `${hostLabel()}:${randomUUID()}`;
88
+ persistTerminalId(filePath, minted);
89
+ return minted;
90
+ }
91
+ /**
92
+ * Harnesses that may hold their own terminal id. A fixed list, so the slug is a safe
93
+ * single path segment and no caller-chosen string ever names a directory.
94
+ */
95
+ export const HARNESSES = ["antigravity", "claude-code", "codex", "cursor", "hermes"];
96
+ /**
97
+ * Per-harness terminal id: `{harness}:{uuid}` persisted at `<dataDir>/<harness>/terminal_id`
98
+ * (dir 0700, file 0600), minted on first use and stable afterwards. Unlike
99
+ * {@link resolveTerminalId} it ignores `SOHO_TERMINAL_ID`: a host-wide override would
100
+ * collapse every harness back onto one terminal.
101
+ */
102
+ export function resolveHarnessTerminalId(harness, dataDir) {
103
+ if (!HARNESSES.includes(harness)) {
104
+ throw new SignerError("INVALID_HARNESS", `--harness must be one of: ${HARNESSES.join(", ")}`);
105
+ }
106
+ const dir = join(resolveDataDir(dataDir), harness);
107
+ const filePath = join(dir, "terminal_id");
108
+ const persisted = readHarnessTerminalId(filePath, harness);
109
+ if (persisted)
110
+ return persisted;
111
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
112
+ chmodSync(dir, 0o700);
113
+ const minted = `${harness}:${randomUUID()}`;
114
+ // Write a private temp file, then publish it with link(2): the id appears complete or
115
+ // not at all, so a racing first call can never read a half-written file, and EEXIST
116
+ // means someone else won and their id is already whole.
117
+ const tmp = join(dir, `.terminal_id.${process.pid}.${randomUUID()}`);
118
+ writeFileSync(tmp, `${minted}\n`, { encoding: "utf8", mode: 0o600, flag: "wx" });
119
+ try {
120
+ linkSync(tmp, filePath);
121
+ return minted;
122
+ }
123
+ catch (error) {
124
+ if (error.code !== "EEXIST")
125
+ throw error;
126
+ const winner = readHarnessTerminalId(filePath, harness);
127
+ if (!winner)
128
+ throw new SignerError("INVALID_TERMINAL_ID", `${filePath} holds no valid terminal id`);
129
+ return winner;
130
+ }
131
+ finally {
132
+ unlinkSync(tmp);
133
+ }
134
+ }
135
+ /** Reads the persisted id and refuses one minted for another harness (a copied or edited file). */
136
+ function readHarnessTerminalId(filePath, harness) {
137
+ const id = readPersistedTerminalId(filePath);
138
+ if (id !== undefined && !id.startsWith(`${harness}:`)) {
139
+ throw new SignerError("INVALID_TERMINAL_ID", `${filePath} holds an id that does not belong to ${harness}`);
140
+ }
141
+ return id;
142
+ }
@@ -0,0 +1,39 @@
1
+ import { type Ed25519PublicJwk } from "./keys.js";
2
+ export interface AgentPaymentVoucherCore {
3
+ agentId: string;
4
+ merchantId: string;
5
+ asset: string;
6
+ chainId: string;
7
+ amount: string;
8
+ feeAmount: string;
9
+ orderRef: string;
10
+ nonce: string;
11
+ deadline: string;
12
+ }
13
+ export interface AgentPaymentVoucher extends AgentPaymentVoucherCore {
14
+ paymentId: `0x${string}`;
15
+ agentKeyJkt: string;
16
+ }
17
+ /** The server's advertised signing block, validated against {@link SUPPORTED_SIGNING}. */
18
+ export interface ServerSigningBlock {
19
+ algorithm?: string;
20
+ domain_tag?: string;
21
+ canonicalization?: string;
22
+ signature_encoding?: string;
23
+ }
24
+ /** `paymentId = keccak256(utf8(tag) || 0x00 || JCS(core))`. */
25
+ export declare function computePaymentId(core: AgentPaymentVoucherCore): `0x${string}`;
26
+ /** The exact bytes the agent signs: tagged preimage over the full 11-field voucher. */
27
+ export declare function buildVoucherSignedBytes(voucher: AgentPaymentVoucher): Uint8Array;
28
+ export interface SignVoucherArgs {
29
+ voucher: AgentPaymentVoucher;
30
+ privateKeyBase64Url: string;
31
+ /** The server `signing` block from prepare — validated, never substituted. */
32
+ signing?: ServerSigningBlock;
33
+ /** When given, asserts the voucher's `agentKeyJkt` matches this signing key. */
34
+ publicJwk?: Ed25519PublicJwk;
35
+ }
36
+ /** Signs a voucher after fail-closed guards (scheme allowlist, paymentId, jkt). */
37
+ export declare function signVoucher(args: SignVoucherArgs): {
38
+ signature: string;
39
+ };
@@ -0,0 +1,86 @@
1
+ import { ed25519 } from "@noble/curves/ed25519";
2
+ import { keccak_256 } from "@noble/hashes/sha3";
3
+ import { DOMAIN_SEPARATOR_BYTE, SUPPORTED_SIGNING, VOUCHER_CORE_FIELDS, VOUCHER_DOMAIN_TAG, } from "./constants.js";
4
+ import { fromBase64Url, toBase64Url, toHex, utf8Bytes } from "./encoding.js";
5
+ import { SignerError } from "./errors.js";
6
+ import { jcs } from "./jcs.js";
7
+ import { computeJkt } from "./keys.js";
8
+ /** Every core field must be a string — no JSON number enters a signed preimage. */
9
+ function assertCoreStrings(core) {
10
+ for (const field of VOUCHER_CORE_FIELDS) {
11
+ if (typeof core[field] !== "string") {
12
+ throw new SignerError("VOUCHER_FIELD_NOT_STRING", `voucher field "${field}" must be a string, got ${typeof core[field]}`);
13
+ }
14
+ }
15
+ }
16
+ /** Explicit 9-field projection — an unknown wire key never enters the preimage. */
17
+ function voucherCoreOf(core) {
18
+ return {
19
+ agentId: core.agentId,
20
+ merchantId: core.merchantId,
21
+ asset: core.asset,
22
+ chainId: core.chainId,
23
+ amount: core.amount,
24
+ feeAmount: core.feeAmount,
25
+ orderRef: core.orderRef,
26
+ nonce: core.nonce,
27
+ deadline: core.deadline,
28
+ };
29
+ }
30
+ /** `utf8(tag) || 0x00 || JCS(value)`. */
31
+ function taggedPreimage(value) {
32
+ const tag = utf8Bytes(VOUCHER_DOMAIN_TAG);
33
+ const body = utf8Bytes(jcs(value));
34
+ const out = new Uint8Array(tag.length + 1 + body.length);
35
+ out.set(tag, 0);
36
+ out[tag.length] = DOMAIN_SEPARATOR_BYTE;
37
+ out.set(body, tag.length + 1);
38
+ return out;
39
+ }
40
+ /** `paymentId = keccak256(utf8(tag) || 0x00 || JCS(core))`. */
41
+ export function computePaymentId(core) {
42
+ assertCoreStrings(core);
43
+ return `0x${toHex(keccak_256(taggedPreimage(voucherCoreOf(core))))}`;
44
+ }
45
+ /** The exact bytes the agent signs: tagged preimage over the full 11-field voucher. */
46
+ export function buildVoucherSignedBytes(voucher) {
47
+ assertCoreStrings(voucher);
48
+ return taggedPreimage({
49
+ ...voucherCoreOf(voucher),
50
+ paymentId: voucher.paymentId,
51
+ agentKeyJkt: voucher.agentKeyJkt,
52
+ });
53
+ }
54
+ function assertSigningAllowed(signing) {
55
+ if (!signing) {
56
+ return;
57
+ }
58
+ const checks = [
59
+ ["algorithm", SUPPORTED_SIGNING.algorithm],
60
+ ["domain_tag", SUPPORTED_SIGNING.domain_tag],
61
+ ["canonicalization", SUPPORTED_SIGNING.canonicalization],
62
+ ["signature_encoding", SUPPORTED_SIGNING.signature_encoding],
63
+ ];
64
+ for (const [key, expected] of checks) {
65
+ const actual = signing[key];
66
+ if (actual !== undefined && actual !== expected) {
67
+ throw new SignerError("SIGNING_SCHEME_NOT_ALLOWED", `server proposed ${key}="${actual}"; this SDK signs only "${expected}"`);
68
+ }
69
+ }
70
+ }
71
+ /** Signs a voucher after fail-closed guards (scheme allowlist, paymentId, jkt). */
72
+ export function signVoucher(args) {
73
+ assertSigningAllowed(args.signing);
74
+ const recomputed = computePaymentId(args.voucher);
75
+ if (recomputed.toLowerCase() !== args.voucher.paymentId.toLowerCase()) {
76
+ throw new SignerError("PAYMENT_ID_MISMATCH", "voucher.paymentId does not match the hash of its core");
77
+ }
78
+ if (args.publicJwk) {
79
+ const jkt = computeJkt(args.publicJwk);
80
+ if (jkt !== args.voucher.agentKeyJkt) {
81
+ throw new SignerError("AGENT_KEY_JKT_MISMATCH", "voucher.agentKeyJkt does not match the signing key's thumbprint");
82
+ }
83
+ }
84
+ const signature = ed25519.sign(buildVoucherSignedBytes(args.voucher), fromBase64Url(args.privateKeyBase64Url));
85
+ return { signature: toBase64Url(signature) };
86
+ }
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@sohopay/agent-signer",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.4.0",
4
+ "description": "Deterministic client-side signer for SohoPay Protocol V2 agent payments: Ed25519 vouchers, PoP challenges, RFC 7638 jkt. Holds agent workload keys only — never borrower keys.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/index.d.ts",
9
+ "import": "./dist/index.js"
10
+ }
11
+ },
12
+ "bin": {
13
+ "sohopay-signer": "dist/cli/index.js"
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "scripts": {
19
+ "build": "tsc -p tsconfig.json",
20
+ "test": "node --import tsx --test test/*.test.ts",
21
+ "check": "tsc --noEmit && npm run test",
22
+ "bundle": "node scripts/bundle.mjs"
23
+ },
24
+ "dependencies": {
25
+ "@noble/curves": "^1.9.7",
26
+ "@noble/hashes": "^1.4.0",
27
+ "@sohopay/signer-vectors": "^0.2.0",
28
+ "canonicalize": "2.1.0"
29
+ },
30
+ "devDependencies": {
31
+ "@types/node": "^22.7.0",
32
+ "esbuild": "0.28.2",
33
+ "tsx": "^4.20.5",
34
+ "typescript": "^5.6.0"
35
+ },
36
+ "engines": {
37
+ "node": ">=18"
38
+ }
39
+ }