@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.
- package/README.md +261 -2
- package/dist/cli/args.d.ts +20 -0
- package/dist/cli/args.js +106 -0
- package/dist/cli/commands.d.ts +37 -0
- package/dist/cli/commands.js +230 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +32 -0
- package/dist/cli/io-schema.d.ts +2 -0
- package/dist/cli/io-schema.js +55 -0
- package/dist/cli/io.d.ts +18 -0
- package/dist/cli/io.js +56 -0
- package/dist/cli/key-generate.d.ts +8 -0
- package/dist/cli/key-generate.js +77 -0
- package/dist/cli/key-path.d.ts +15 -0
- package/dist/cli/key-path.js +188 -0
- package/dist/cli/node-floor.d.ts +4 -0
- package/dist/cli/node-floor.js +11 -0
- package/dist/cli/run.d.ts +11 -0
- package/dist/cli/run.js +148 -0
- package/dist/cli/signer-config.d.ts +6 -0
- package/dist/cli/signer-config.js +84 -0
- package/dist/cli/verify-vectors.d.ts +8 -0
- package/dist/cli/verify-vectors.js +116 -0
- package/dist/constants.d.ts +24 -0
- package/dist/constants.js +34 -0
- package/dist/encoding.d.ts +5 -0
- package/dist/encoding.js +5 -0
- package/dist/envelope.d.ts +11 -0
- package/dist/envelope.js +20 -0
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +9 -0
- package/dist/flow.d.ts +70 -0
- package/dist/flow.js +62 -0
- package/dist/idempotency.d.ts +32 -0
- package/dist/idempotency.js +45 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +12 -0
- package/dist/jcs.d.ts +8 -0
- package/dist/jcs.js +15 -0
- package/dist/keys.d.ts +28 -0
- package/dist/keys.js +64 -0
- package/dist/operations.d.ts +107 -0
- package/dist/operations.js +151 -0
- package/dist/pop.d.ts +19 -0
- package/dist/pop.js +27 -0
- package/dist/rotation.d.ts +41 -0
- package/dist/rotation.js +33 -0
- package/dist/storage.d.ts +38 -0
- package/dist/storage.js +116 -0
- package/dist/terminal.d.ts +31 -0
- package/dist/terminal.js +142 -0
- package/dist/voucher.d.ts +39 -0
- package/dist/voucher.js +86 -0
- package/package.json +37 -4
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { lstatSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
2
|
+
import { homedir, platform, userInfo } from "node:os";
|
|
3
|
+
import { isAbsolute, join, resolve, sep } from "node:path";
|
|
4
|
+
import { SignerError } from "../errors.js";
|
|
5
|
+
export const DEFAULT_SUBDIR = [".agents", "sohopay-agent-workload"];
|
|
6
|
+
const CONFIG_REL = [".config", "sohopay-signer", "config.json"];
|
|
7
|
+
function invalid(message) {
|
|
8
|
+
throw new SignerError("KEY_PATH_INVALID", message);
|
|
9
|
+
}
|
|
10
|
+
/** Owner==uid, 0600, not a symlink, parent 0700 — the config file is a trusted input. */
|
|
11
|
+
function assertConfigFileSecure(path) {
|
|
12
|
+
if (platform() === "win32")
|
|
13
|
+
return; // ACL-governed; POSIX mode bits not meaningful
|
|
14
|
+
const l = lstatSync(path);
|
|
15
|
+
if (l.isSymbolicLink())
|
|
16
|
+
invalid(`${path} is a symlink`);
|
|
17
|
+
const st = statSync(path);
|
|
18
|
+
if (st.uid !== userInfo().uid)
|
|
19
|
+
invalid(`${path} is not owned by the current user`);
|
|
20
|
+
if ((st.mode & 0o077) !== 0)
|
|
21
|
+
invalid(`${path} must be 0600`);
|
|
22
|
+
const parent = statSync(join(path, ".."));
|
|
23
|
+
if ((parent.mode & 0o077) !== 0)
|
|
24
|
+
invalid(`${path} parent dir must be 0700`);
|
|
25
|
+
}
|
|
26
|
+
function realOrNull(p) {
|
|
27
|
+
try {
|
|
28
|
+
return realpathSync(p);
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** Reject relative or `..`-bearing entries so a lexical prefix can never escape a root (INV-4). */
|
|
35
|
+
function normalizeRootEntry(entry, source) {
|
|
36
|
+
if (!isAbsolute(entry) || entry.split(/[\\/]/).includes("..")) {
|
|
37
|
+
invalid(`${source} entry ${entry} must be an absolute path without ".." segments`);
|
|
38
|
+
}
|
|
39
|
+
const abs = resolve(entry);
|
|
40
|
+
return realOrNull(abs) ?? abs;
|
|
41
|
+
}
|
|
42
|
+
/** Resolve the allowed key roots: compiled default + config file, narrowed by env. */
|
|
43
|
+
export function resolveKeyRoots(opts = {}) {
|
|
44
|
+
const home = opts.homeDir ?? homedir();
|
|
45
|
+
const env = opts.env ?? process.env;
|
|
46
|
+
const configured = new Set();
|
|
47
|
+
const def = join(home, ...DEFAULT_SUBDIR);
|
|
48
|
+
configured.add(realOrNull(def) ?? def);
|
|
49
|
+
const cfgPath = join(home, ...CONFIG_REL);
|
|
50
|
+
if (realOrNull(cfgPath) !== null) {
|
|
51
|
+
assertConfigFileSecure(cfgPath);
|
|
52
|
+
let parsed;
|
|
53
|
+
try {
|
|
54
|
+
parsed = JSON.parse(readFileSync(cfgPath, "utf8"));
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
invalid(`${cfgPath} is not valid JSON`);
|
|
58
|
+
}
|
|
59
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
60
|
+
invalid(`${cfgPath} must contain a JSON object`);
|
|
61
|
+
}
|
|
62
|
+
const roots = parsed.keyRoots;
|
|
63
|
+
if (roots !== undefined) {
|
|
64
|
+
if (!Array.isArray(roots) || roots.some((r) => typeof r !== "string")) {
|
|
65
|
+
invalid(`${cfgPath} keyRoots must be an array of strings`);
|
|
66
|
+
}
|
|
67
|
+
for (const r of roots)
|
|
68
|
+
configured.add(normalizeRootEntry(r, cfgPath));
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
const envRaw = env.SOHOPAY_SIGNER_KEY_ROOTS;
|
|
72
|
+
if (envRaw === undefined || envRaw.length === 0) {
|
|
73
|
+
return [...configured];
|
|
74
|
+
}
|
|
75
|
+
const envRoots = envRaw.split(":").filter((s) => s.length > 0).map((r) => normalizeRootEntry(r, "SOHOPAY_SIGNER_KEY_ROOTS"));
|
|
76
|
+
const narrowed = [];
|
|
77
|
+
for (const er of envRoots) {
|
|
78
|
+
const ok = [...configured].some((cr) => er === cr || er.startsWith(cr + sep));
|
|
79
|
+
if (!ok)
|
|
80
|
+
invalid(`SOHOPAY_SIGNER_KEY_ROOTS entry ${er} is not within a configured root`);
|
|
81
|
+
narrowed.push(er);
|
|
82
|
+
}
|
|
83
|
+
return narrowed;
|
|
84
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from "node:util";
|
|
2
|
+
import { loadVectors } from "@sohopay/signer-vectors";
|
|
3
|
+
import { toHex } from "../encoding.js";
|
|
4
|
+
import { SignerError } from "../errors.js";
|
|
5
|
+
import { buildPaymentSignatureHeader } from "../envelope.js";
|
|
6
|
+
import { jcs } from "../jcs.js";
|
|
7
|
+
import { computeJkt } from "../keys.js";
|
|
8
|
+
import { buildPopChallengeMessage, signPoP } from "../pop.js";
|
|
9
|
+
import { buildVoucherSignedBytes, computePaymentId, signVoucher, } from "../voucher.js";
|
|
10
|
+
/**
|
|
11
|
+
* Negative vectors that are backend-verify-only (cross-replay invariants): the
|
|
12
|
+
* client cannot reproduce them, so they are intentionally skipped here. Any
|
|
13
|
+
* negative id NOT handled by the switch and NOT in this set is treated as an
|
|
14
|
+
* unhandled new vector and fails, so coverage can never regress silently.
|
|
15
|
+
*/
|
|
16
|
+
const BACKEND_ONLY_NEGATIVES = new Set([
|
|
17
|
+
"neg-cross-replay-voucher-as-pop",
|
|
18
|
+
"neg-cross-replay-pop-as-voucher",
|
|
19
|
+
]);
|
|
20
|
+
/** Runs the full known-answer set in-process. A host calls this to self-certify. */
|
|
21
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
22
|
+
export function verifyVectors(doc = loadVectors()) {
|
|
23
|
+
const testKey = doc.testKeys[0];
|
|
24
|
+
const failures = [];
|
|
25
|
+
let passed = 0;
|
|
26
|
+
const check = (id, actual, expected) => {
|
|
27
|
+
if (expected === undefined) {
|
|
28
|
+
failures.push(`${id}:no-expected`);
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
if (isDeepStrictEqual(actual, expected)) {
|
|
32
|
+
passed += 1;
|
|
33
|
+
}
|
|
34
|
+
else {
|
|
35
|
+
failures.push(id);
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
const checkThrows = (id, fn, expectedCode) => {
|
|
39
|
+
try {
|
|
40
|
+
fn();
|
|
41
|
+
failures.push(`${id}:did-not-throw`);
|
|
42
|
+
}
|
|
43
|
+
catch (e) {
|
|
44
|
+
if (e instanceof SignerError && e.code === expectedCode)
|
|
45
|
+
passed += 1;
|
|
46
|
+
else
|
|
47
|
+
failures.push(`${id}:wrong-error`);
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
for (const v of doc.vectors.jcs) {
|
|
51
|
+
// Standalone canonicalization, incl. the unicode/NUL edges the voucher
|
|
52
|
+
// payloads don't exercise — asserted directly so a JCS divergence surfaces.
|
|
53
|
+
check(`jcs:${v.id}`, jcs(v.input), v.expected.canonical);
|
|
54
|
+
}
|
|
55
|
+
for (const v of doc.vectors.jkt) {
|
|
56
|
+
check(`jkt:${v.id}`, computeJkt(v.input.publicJwk), v.expected.jkt);
|
|
57
|
+
}
|
|
58
|
+
for (const v of doc.vectors.pop) {
|
|
59
|
+
check(`pop-msg:${v.id}`, toHex(buildPopChallengeMessage(v.input.fields)), v.expected.messageUtf8Hex);
|
|
60
|
+
check(`pop-sig:${v.id}`, signPoP(v.input.fields, testKey.seedB64Url).pop_signature, v.expected.popSignature);
|
|
61
|
+
}
|
|
62
|
+
for (const v of doc.vectors.voucherPaymentId) {
|
|
63
|
+
check(`pid:${v.id}`, computePaymentId(v.input.core), v.expected.paymentId);
|
|
64
|
+
}
|
|
65
|
+
for (const v of doc.vectors.voucherSignature) {
|
|
66
|
+
const voucher = v.input.voucher;
|
|
67
|
+
check(`vsig-pre:${v.id}`, toHex(buildVoucherSignedBytes(voucher)), v.expected.preimageHex);
|
|
68
|
+
check(`vsig:${v.id}`, signVoucher({
|
|
69
|
+
voucher,
|
|
70
|
+
privateKeyBase64Url: testKey.seedB64Url,
|
|
71
|
+
signing: v.input.signing,
|
|
72
|
+
publicJwk: testKey.publicJwk,
|
|
73
|
+
}).signature, v.expected.signature);
|
|
74
|
+
}
|
|
75
|
+
for (const v of doc.vectors.envelope) {
|
|
76
|
+
// env-value derives both sides from v.input.prepareResponse via the same
|
|
77
|
+
// fill-signature → compact-JSON → base64 transform, so it pins this runtime's
|
|
78
|
+
// SERIALIZATION (key order, padding) byte-for-byte across languages — it does
|
|
79
|
+
// NOT attest the envelope's shape/completeness; that correctness is owned by
|
|
80
|
+
// the backend vector generator that produced prepareResponse + headerValue.
|
|
81
|
+
const { headerName, headerValue } = buildPaymentSignatureHeader(v.input.prepareResponse, v.input.signature);
|
|
82
|
+
check(`env-name:${v.id}`, headerName, v.expected.headerName);
|
|
83
|
+
// Normative byte-exact header_value (standard base64 of the compact completed envelope).
|
|
84
|
+
check(`env-value:${v.id}`, headerValue, v.expected.headerValue);
|
|
85
|
+
check(`env-decoded:${v.id}`, JSON.parse(Buffer.from(headerValue, "base64").toString("utf8")), v.expected.decodedEnvelope);
|
|
86
|
+
}
|
|
87
|
+
for (const v of doc.negative) {
|
|
88
|
+
switch (v.id) {
|
|
89
|
+
case "neg-voucher-field-number":
|
|
90
|
+
checkThrows(v.id, () => computePaymentId(v.input.core), v.expectError);
|
|
91
|
+
break;
|
|
92
|
+
case "neg-pop-iat-float":
|
|
93
|
+
checkThrows(v.id, () => buildPopChallengeMessage(v.input.fields), v.expectError);
|
|
94
|
+
break;
|
|
95
|
+
case "neg-downgrade-algorithm":
|
|
96
|
+
checkThrows(v.id, () => signVoucher({
|
|
97
|
+
voucher: doc.vectors.voucherSignature[0].input.voucher,
|
|
98
|
+
privateKeyBase64Url: testKey.seedB64Url,
|
|
99
|
+
signing: v.input.signing,
|
|
100
|
+
}), v.expectError);
|
|
101
|
+
break;
|
|
102
|
+
case "neg-public-jwk-has-private-d":
|
|
103
|
+
checkThrows(v.id, () => computeJkt(v.input.publicJwk), v.expectError);
|
|
104
|
+
break;
|
|
105
|
+
default:
|
|
106
|
+
// Backend-only cross-replay invariants are skipped by design; anything
|
|
107
|
+
// else is a new negative vector this client doesn't yet assert — fail so
|
|
108
|
+
// it is noticed rather than silently uncovered.
|
|
109
|
+
if (!BACKEND_ONLY_NEGATIVES.has(v.id)) {
|
|
110
|
+
failures.push(`${v.id}:unhandled-negative`);
|
|
111
|
+
}
|
|
112
|
+
break;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return { passed, failed: failures.length, total: passed + failures.length, failures };
|
|
116
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compiled-in protocol constants. These are the SDK's source of truth for what
|
|
3
|
+
* it will sign; a server-supplied `signing` block is only ever VALIDATED against
|
|
4
|
+
* these, never substituted for them (downgrade protection).
|
|
5
|
+
*/
|
|
6
|
+
/** Protocol-V2 Envelope 1 domain-separation tag (SOHO-251 / T12). */
|
|
7
|
+
export declare const VOUCHER_DOMAIN_TAG = "SohoPay:AgentPaymentVoucher:v2";
|
|
8
|
+
/** Single 0x00 byte between the tag and the canonical JSON in every tagged preimage. */
|
|
9
|
+
export declare const DOMAIN_SEPARATOR_BYTE = 0;
|
|
10
|
+
/** Merchant-settler unlock header for the filled x402 envelope. */
|
|
11
|
+
export declare const PAYMENT_SIGNATURE_HEADER = "PAYMENT-SIGNATURE";
|
|
12
|
+
/** The only signing scheme this SDK version implements. */
|
|
13
|
+
export declare const SUPPORTED_SIGNING: {
|
|
14
|
+
readonly algorithm: "Ed25519";
|
|
15
|
+
readonly domain_tag: "SohoPay:AgentPaymentVoucher:v2";
|
|
16
|
+
readonly canonicalization: "RFC8785";
|
|
17
|
+
readonly signature_encoding: "base64url";
|
|
18
|
+
};
|
|
19
|
+
/** The nine economic core fields, in the explicit projection order (never a spread). */
|
|
20
|
+
export declare const VOUCHER_CORE_FIELDS: readonly ["agentId", "merchantId", "asset", "chainId", "amount", "feeAmount", "orderRef", "nonce", "deadline"];
|
|
21
|
+
/** SP1 protocol identifier — advertised by every conformant executable. */
|
|
22
|
+
export declare const SIGNER_PROTOCOL = "sohopay-signer/1";
|
|
23
|
+
/** This implementation's package name, stamped into machine output. */
|
|
24
|
+
export declare const IMPLEMENTATION = "@sohopay/agent-signer";
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compiled-in protocol constants. These are the SDK's source of truth for what
|
|
3
|
+
* it will sign; a server-supplied `signing` block is only ever VALIDATED against
|
|
4
|
+
* these, never substituted for them (downgrade protection).
|
|
5
|
+
*/
|
|
6
|
+
/** Protocol-V2 Envelope 1 domain-separation tag (SOHO-251 / T12). */
|
|
7
|
+
export const VOUCHER_DOMAIN_TAG = "SohoPay:AgentPaymentVoucher:v2";
|
|
8
|
+
/** Single 0x00 byte between the tag and the canonical JSON in every tagged preimage. */
|
|
9
|
+
export const DOMAIN_SEPARATOR_BYTE = 0x00;
|
|
10
|
+
/** Merchant-settler unlock header for the filled x402 envelope. */
|
|
11
|
+
export const PAYMENT_SIGNATURE_HEADER = "PAYMENT-SIGNATURE";
|
|
12
|
+
/** The only signing scheme this SDK version implements. */
|
|
13
|
+
export const SUPPORTED_SIGNING = {
|
|
14
|
+
algorithm: "Ed25519",
|
|
15
|
+
domain_tag: VOUCHER_DOMAIN_TAG,
|
|
16
|
+
canonicalization: "RFC8785",
|
|
17
|
+
signature_encoding: "base64url",
|
|
18
|
+
};
|
|
19
|
+
/** The nine economic core fields, in the explicit projection order (never a spread). */
|
|
20
|
+
export const VOUCHER_CORE_FIELDS = [
|
|
21
|
+
"agentId",
|
|
22
|
+
"merchantId",
|
|
23
|
+
"asset",
|
|
24
|
+
"chainId",
|
|
25
|
+
"amount",
|
|
26
|
+
"feeAmount",
|
|
27
|
+
"orderRef",
|
|
28
|
+
"nonce",
|
|
29
|
+
"deadline",
|
|
30
|
+
];
|
|
31
|
+
/** SP1 protocol identifier — advertised by every conformant executable. */
|
|
32
|
+
export const SIGNER_PROTOCOL = "sohopay-signer/1";
|
|
33
|
+
/** This implementation's package name, stamped into machine output. */
|
|
34
|
+
export const IMPLEMENTATION = "@sohopay/agent-signer";
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** Byte/string encoding helpers, centralized so every preimage uses the same ones. */
|
|
2
|
+
export declare const toBase64Url: (bytes: Uint8Array) => string;
|
|
3
|
+
export declare const fromBase64Url: (value: string) => Uint8Array;
|
|
4
|
+
export declare const toHex: (bytes: Uint8Array) => string;
|
|
5
|
+
export declare const utf8Bytes: (value: string) => Uint8Array;
|
package/dist/encoding.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** Byte/string encoding helpers, centralized so every preimage uses the same ones. */
|
|
2
|
+
export const toBase64Url = (bytes) => Buffer.from(bytes).toString("base64url");
|
|
3
|
+
export const fromBase64Url = (value) => new Uint8Array(Buffer.from(value, "base64url"));
|
|
4
|
+
export const toHex = (bytes) => Buffer.from(bytes).toString("hex");
|
|
5
|
+
export const utf8Bytes = (value) => new Uint8Array(Buffer.from(value, "utf8"));
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export interface PaymentSignatureHeader {
|
|
2
|
+
headerName: string;
|
|
3
|
+
headerValue: string;
|
|
4
|
+
envelope: unknown;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Fills `paymentPayload.payload.signature` on a clone of the prepare response and
|
|
8
|
+
* base64-encodes it into the PAYMENT-SIGNATURE header. The signature is bound by
|
|
9
|
+
* JCS(voucher), so envelope key ordering here is not security-relevant.
|
|
10
|
+
*/
|
|
11
|
+
export declare function buildPaymentSignatureHeader(prepareResponse: unknown, signature: string): PaymentSignatureHeader;
|
package/dist/envelope.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { PAYMENT_SIGNATURE_HEADER } from "./constants.js";
|
|
2
|
+
import { SignerError } from "./errors.js";
|
|
3
|
+
/**
|
|
4
|
+
* Fills `paymentPayload.payload.signature` on a clone of the prepare response and
|
|
5
|
+
* base64-encodes it into the PAYMENT-SIGNATURE header. The signature is bound by
|
|
6
|
+
* JCS(voucher), so envelope key ordering here is not security-relevant.
|
|
7
|
+
*/
|
|
8
|
+
export function buildPaymentSignatureHeader(prepareResponse, signature) {
|
|
9
|
+
if (prepareResponse === null || typeof prepareResponse !== "object") {
|
|
10
|
+
throw new SignerError("MALFORMED_ENVELOPE", "prepare response must be an object");
|
|
11
|
+
}
|
|
12
|
+
const envelope = structuredClone(prepareResponse);
|
|
13
|
+
const payload = envelope.paymentPayload?.payload;
|
|
14
|
+
if (!payload) {
|
|
15
|
+
throw new SignerError("MALFORMED_ENVELOPE", "prepare response missing paymentPayload.payload");
|
|
16
|
+
}
|
|
17
|
+
payload.signature = signature;
|
|
18
|
+
const headerValue = Buffer.from(JSON.stringify(envelope), "utf8").toString("base64");
|
|
19
|
+
return { headerName: PAYMENT_SIGNATURE_HEADER, headerValue, envelope };
|
|
20
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** Typed error taxonomy. Hosts (S12) use `code` to tell terminal from retryable. */
|
|
2
|
+
export type SignerErrorCode = "VOUCHER_FIELD_NOT_STRING" | "POP_IAT_NOT_INTEGER" | "SIGNING_SCHEME_NOT_ALLOWED" | "PRIVATE_KEY_MATERIAL_REJECTED" | "INVALID_PRIVATE_KEY" | "INVALID_PUBLIC_JWK" | "PAYMENT_ID_MISMATCH" | "AGENT_KEY_JKT_MISMATCH" | "MALFORMED_ENVELOPE" | "INVALID_TERMINAL_ID" | "INVALID_HARNESS" | "INVALID_BORROWER_ID" | "INSECURE_KEY_PERMISSIONS" | "STORED_KEY_CORRUPT" | "IDEMPOTENCY_PAYLOAD_MISMATCH" | "OPERATION_NOT_FOUND" | "KEY_PATH_INVALID" | "CROSS_BORROWER_KEY" | "TERMINAL_MISMATCH" | "KEY_INTEGRITY_FAILED" | "KEY_PERSIST_FAILED" | "INLINE_KEY_REJECTED" | "MALFORMED_INPUT";
|
|
3
|
+
/** All SDK-raised failures carry a stable `code` from {@link SignerErrorCode}. */
|
|
4
|
+
export declare class SignerError extends Error {
|
|
5
|
+
readonly code: SignerErrorCode;
|
|
6
|
+
constructor(code: SignerErrorCode, message: string);
|
|
7
|
+
}
|
package/dist/errors.js
ADDED
package/dist/flow.d.ts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { Ed25519PublicJwk } from "./keys.js";
|
|
2
|
+
import { type OperationStore } from "./operations.js";
|
|
3
|
+
import { type AgentPaymentVoucher, type ServerSigningBlock } from "./voucher.js";
|
|
4
|
+
/**
|
|
5
|
+
* S12 — optional reference orchestration of one x402 payment using the SDK.
|
|
6
|
+
*
|
|
7
|
+
* This is a convenience, not a required layer: a host may call the primitives
|
|
8
|
+
* (`signVoucher`, the operation ledger, `recoveryAction`) directly. It exists to
|
|
9
|
+
* show the canonical, recovery-aware sequence and to prove the pieces compose.
|
|
10
|
+
* It performs NO I/O — every network call is delegated to {@link HostTransport},
|
|
11
|
+
* which the host implements over its own MCP client / HTTP.
|
|
12
|
+
*/
|
|
13
|
+
/** `prepare_x402_payment` returned an unsigned voucher (Protocol V2). */
|
|
14
|
+
export interface PrepareVoucherResult {
|
|
15
|
+
status: "VOUCHER_ISSUED";
|
|
16
|
+
voucher: AgentPaymentVoucher;
|
|
17
|
+
/** The server's advertised signing block, validated by signVoucher. */
|
|
18
|
+
signing?: ServerSigningBlock;
|
|
19
|
+
/** The prepare-response envelope to fill with the signature (paymentPayload wrapper). */
|
|
20
|
+
prepareResponse: unknown;
|
|
21
|
+
}
|
|
22
|
+
/** Any non-voucher prepare outcome (e.g. a terminal FAILED, or legacy V1 COMPLETED). */
|
|
23
|
+
export interface PrepareTerminalResult {
|
|
24
|
+
status: string;
|
|
25
|
+
}
|
|
26
|
+
export type PrepareResult = PrepareVoucherResult | PrepareTerminalResult;
|
|
27
|
+
export interface SettlementStatus {
|
|
28
|
+
status: string;
|
|
29
|
+
terminal: boolean;
|
|
30
|
+
}
|
|
31
|
+
/** The host-provided transport. The SDK never does I/O itself. */
|
|
32
|
+
export interface HostTransport {
|
|
33
|
+
prepare(input: {
|
|
34
|
+
borrowerId: string;
|
|
35
|
+
orderRef: string;
|
|
36
|
+
idempotencyKey: string;
|
|
37
|
+
}): Promise<PrepareResult>;
|
|
38
|
+
submit(input: {
|
|
39
|
+
paymentId: string;
|
|
40
|
+
headerName: string;
|
|
41
|
+
headerValue: string;
|
|
42
|
+
}): Promise<void>;
|
|
43
|
+
getStatus(input: {
|
|
44
|
+
borrowerId: string;
|
|
45
|
+
paymentId: string;
|
|
46
|
+
}): Promise<SettlementStatus>;
|
|
47
|
+
}
|
|
48
|
+
export interface ExecutePaymentArgs {
|
|
49
|
+
transport: HostTransport;
|
|
50
|
+
store: OperationStore;
|
|
51
|
+
borrowerId: string;
|
|
52
|
+
orderRef: string;
|
|
53
|
+
/** The agent workload private seed (base64url) used to sign the voucher. */
|
|
54
|
+
privateKeyBase64Url: string;
|
|
55
|
+
/** Optional: asserts the voucher's agentKeyJkt matches this signing key. */
|
|
56
|
+
publicJwk?: Ed25519PublicJwk;
|
|
57
|
+
}
|
|
58
|
+
export interface ExecutePaymentResult {
|
|
59
|
+
paymentId?: string;
|
|
60
|
+
status: string;
|
|
61
|
+
terminal: boolean;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Runs (or resumes) one payment. On resume it consults the operation ledger:
|
|
65
|
+
* a terminal op returns immediately, an op that already has a voucher queries
|
|
66
|
+
* authoritative status (never re-submits), and an op with no voucher yet re-
|
|
67
|
+
* prepares under the same idempotency key. A fresh run prepares → signs →
|
|
68
|
+
* submits → resolves.
|
|
69
|
+
*/
|
|
70
|
+
export declare function executePayment(args: ExecutePaymentArgs): Promise<ExecutePaymentResult>;
|
package/dist/flow.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { buildPaymentSignatureHeader } from "./envelope.js";
|
|
2
|
+
import { advancePhase, beginOperation, recordPrepared, recoveryAction, resolveOperation, } from "./operations.js";
|
|
3
|
+
import { signVoucher } from "./voucher.js";
|
|
4
|
+
function isVoucherResult(result) {
|
|
5
|
+
return result.status === "VOUCHER_ISSUED";
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Runs (or resumes) one payment. On resume it consults the operation ledger:
|
|
9
|
+
* a terminal op returns immediately, an op that already has a voucher queries
|
|
10
|
+
* authoritative status (never re-submits), and an op with no voucher yet re-
|
|
11
|
+
* prepares under the same idempotency key. A fresh run prepares → signs →
|
|
12
|
+
* submits → resolves.
|
|
13
|
+
*/
|
|
14
|
+
export async function executePayment(args) {
|
|
15
|
+
const { transport, store, borrowerId, orderRef } = args;
|
|
16
|
+
const op = beginOperation({ store, borrowerId, orderRef });
|
|
17
|
+
switch (recoveryAction(op)) {
|
|
18
|
+
case "DONE":
|
|
19
|
+
return { paymentId: op.paymentId, status: op.status ?? "RESOLVED", terminal: true };
|
|
20
|
+
case "QUERY_STATUS": {
|
|
21
|
+
const status = await transport.getStatus({ borrowerId, paymentId: op.paymentId });
|
|
22
|
+
if (status.terminal) {
|
|
23
|
+
resolveOperation({ store, borrowerId, orderRef, status: status.status });
|
|
24
|
+
}
|
|
25
|
+
return { paymentId: op.paymentId, status: status.status, terminal: status.terminal };
|
|
26
|
+
}
|
|
27
|
+
case "RETRY_PREPARE":
|
|
28
|
+
break;
|
|
29
|
+
}
|
|
30
|
+
const prepared = await transport.prepare({ borrowerId, orderRef, idempotencyKey: op.idempotencyKey });
|
|
31
|
+
if (!isVoucherResult(prepared)) {
|
|
32
|
+
resolveOperation({ store, borrowerId, orderRef, status: prepared.status });
|
|
33
|
+
return { status: prepared.status, terminal: true };
|
|
34
|
+
}
|
|
35
|
+
recordPrepared({
|
|
36
|
+
store,
|
|
37
|
+
borrowerId,
|
|
38
|
+
orderRef,
|
|
39
|
+
paymentId: prepared.voucher.paymentId,
|
|
40
|
+
agentKeyJkt: prepared.voucher.agentKeyJkt,
|
|
41
|
+
voucherDeadline: prepared.voucher.deadline,
|
|
42
|
+
});
|
|
43
|
+
const { signature } = signVoucher({
|
|
44
|
+
voucher: prepared.voucher,
|
|
45
|
+
signing: prepared.signing,
|
|
46
|
+
privateKeyBase64Url: args.privateKeyBase64Url,
|
|
47
|
+
publicJwk: args.publicJwk,
|
|
48
|
+
});
|
|
49
|
+
advancePhase({ store, borrowerId, orderRef, phase: "SIGNED" });
|
|
50
|
+
const header = buildPaymentSignatureHeader(prepared.prepareResponse, signature);
|
|
51
|
+
await transport.submit({
|
|
52
|
+
paymentId: prepared.voucher.paymentId,
|
|
53
|
+
headerName: header.headerName,
|
|
54
|
+
headerValue: header.headerValue,
|
|
55
|
+
});
|
|
56
|
+
advancePhase({ store, borrowerId, orderRef, phase: "SUBMITTED" });
|
|
57
|
+
const status = await transport.getStatus({ borrowerId, paymentId: prepared.voucher.paymentId });
|
|
58
|
+
if (status.terminal) {
|
|
59
|
+
resolveOperation({ store, borrowerId, orderRef, status: status.status });
|
|
60
|
+
}
|
|
61
|
+
return { paymentId: prepared.voucher.paymentId, status: status.status, terminal: status.terminal };
|
|
62
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** A fresh UUID v4 idempotency key (what the backend's @Idempotent endpoints require). */
|
|
2
|
+
export declare function newIdempotencyKey(): string;
|
|
3
|
+
export interface IdempotencyRecord {
|
|
4
|
+
key: string;
|
|
5
|
+
/** The client-computed paymentId this key is bound to, once known. */
|
|
6
|
+
paymentId?: string;
|
|
7
|
+
}
|
|
8
|
+
/** Pluggable persistence for idempotency records. Default is in-memory. */
|
|
9
|
+
export interface IdempotencyStore {
|
|
10
|
+
get(scope: string): IdempotencyRecord | undefined;
|
|
11
|
+
set(scope: string, record: IdempotencyRecord): void;
|
|
12
|
+
}
|
|
13
|
+
/** Process-lifetime store. Swap for a persistent one to survive restarts. */
|
|
14
|
+
export declare class InMemoryIdempotencyStore implements IdempotencyStore {
|
|
15
|
+
private readonly records;
|
|
16
|
+
get(scope: string): IdempotencyRecord | undefined;
|
|
17
|
+
set(scope: string, record: IdempotencyRecord): void;
|
|
18
|
+
}
|
|
19
|
+
export interface ResolveIdempotencyKeyArgs {
|
|
20
|
+
borrowerId: string;
|
|
21
|
+
orderRef: string;
|
|
22
|
+
/** When known, binds the key to this paymentId and guards against payload drift. */
|
|
23
|
+
paymentId?: string;
|
|
24
|
+
store?: IdempotencyStore;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Returns a stable idempotency key for a logical payment `(borrowerId, orderRef)`,
|
|
28
|
+
* minting one on first use and reusing it on retry. If the same order is retried
|
|
29
|
+
* with a DIFFERENT `paymentId`, it throws rather than silently reusing the key —
|
|
30
|
+
* a changed amount/payee is a new payment, not a retry.
|
|
31
|
+
*/
|
|
32
|
+
export declare function resolveIdempotencyKey(args: ResolveIdempotencyKeyArgs): string;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { SignerError } from "./errors.js";
|
|
3
|
+
/** A fresh UUID v4 idempotency key (what the backend's @Idempotent endpoints require). */
|
|
4
|
+
export function newIdempotencyKey() {
|
|
5
|
+
return randomUUID();
|
|
6
|
+
}
|
|
7
|
+
/** Process-lifetime store. Swap for a persistent one to survive restarts. */
|
|
8
|
+
export class InMemoryIdempotencyStore {
|
|
9
|
+
records = new Map();
|
|
10
|
+
get(scope) {
|
|
11
|
+
return this.records.get(scope);
|
|
12
|
+
}
|
|
13
|
+
set(scope, record) {
|
|
14
|
+
this.records.set(scope, record);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
const defaultStore = new InMemoryIdempotencyStore();
|
|
18
|
+
function scopeKey(borrowerId, orderRef) {
|
|
19
|
+
return `${borrowerId}\u0000${orderRef}`;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Returns a stable idempotency key for a logical payment `(borrowerId, orderRef)`,
|
|
23
|
+
* minting one on first use and reusing it on retry. If the same order is retried
|
|
24
|
+
* with a DIFFERENT `paymentId`, it throws rather than silently reusing the key —
|
|
25
|
+
* a changed amount/payee is a new payment, not a retry.
|
|
26
|
+
*/
|
|
27
|
+
export function resolveIdempotencyKey(args) {
|
|
28
|
+
const store = args.store ?? defaultStore;
|
|
29
|
+
const scope = scopeKey(args.borrowerId, args.orderRef);
|
|
30
|
+
const existing = store.get(scope);
|
|
31
|
+
if (existing) {
|
|
32
|
+
if (args.paymentId &&
|
|
33
|
+
existing.paymentId &&
|
|
34
|
+
existing.paymentId.toLowerCase() !== args.paymentId.toLowerCase()) {
|
|
35
|
+
throw new SignerError("IDEMPOTENCY_PAYLOAD_MISMATCH", `orderRef "${args.orderRef}" was already used for a different paymentId`);
|
|
36
|
+
}
|
|
37
|
+
if (args.paymentId && !existing.paymentId) {
|
|
38
|
+
store.set(scope, { ...existing, paymentId: args.paymentId });
|
|
39
|
+
}
|
|
40
|
+
return existing.key;
|
|
41
|
+
}
|
|
42
|
+
const record = { key: newIdempotencyKey(), paymentId: args.paymentId };
|
|
43
|
+
store.set(scope, record);
|
|
44
|
+
return record.key;
|
|
45
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export * from "./constants.js";
|
|
2
|
+
export * from "./errors.js";
|
|
3
|
+
export * from "./keys.js";
|
|
4
|
+
export * from "./voucher.js";
|
|
5
|
+
export * from "./pop.js";
|
|
6
|
+
export * from "./envelope.js";
|
|
7
|
+
export * from "./terminal.js";
|
|
8
|
+
export * from "./storage.js";
|
|
9
|
+
export * from "./idempotency.js";
|
|
10
|
+
export * from "./operations.js";
|
|
11
|
+
export * from "./rotation.js";
|
|
12
|
+
export * from "./flow.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export * from "./constants.js";
|
|
2
|
+
export * from "./errors.js";
|
|
3
|
+
export * from "./keys.js";
|
|
4
|
+
export * from "./voucher.js";
|
|
5
|
+
export * from "./pop.js";
|
|
6
|
+
export * from "./envelope.js";
|
|
7
|
+
export * from "./terminal.js";
|
|
8
|
+
export * from "./storage.js";
|
|
9
|
+
export * from "./idempotency.js";
|
|
10
|
+
export * from "./operations.js";
|
|
11
|
+
export * from "./rotation.js";
|
|
12
|
+
export * from "./flow.js";
|
package/dist/jcs.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RFC 8785 JSON Canonicalization Scheme. Uses the same `canonicalize` package
|
|
3
|
+
* (exact-pinned) as the backend so preimages are byte-identical. Throws rather
|
|
4
|
+
* than returning an empty string on non-canonicalizable input (undefined,
|
|
5
|
+
* functions) — an empty preimage would hash/sign deterministically to a value
|
|
6
|
+
* no verifier expects.
|
|
7
|
+
*/
|
|
8
|
+
export declare function jcs(value: unknown): string;
|
package/dist/jcs.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import canonicalize from "canonicalize";
|
|
2
|
+
/**
|
|
3
|
+
* RFC 8785 JSON Canonicalization Scheme. Uses the same `canonicalize` package
|
|
4
|
+
* (exact-pinned) as the backend so preimages are byte-identical. Throws rather
|
|
5
|
+
* than returning an empty string on non-canonicalizable input (undefined,
|
|
6
|
+
* functions) — an empty preimage would hash/sign deterministically to a value
|
|
7
|
+
* no verifier expects.
|
|
8
|
+
*/
|
|
9
|
+
export function jcs(value) {
|
|
10
|
+
const canonical = canonicalize(value);
|
|
11
|
+
if (canonical === undefined) {
|
|
12
|
+
throw new Error("JCS canonicalization produced undefined");
|
|
13
|
+
}
|
|
14
|
+
return canonical;
|
|
15
|
+
}
|
package/dist/keys.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export interface Ed25519PublicJwk {
|
|
2
|
+
kty: "OKP";
|
|
3
|
+
crv: "Ed25519";
|
|
4
|
+
x: string;
|
|
5
|
+
}
|
|
6
|
+
export interface WorkloadKeypair {
|
|
7
|
+
/** 32-byte Ed25519 seed, base64url. Stays on the client — never transmitted. */
|
|
8
|
+
privateKeyBase64Url: string;
|
|
9
|
+
publicJwk: Ed25519PublicJwk;
|
|
10
|
+
jkt: string;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Validates that a value is an Ed25519 PUBLIC JWK with no private material.
|
|
14
|
+
* The borrower-key boundary: the SDK only handles agent workload keys, and a
|
|
15
|
+
* JWK carrying `d` is rejected outright.
|
|
16
|
+
*/
|
|
17
|
+
export declare function assertPublicJwk(value: unknown): Ed25519PublicJwk;
|
|
18
|
+
/** RFC 7638 thumbprint: base64url(SHA-256(JCS({ crv, kty, x }))). */
|
|
19
|
+
export declare function computeJkt(publicJwk: Ed25519PublicJwk): string;
|
|
20
|
+
/** Generates a fresh agent workload keypair. The private seed is never logged or sent. */
|
|
21
|
+
export declare function generateWorkloadKey(): WorkloadKeypair;
|
|
22
|
+
/**
|
|
23
|
+
* Decodes a base64url Ed25519 private seed, asserting the 32-byte length so a
|
|
24
|
+
* malformed key fails with a specific code instead of a generic envelope error.
|
|
25
|
+
*/
|
|
26
|
+
export declare function decodeWorkloadSeed(privateKeyBase64Url: string): Uint8Array;
|
|
27
|
+
/** Rehydrates the public half + jkt from a persisted private seed. */
|
|
28
|
+
export declare function workloadKeyFromPrivate(privateKeyBase64Url: string): WorkloadKeypair;
|