@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
package/dist/keys.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { ed25519 } from "@noble/curves/ed25519";
|
|
3
|
+
import { fromBase64Url, toBase64Url } from "./encoding.js";
|
|
4
|
+
import { SignerError } from "./errors.js";
|
|
5
|
+
import { jcs } from "./jcs.js";
|
|
6
|
+
/**
|
|
7
|
+
* Validates that a value is an Ed25519 PUBLIC JWK with no private material.
|
|
8
|
+
* The borrower-key boundary: the SDK only handles agent workload keys, and a
|
|
9
|
+
* JWK carrying `d` is rejected outright.
|
|
10
|
+
*/
|
|
11
|
+
export function assertPublicJwk(value) {
|
|
12
|
+
if (value === null || typeof value !== "object") {
|
|
13
|
+
throw new SignerError("INVALID_PUBLIC_JWK", "public JWK must be an object");
|
|
14
|
+
}
|
|
15
|
+
const jwk = value;
|
|
16
|
+
if ("d" in jwk) {
|
|
17
|
+
throw new SignerError("PRIVATE_KEY_MATERIAL_REJECTED", "JWK must not contain private key material (d)");
|
|
18
|
+
}
|
|
19
|
+
if (jwk.kty !== "OKP" ||
|
|
20
|
+
jwk.crv !== "Ed25519" ||
|
|
21
|
+
typeof jwk.x !== "string" ||
|
|
22
|
+
jwk.x.length === 0) {
|
|
23
|
+
throw new SignerError("INVALID_PUBLIC_JWK", "expected an Ed25519 OKP public JWK with a non-empty x");
|
|
24
|
+
}
|
|
25
|
+
return { kty: "OKP", crv: "Ed25519", x: jwk.x };
|
|
26
|
+
}
|
|
27
|
+
/** RFC 7638 thumbprint: base64url(SHA-256(JCS({ crv, kty, x }))). */
|
|
28
|
+
export function computeJkt(publicJwk) {
|
|
29
|
+
const validated = assertPublicJwk(publicJwk);
|
|
30
|
+
const canonical = jcs({ crv: validated.crv, kty: validated.kty, x: validated.x });
|
|
31
|
+
return createHash("sha256").update(canonical, "utf8").digest("base64url");
|
|
32
|
+
}
|
|
33
|
+
function keypairFromSeed(seed) {
|
|
34
|
+
const publicKey = ed25519.getPublicKey(seed);
|
|
35
|
+
const publicJwk = {
|
|
36
|
+
kty: "OKP",
|
|
37
|
+
crv: "Ed25519",
|
|
38
|
+
x: toBase64Url(publicKey),
|
|
39
|
+
};
|
|
40
|
+
return {
|
|
41
|
+
privateKeyBase64Url: toBase64Url(seed),
|
|
42
|
+
publicJwk,
|
|
43
|
+
jkt: computeJkt(publicJwk),
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/** Generates a fresh agent workload keypair. The private seed is never logged or sent. */
|
|
47
|
+
export function generateWorkloadKey() {
|
|
48
|
+
return keypairFromSeed(ed25519.utils.randomPrivateKey());
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Decodes a base64url Ed25519 private seed, asserting the 32-byte length so a
|
|
52
|
+
* malformed key fails with a specific code instead of a generic envelope error.
|
|
53
|
+
*/
|
|
54
|
+
export function decodeWorkloadSeed(privateKeyBase64Url) {
|
|
55
|
+
const seed = fromBase64Url(privateKeyBase64Url);
|
|
56
|
+
if (seed.length !== 32) {
|
|
57
|
+
throw new SignerError("INVALID_PRIVATE_KEY", `Ed25519 private seed must be 32 bytes, got ${seed.length}`);
|
|
58
|
+
}
|
|
59
|
+
return seed;
|
|
60
|
+
}
|
|
61
|
+
/** Rehydrates the public half + jkt from a persisted private seed. */
|
|
62
|
+
export function workloadKeyFromPrivate(privateKeyBase64Url) {
|
|
63
|
+
return keypairFromSeed(decodeWorkloadSeed(privateKeyBase64Url));
|
|
64
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* S9 — client-side operation ledger for crash/timeout recovery. Tracks each
|
|
3
|
+
* logical payment `(borrowerId, orderRef)` through its phases so that after an
|
|
4
|
+
* interruption the client can decide whether to safely re-prepare (idempotent)
|
|
5
|
+
* or query authoritative status — never blindly re-submit a money operation.
|
|
6
|
+
*
|
|
7
|
+
* The SDK does NOT make the status HTTP call (that is the host's transport); it
|
|
8
|
+
* records state and recommends the next action via {@link recoveryAction}.
|
|
9
|
+
*/
|
|
10
|
+
export type OperationPhase = "STARTED" | "PREPARED" | "SIGNED" | "SUBMITTED" | "RESOLVED";
|
|
11
|
+
export interface OperationRecord {
|
|
12
|
+
borrowerId: string;
|
|
13
|
+
orderRef: string;
|
|
14
|
+
/** The idempotency key bound to this logical payment (reused on every retry). */
|
|
15
|
+
idempotencyKey: string;
|
|
16
|
+
/** Set once prepare returns a voucher. */
|
|
17
|
+
paymentId?: string;
|
|
18
|
+
/** jkt the voucher was signed under — used by the rotation drain gate (S10). */
|
|
19
|
+
agentKeyJkt?: string;
|
|
20
|
+
/** Voucher validity, unix seconds (string) — an elapsed deadline is uncapturable. */
|
|
21
|
+
voucherDeadline?: string;
|
|
22
|
+
phase: OperationPhase;
|
|
23
|
+
/** Last authoritative status the host observed (free-form, from the backend). */
|
|
24
|
+
status?: string;
|
|
25
|
+
terminal: boolean;
|
|
26
|
+
attempts: number;
|
|
27
|
+
/** epoch ms. */
|
|
28
|
+
createdAt: number;
|
|
29
|
+
updatedAt: number;
|
|
30
|
+
}
|
|
31
|
+
export interface OperationStore {
|
|
32
|
+
get(borrowerId: string, orderRef: string): OperationRecord | undefined;
|
|
33
|
+
put(record: OperationRecord): void;
|
|
34
|
+
list(borrowerId: string): OperationRecord[];
|
|
35
|
+
}
|
|
36
|
+
/** Process-lifetime store (does not survive restarts — use FileOperationStore for recovery). */
|
|
37
|
+
export declare class InMemoryOperationStore implements OperationStore {
|
|
38
|
+
private readonly records;
|
|
39
|
+
private key;
|
|
40
|
+
get(borrowerId: string, orderRef: string): OperationRecord | undefined;
|
|
41
|
+
put(record: OperationRecord): void;
|
|
42
|
+
list(borrowerId: string): OperationRecord[];
|
|
43
|
+
}
|
|
44
|
+
/** Durable store: one JSON file per borrower, so operations survive a restart. */
|
|
45
|
+
export declare class FileOperationStore implements OperationStore {
|
|
46
|
+
private readonly options;
|
|
47
|
+
constructor(options?: {
|
|
48
|
+
dataDir?: string;
|
|
49
|
+
});
|
|
50
|
+
private file;
|
|
51
|
+
private readAll;
|
|
52
|
+
get(borrowerId: string, orderRef: string): OperationRecord | undefined;
|
|
53
|
+
list(borrowerId: string): OperationRecord[];
|
|
54
|
+
put(record: OperationRecord): void;
|
|
55
|
+
}
|
|
56
|
+
export interface BeginOperationArgs {
|
|
57
|
+
store: OperationStore;
|
|
58
|
+
borrowerId: string;
|
|
59
|
+
orderRef: string;
|
|
60
|
+
/** Reuse an idempotency key (e.g. from resolveIdempotencyKey); minted if absent. */
|
|
61
|
+
idempotencyKey?: string;
|
|
62
|
+
now?: number;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Starts or resumes an operation. A resume (existing, non-terminal) bumps the
|
|
66
|
+
* attempt counter and keeps the same idempotency key; a terminal operation is
|
|
67
|
+
* returned unchanged (its {@link recoveryAction} is `DONE`).
|
|
68
|
+
*/
|
|
69
|
+
export declare function beginOperation(args: BeginOperationArgs): OperationRecord;
|
|
70
|
+
export interface RecordPreparedArgs {
|
|
71
|
+
store: OperationStore;
|
|
72
|
+
borrowerId: string;
|
|
73
|
+
orderRef: string;
|
|
74
|
+
paymentId: string;
|
|
75
|
+
agentKeyJkt?: string;
|
|
76
|
+
voucherDeadline?: string;
|
|
77
|
+
now?: number;
|
|
78
|
+
}
|
|
79
|
+
/** Records that prepare returned a voucher (paymentId known). */
|
|
80
|
+
export declare function recordPrepared(args: RecordPreparedArgs): OperationRecord;
|
|
81
|
+
/** Advances the phase (e.g. SIGNED after signing, SUBMITTED after handing to the merchant). */
|
|
82
|
+
export declare function advancePhase(args: {
|
|
83
|
+
store: OperationStore;
|
|
84
|
+
borrowerId: string;
|
|
85
|
+
orderRef: string;
|
|
86
|
+
phase: OperationPhase;
|
|
87
|
+
now?: number;
|
|
88
|
+
}): OperationRecord;
|
|
89
|
+
/** Marks the operation terminal with the authoritative status the host observed. */
|
|
90
|
+
export declare function resolveOperation(args: {
|
|
91
|
+
store: OperationStore;
|
|
92
|
+
borrowerId: string;
|
|
93
|
+
orderRef: string;
|
|
94
|
+
status?: string;
|
|
95
|
+
now?: number;
|
|
96
|
+
}): OperationRecord;
|
|
97
|
+
export declare function getOperation(store: OperationStore, borrowerId: string, orderRef: string): OperationRecord | undefined;
|
|
98
|
+
/** What the client should do next for an interrupted operation. */
|
|
99
|
+
export type RecoveryAction = "RETRY_PREPARE" | "QUERY_STATUS" | "DONE";
|
|
100
|
+
/**
|
|
101
|
+
* - `DONE` — terminal, nothing to do.
|
|
102
|
+
* - `RETRY_PREPARE` — no voucher was ever issued; safe to re-prepare with the
|
|
103
|
+
* same idempotency key.
|
|
104
|
+
* - `QUERY_STATUS` — a voucher exists (paymentId known); ask the backend for the
|
|
105
|
+
* authoritative outcome rather than re-submitting.
|
|
106
|
+
*/
|
|
107
|
+
export declare function recoveryAction(op: OperationRecord): RecoveryAction;
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { chmodSync, closeSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, writeFileSync, } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { SignerError } from "./errors.js";
|
|
4
|
+
import { newIdempotencyKey } from "./idempotency.js";
|
|
5
|
+
import { resolveDataDir } from "./terminal.js";
|
|
6
|
+
const BORROWER_ID_PATTERN = /^[A-Za-z0-9._:@-]+$/;
|
|
7
|
+
function assertSafeId(borrowerId) {
|
|
8
|
+
if (!borrowerId || !BORROWER_ID_PATTERN.test(borrowerId)) {
|
|
9
|
+
throw new SignerError("INVALID_BORROWER_ID", "borrower_id must be safe as a path segment (letters, digits, . _ : @ -)");
|
|
10
|
+
}
|
|
11
|
+
return borrowerId;
|
|
12
|
+
}
|
|
13
|
+
/** Process-lifetime store (does not survive restarts — use FileOperationStore for recovery). */
|
|
14
|
+
export class InMemoryOperationStore {
|
|
15
|
+
records = new Map();
|
|
16
|
+
key(borrowerId, orderRef) {
|
|
17
|
+
return `${borrowerId}\u0000${orderRef}`;
|
|
18
|
+
}
|
|
19
|
+
get(borrowerId, orderRef) {
|
|
20
|
+
return this.records.get(this.key(borrowerId, orderRef));
|
|
21
|
+
}
|
|
22
|
+
put(record) {
|
|
23
|
+
this.records.set(this.key(record.borrowerId, record.orderRef), record);
|
|
24
|
+
}
|
|
25
|
+
list(borrowerId) {
|
|
26
|
+
return [...this.records.values()].filter((r) => r.borrowerId === borrowerId);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/** Atomic JSON write (temp → fsync → rename), mode 0600. */
|
|
30
|
+
function atomicWriteJson(path, data) {
|
|
31
|
+
const dir = dirname(path);
|
|
32
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
33
|
+
const tmp = join(dir, `.op.${process.pid}.${Date.now()}.tmp`);
|
|
34
|
+
const fd = openSync(tmp, "w", 0o600);
|
|
35
|
+
try {
|
|
36
|
+
writeFileSync(fd, `${JSON.stringify(data, null, 2)}\n`);
|
|
37
|
+
fsyncSync(fd);
|
|
38
|
+
}
|
|
39
|
+
finally {
|
|
40
|
+
closeSync(fd);
|
|
41
|
+
}
|
|
42
|
+
chmodSync(tmp, 0o600);
|
|
43
|
+
renameSync(tmp, path);
|
|
44
|
+
}
|
|
45
|
+
/** Durable store: one JSON file per borrower, so operations survive a restart. */
|
|
46
|
+
export class FileOperationStore {
|
|
47
|
+
options;
|
|
48
|
+
constructor(options = {}) {
|
|
49
|
+
this.options = options;
|
|
50
|
+
}
|
|
51
|
+
file(borrowerId) {
|
|
52
|
+
return join(resolveDataDir(this.options.dataDir), "operations", `${assertSafeId(borrowerId)}.json`);
|
|
53
|
+
}
|
|
54
|
+
readAll(borrowerId) {
|
|
55
|
+
try {
|
|
56
|
+
return JSON.parse(readFileSync(this.file(borrowerId), "utf8"));
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
if (error.code === "ENOENT") {
|
|
60
|
+
return {};
|
|
61
|
+
}
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
get(borrowerId, orderRef) {
|
|
66
|
+
return this.readAll(borrowerId)[orderRef];
|
|
67
|
+
}
|
|
68
|
+
list(borrowerId) {
|
|
69
|
+
return Object.values(this.readAll(borrowerId));
|
|
70
|
+
}
|
|
71
|
+
put(record) {
|
|
72
|
+
const all = this.readAll(record.borrowerId);
|
|
73
|
+
all[record.orderRef] = record;
|
|
74
|
+
atomicWriteJson(this.file(record.borrowerId), all);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function requireOperation(store, borrowerId, orderRef) {
|
|
78
|
+
const existing = store.get(borrowerId, orderRef);
|
|
79
|
+
if (!existing) {
|
|
80
|
+
throw new SignerError("OPERATION_NOT_FOUND", `no operation for (${borrowerId}, ${orderRef})`);
|
|
81
|
+
}
|
|
82
|
+
return existing;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Starts or resumes an operation. A resume (existing, non-terminal) bumps the
|
|
86
|
+
* attempt counter and keeps the same idempotency key; a terminal operation is
|
|
87
|
+
* returned unchanged (its {@link recoveryAction} is `DONE`).
|
|
88
|
+
*/
|
|
89
|
+
export function beginOperation(args) {
|
|
90
|
+
const now = args.now ?? Date.now();
|
|
91
|
+
const existing = args.store.get(args.borrowerId, args.orderRef);
|
|
92
|
+
if (existing) {
|
|
93
|
+
if (existing.terminal) {
|
|
94
|
+
return existing;
|
|
95
|
+
}
|
|
96
|
+
const resumed = { ...existing, attempts: existing.attempts + 1, updatedAt: now };
|
|
97
|
+
args.store.put(resumed);
|
|
98
|
+
return resumed;
|
|
99
|
+
}
|
|
100
|
+
const record = {
|
|
101
|
+
borrowerId: args.borrowerId,
|
|
102
|
+
orderRef: args.orderRef,
|
|
103
|
+
idempotencyKey: args.idempotencyKey ?? newIdempotencyKey(),
|
|
104
|
+
phase: "STARTED",
|
|
105
|
+
terminal: false,
|
|
106
|
+
attempts: 1,
|
|
107
|
+
createdAt: now,
|
|
108
|
+
updatedAt: now,
|
|
109
|
+
};
|
|
110
|
+
args.store.put(record);
|
|
111
|
+
return record;
|
|
112
|
+
}
|
|
113
|
+
function update(store, borrowerId, orderRef, patch, now) {
|
|
114
|
+
const existing = requireOperation(store, borrowerId, orderRef);
|
|
115
|
+
const next = { ...existing, ...patch, updatedAt: now };
|
|
116
|
+
store.put(next);
|
|
117
|
+
return next;
|
|
118
|
+
}
|
|
119
|
+
/** Records that prepare returned a voucher (paymentId known). */
|
|
120
|
+
export function recordPrepared(args) {
|
|
121
|
+
return update(args.store, args.borrowerId, args.orderRef, {
|
|
122
|
+
phase: "PREPARED",
|
|
123
|
+
paymentId: args.paymentId,
|
|
124
|
+
agentKeyJkt: args.agentKeyJkt,
|
|
125
|
+
voucherDeadline: args.voucherDeadline,
|
|
126
|
+
}, args.now ?? Date.now());
|
|
127
|
+
}
|
|
128
|
+
/** Advances the phase (e.g. SIGNED after signing, SUBMITTED after handing to the merchant). */
|
|
129
|
+
export function advancePhase(args) {
|
|
130
|
+
return update(args.store, args.borrowerId, args.orderRef, { phase: args.phase }, args.now ?? Date.now());
|
|
131
|
+
}
|
|
132
|
+
/** Marks the operation terminal with the authoritative status the host observed. */
|
|
133
|
+
export function resolveOperation(args) {
|
|
134
|
+
return update(args.store, args.borrowerId, args.orderRef, { phase: "RESOLVED", terminal: true, status: args.status }, args.now ?? Date.now());
|
|
135
|
+
}
|
|
136
|
+
export function getOperation(store, borrowerId, orderRef) {
|
|
137
|
+
return store.get(borrowerId, orderRef);
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* - `DONE` — terminal, nothing to do.
|
|
141
|
+
* - `RETRY_PREPARE` — no voucher was ever issued; safe to re-prepare with the
|
|
142
|
+
* same idempotency key.
|
|
143
|
+
* - `QUERY_STATUS` — a voucher exists (paymentId known); ask the backend for the
|
|
144
|
+
* authoritative outcome rather than re-submitting.
|
|
145
|
+
*/
|
|
146
|
+
export function recoveryAction(op) {
|
|
147
|
+
if (op.terminal) {
|
|
148
|
+
return "DONE";
|
|
149
|
+
}
|
|
150
|
+
return op.paymentId ? "QUERY_STATUS" : "RETRY_PREPARE";
|
|
151
|
+
}
|
package/dist/pop.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export interface PopChallengeFields {
|
|
2
|
+
borrowerId: string;
|
|
3
|
+
terminalId: string;
|
|
4
|
+
jkt: string;
|
|
5
|
+
nonce: string;
|
|
6
|
+
/** Unix seconds. Server enforces a ±skew window; keep it current. */
|
|
7
|
+
iat: number;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Untagged JCS challenge bytes (SOHO-74). Deliberately NOT domain-tagged, so it
|
|
11
|
+
* stays byte-compatible with the deployed backend verifier; the voucher preimage
|
|
12
|
+
* carries a tag, which keeps the two signatures non-interchangeable. `iat` is the
|
|
13
|
+
* one numeric field in any signed payload, so it is constrained to a safe integer.
|
|
14
|
+
*/
|
|
15
|
+
export declare function buildPopChallengeMessage(fields: PopChallengeFields): Uint8Array;
|
|
16
|
+
/** Signs the PoP challenge with the agent workload key. */
|
|
17
|
+
export declare function signPoP(fields: PopChallengeFields, privateKeyBase64Url: string): {
|
|
18
|
+
pop_signature: string;
|
|
19
|
+
};
|
package/dist/pop.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { ed25519 } from "@noble/curves/ed25519";
|
|
2
|
+
import { fromBase64Url, toBase64Url, utf8Bytes } from "./encoding.js";
|
|
3
|
+
import { SignerError } from "./errors.js";
|
|
4
|
+
import { jcs } from "./jcs.js";
|
|
5
|
+
/**
|
|
6
|
+
* Untagged JCS challenge bytes (SOHO-74). Deliberately NOT domain-tagged, so it
|
|
7
|
+
* stays byte-compatible with the deployed backend verifier; the voucher preimage
|
|
8
|
+
* carries a tag, which keeps the two signatures non-interchangeable. `iat` is the
|
|
9
|
+
* one numeric field in any signed payload, so it is constrained to a safe integer.
|
|
10
|
+
*/
|
|
11
|
+
export function buildPopChallengeMessage(fields) {
|
|
12
|
+
if (!Number.isSafeInteger(fields.iat)) {
|
|
13
|
+
throw new SignerError("POP_IAT_NOT_INTEGER", "pop iat must be a safe integer (unix seconds)");
|
|
14
|
+
}
|
|
15
|
+
return utf8Bytes(jcs({
|
|
16
|
+
borrowerId: fields.borrowerId,
|
|
17
|
+
terminalId: fields.terminalId,
|
|
18
|
+
jkt: fields.jkt,
|
|
19
|
+
nonce: fields.nonce,
|
|
20
|
+
iat: fields.iat,
|
|
21
|
+
}));
|
|
22
|
+
}
|
|
23
|
+
/** Signs the PoP challenge with the agent workload key. */
|
|
24
|
+
export function signPoP(fields, privateKeyBase64Url) {
|
|
25
|
+
const signature = ed25519.sign(buildPopChallengeMessage(fields), fromBase64Url(privateKeyBase64Url));
|
|
26
|
+
return { pop_signature: toBase64Url(signature) };
|
|
27
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { OperationRecord, OperationStore } from "./operations.js";
|
|
2
|
+
/**
|
|
3
|
+
* S10 — key-rotation drain gate.
|
|
4
|
+
*
|
|
5
|
+
* A voucher signed under the old workload key but not yet captured will fail at
|
|
6
|
+
* capture once the key is rotated out (the backend verifies against the live key
|
|
7
|
+
* at capture; SOHO-254 supersedes the old key atomically). So a rotation must not
|
|
8
|
+
* be *activated* while such vouchers are still in flight. This assesses, from the
|
|
9
|
+
* operation ledger (S9), whether rotation is safe and, if not, which operations
|
|
10
|
+
* block it.
|
|
11
|
+
*
|
|
12
|
+
* An operation blocks when it is non-terminal, has produced a voucher
|
|
13
|
+
* (`paymentId` known), is signed under the key being rotated out, and its voucher
|
|
14
|
+
* deadline has not elapsed. A `STARTED` operation with no voucher does not block
|
|
15
|
+
* (it simply re-prepares under the new key), and an elapsed-deadline voucher can
|
|
16
|
+
* no longer be captured, so it is surfaced as expired rather than blocking.
|
|
17
|
+
*/
|
|
18
|
+
export interface RotationDrainAssessment {
|
|
19
|
+
/** True when nothing is in flight that could capture under the rotating key. */
|
|
20
|
+
ready: boolean;
|
|
21
|
+
/** Non-terminal, unexpired vouchers that must resolve (or expire) before rotating. */
|
|
22
|
+
blocking: OperationRecord[];
|
|
23
|
+
/** Non-terminal vouchers whose deadline has passed — safe, reported for visibility. */
|
|
24
|
+
expired: OperationRecord[];
|
|
25
|
+
}
|
|
26
|
+
export interface AssessRotationDrainArgs {
|
|
27
|
+
operations: OperationRecord[];
|
|
28
|
+
/** epoch ms; defaults to now. */
|
|
29
|
+
now?: number;
|
|
30
|
+
/** When set, only operations signed under this jkt are considered (the key being rotated out). */
|
|
31
|
+
jkt?: string;
|
|
32
|
+
}
|
|
33
|
+
/** Assesses rotation safety from a list of operation records. */
|
|
34
|
+
export declare function assessRotationDrain(args: AssessRotationDrainArgs): RotationDrainAssessment;
|
|
35
|
+
/** Convenience: assess drain for one borrower straight from an operation store. */
|
|
36
|
+
export declare function assessRotationDrainForBorrower(args: {
|
|
37
|
+
store: OperationStore;
|
|
38
|
+
borrowerId: string;
|
|
39
|
+
now?: number;
|
|
40
|
+
jkt?: string;
|
|
41
|
+
}): RotationDrainAssessment;
|
package/dist/rotation.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** Assesses rotation safety from a list of operation records. */
|
|
2
|
+
export function assessRotationDrain(args) {
|
|
3
|
+
const nowSeconds = Math.floor((args.now ?? Date.now()) / 1000);
|
|
4
|
+
const blocking = [];
|
|
5
|
+
const expired = [];
|
|
6
|
+
for (const op of args.operations) {
|
|
7
|
+
if (op.terminal) {
|
|
8
|
+
continue;
|
|
9
|
+
}
|
|
10
|
+
// Only a voucher (paymentId issued) can be captured under the old key.
|
|
11
|
+
if (!op.paymentId) {
|
|
12
|
+
continue;
|
|
13
|
+
}
|
|
14
|
+
// Scope to the key being rotated out, when known on both sides.
|
|
15
|
+
if (args.jkt && op.agentKeyJkt && op.agentKeyJkt !== args.jkt) {
|
|
16
|
+
continue;
|
|
17
|
+
}
|
|
18
|
+
if (op.voucherDeadline !== undefined && Number(op.voucherDeadline) < nowSeconds) {
|
|
19
|
+
expired.push(op);
|
|
20
|
+
continue;
|
|
21
|
+
}
|
|
22
|
+
blocking.push(op);
|
|
23
|
+
}
|
|
24
|
+
return { ready: blocking.length === 0, blocking, expired };
|
|
25
|
+
}
|
|
26
|
+
/** Convenience: assess drain for one borrower straight from an operation store. */
|
|
27
|
+
export function assessRotationDrainForBorrower(args) {
|
|
28
|
+
return assessRotationDrain({
|
|
29
|
+
operations: args.store.list(args.borrowerId),
|
|
30
|
+
now: args.now,
|
|
31
|
+
jkt: args.jkt,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { type Ed25519PublicJwk } from "./keys.js";
|
|
2
|
+
/** On-disk shape of a persisted agent workload key. */
|
|
3
|
+
export interface StoredWorkloadKey {
|
|
4
|
+
private_key_base64url: string;
|
|
5
|
+
public_jwk: Ed25519PublicJwk;
|
|
6
|
+
jkt: string;
|
|
7
|
+
terminal_id: string;
|
|
8
|
+
borrower_id: string;
|
|
9
|
+
}
|
|
10
|
+
export interface WorkloadKeyStoreOptions {
|
|
11
|
+
dataDir?: string;
|
|
12
|
+
}
|
|
13
|
+
/** Reads and parses a key file at an explicit path, refusing group/world-readable files. */
|
|
14
|
+
export declare function loadKeyFile(path: string): unknown;
|
|
15
|
+
/**
|
|
16
|
+
* Loads the stored key for a borrower, or `undefined` if none exists or it does
|
|
17
|
+
* not match (borrower, and optionally jkt). Refuses to load a world/group
|
|
18
|
+
* readable file. Throws on unexpected IO errors and on corrupt JSON.
|
|
19
|
+
*/
|
|
20
|
+
export declare function loadWorkloadKey(args: {
|
|
21
|
+
borrowerId: string;
|
|
22
|
+
expectedJkt?: string;
|
|
23
|
+
dataDir?: string;
|
|
24
|
+
}): StoredWorkloadKey | undefined;
|
|
25
|
+
/** Atomically writes a StoredWorkloadKey at an explicit path (0600, temp→fsync→rename). */
|
|
26
|
+
export declare function writeSecretFileAtPath(path: string, key: StoredWorkloadKey): void;
|
|
27
|
+
/** Atomically persists a workload key at 0600 (temp file → fsync → rename). */
|
|
28
|
+
export declare function saveWorkloadKey(key: StoredWorkloadKey, options?: WorkloadKeyStoreOptions): void;
|
|
29
|
+
/**
|
|
30
|
+
* Returns the borrower's existing key, or generates and persists a fresh one.
|
|
31
|
+
* Because the path is borrower-scoped, this never overwrites another borrower's
|
|
32
|
+
* key on the same host.
|
|
33
|
+
*/
|
|
34
|
+
export declare function loadOrCreateWorkloadKey(args: {
|
|
35
|
+
borrowerId: string;
|
|
36
|
+
terminalId: string;
|
|
37
|
+
dataDir?: string;
|
|
38
|
+
}): StoredWorkloadKey;
|
package/dist/storage.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { chmodSync, closeSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, statSync, writeFileSync, } from "node:fs";
|
|
2
|
+
import { platform } from "node:os";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { SignerError } from "./errors.js";
|
|
5
|
+
import { generateWorkloadKey } from "./keys.js";
|
|
6
|
+
import { resolveDataDir } from "./terminal.js";
|
|
7
|
+
/** borrower_id must be safe as a single path segment (no separators / traversal). */
|
|
8
|
+
const BORROWER_ID_PATTERN = /^[A-Za-z0-9._:@-]+$/;
|
|
9
|
+
function assertSafeBorrowerId(borrowerId) {
|
|
10
|
+
const trimmed = borrowerId.trim();
|
|
11
|
+
if (!trimmed || !BORROWER_ID_PATTERN.test(trimmed)) {
|
|
12
|
+
throw new SignerError("INVALID_BORROWER_ID", "borrower_id must contain only letters, digits, and . _ : @ - (safe as a path segment)");
|
|
13
|
+
}
|
|
14
|
+
return trimmed;
|
|
15
|
+
}
|
|
16
|
+
/** Per-borrower secret path — keying by borrower prevents cross-borrower overwrite. */
|
|
17
|
+
function secretPath(borrowerId, dataDir) {
|
|
18
|
+
return join(resolveDataDir(dataDir), "agent-workload", assertSafeBorrowerId(borrowerId), "secret.json");
|
|
19
|
+
}
|
|
20
|
+
function assertSecurePermissions(path) {
|
|
21
|
+
if (platform() === "win32") {
|
|
22
|
+
// POSIX mode bits are not meaningful on Windows; ACLs govern access there.
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
const mode = statSync(path).mode & 0o777;
|
|
26
|
+
if (mode & 0o077) {
|
|
27
|
+
throw new SignerError("INSECURE_KEY_PERMISSIONS", `${path} is group/world-accessible (mode ${mode.toString(8)}); refusing to load`);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/** Reads and parses a key file at an explicit path, refusing group/world-readable files. */
|
|
31
|
+
export function loadKeyFile(path) {
|
|
32
|
+
// Permissions are checked before the secret is read so a loosened file is never parsed.
|
|
33
|
+
assertSecurePermissions(path);
|
|
34
|
+
const raw = readFileSync(path, "utf8");
|
|
35
|
+
try {
|
|
36
|
+
return JSON.parse(raw);
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
throw new SignerError("STORED_KEY_CORRUPT", `${path} is not valid JSON`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Loads the stored key for a borrower, or `undefined` if none exists or it does
|
|
44
|
+
* not match (borrower, and optionally jkt). Refuses to load a world/group
|
|
45
|
+
* readable file. Throws on unexpected IO errors and on corrupt JSON.
|
|
46
|
+
*/
|
|
47
|
+
export function loadWorkloadKey(args) {
|
|
48
|
+
const path = secretPath(args.borrowerId, args.dataDir);
|
|
49
|
+
let raw;
|
|
50
|
+
try {
|
|
51
|
+
raw = readFileSync(path, "utf8");
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
if (error.code === "ENOENT") {
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
assertSecurePermissions(path);
|
|
60
|
+
let parsed;
|
|
61
|
+
try {
|
|
62
|
+
parsed = JSON.parse(raw);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
throw new SignerError("STORED_KEY_CORRUPT", `${path} is not valid JSON`);
|
|
66
|
+
}
|
|
67
|
+
if (parsed.borrower_id !== assertSafeBorrowerId(args.borrowerId)) {
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
if (args.expectedJkt && parsed.jkt !== args.expectedJkt) {
|
|
71
|
+
return undefined;
|
|
72
|
+
}
|
|
73
|
+
return parsed;
|
|
74
|
+
}
|
|
75
|
+
/** Atomically writes a StoredWorkloadKey at an explicit path (0600, temp→fsync→rename). */
|
|
76
|
+
export function writeSecretFileAtPath(path, key) {
|
|
77
|
+
const dir = dirname(path);
|
|
78
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
79
|
+
const tmp = join(dir, `.secret.${process.pid}.${Date.now()}.tmp`);
|
|
80
|
+
const fd = openSync(tmp, "w", 0o600);
|
|
81
|
+
try {
|
|
82
|
+
writeFileSync(fd, `${JSON.stringify(key, null, 2)}\n`);
|
|
83
|
+
fsyncSync(fd);
|
|
84
|
+
}
|
|
85
|
+
finally {
|
|
86
|
+
closeSync(fd);
|
|
87
|
+
}
|
|
88
|
+
chmodSync(tmp, 0o600);
|
|
89
|
+
renameSync(tmp, path);
|
|
90
|
+
}
|
|
91
|
+
/** Atomically persists a workload key at 0600 (temp file → fsync → rename). */
|
|
92
|
+
export function saveWorkloadKey(key, options = {}) {
|
|
93
|
+
assertSafeBorrowerId(key.borrower_id);
|
|
94
|
+
writeSecretFileAtPath(secretPath(key.borrower_id, options.dataDir), key);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Returns the borrower's existing key, or generates and persists a fresh one.
|
|
98
|
+
* Because the path is borrower-scoped, this never overwrites another borrower's
|
|
99
|
+
* key on the same host.
|
|
100
|
+
*/
|
|
101
|
+
export function loadOrCreateWorkloadKey(args) {
|
|
102
|
+
const existing = loadWorkloadKey({ borrowerId: args.borrowerId, dataDir: args.dataDir });
|
|
103
|
+
if (existing) {
|
|
104
|
+
return existing;
|
|
105
|
+
}
|
|
106
|
+
const keypair = generateWorkloadKey();
|
|
107
|
+
const stored = {
|
|
108
|
+
private_key_base64url: keypair.privateKeyBase64Url,
|
|
109
|
+
public_jwk: keypair.publicJwk,
|
|
110
|
+
jkt: keypair.jkt,
|
|
111
|
+
terminal_id: args.terminalId,
|
|
112
|
+
borrower_id: assertSafeBorrowerId(args.borrowerId),
|
|
113
|
+
};
|
|
114
|
+
saveWorkloadKey(stored, { dataDir: args.dataDir });
|
|
115
|
+
return stored;
|
|
116
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** Backend `RegisterBorrowerDto.terminal_id` charset / length. */
|
|
2
|
+
export declare const TERMINAL_ID_PATTERN: RegExp;
|
|
3
|
+
export declare const TERMINAL_ID_MAX_LENGTH = 128;
|
|
4
|
+
/** Validates a terminal id against the backend's charset/length rules. */
|
|
5
|
+
export declare function assertValidTerminalId(terminalId: string): string;
|
|
6
|
+
/** The SDK data directory: explicit → `SOHO_DATA_DIR` → `~/.sohopay`. */
|
|
7
|
+
export declare function resolveDataDir(dataDir?: string): string;
|
|
8
|
+
export interface ResolveTerminalIdOptions {
|
|
9
|
+
/** Explicit id (e.g. two clients sharing one remote MCP); validated and returned as-is. */
|
|
10
|
+
explicit?: string;
|
|
11
|
+
dataDir?: string;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Resolves a stable per-host `terminal_id`. Precedence:
|
|
15
|
+
* 1. explicit argument, 2. `SOHO_TERMINAL_ID`, 3. persisted `{hostname}:{uuid}`
|
|
16
|
+
* under the data dir (minted + persisted on first use).
|
|
17
|
+
*/
|
|
18
|
+
export declare function resolveTerminalId(options?: ResolveTerminalIdOptions): string;
|
|
19
|
+
/**
|
|
20
|
+
* Harnesses that may hold their own terminal id. A fixed list, so the slug is a safe
|
|
21
|
+
* single path segment and no caller-chosen string ever names a directory.
|
|
22
|
+
*/
|
|
23
|
+
export declare const HARNESSES: readonly ["antigravity", "claude-code", "codex", "cursor", "hermes"];
|
|
24
|
+
export type Harness = (typeof HARNESSES)[number];
|
|
25
|
+
/**
|
|
26
|
+
* Per-harness terminal id: `{harness}:{uuid}` persisted at `<dataDir>/<harness>/terminal_id`
|
|
27
|
+
* (dir 0700, file 0600), minted on first use and stable afterwards. Unlike
|
|
28
|
+
* {@link resolveTerminalId} it ignores `SOHO_TERMINAL_ID`: a host-wide override would
|
|
29
|
+
* collapse every harness back onto one terminal.
|
|
30
|
+
*/
|
|
31
|
+
export declare function resolveHarnessTerminalId(harness: string, dataDir?: string): string;
|