@forgezero/runtime 0.1.5 → 0.1.7

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.
@@ -0,0 +1,111 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined")
5
+ return require.apply(this, arguments);
6
+ throw Error('Dynamic require of "' + x + '" is not supported');
7
+ });
8
+
9
+ // src/passkey-hybrid.ts
10
+ import { ml_dsa65 } from "@noble/post-quantum/ml-dsa.js";
11
+ import { hkdf } from "@noble/hashes/hkdf.js";
12
+ import { sha256 } from "@noble/hashes/sha2.js";
13
+ var PASSKEY_HYBRID_VERSION = 1;
14
+ var PASSKEY_HYBRID_SUITE = "webauthn+prf-ml-dsa-65";
15
+ var PASSKEY_PRF_SALT = new TextEncoder().encode("forgezero:passkey:hybrid-auth:prf:v1");
16
+ var utf8 = (value) => new TextEncoder().encode(value);
17
+ var b64 = (bytes) => {
18
+ let binary = "";
19
+ for (const byte of bytes)
20
+ binary += String.fromCharCode(byte);
21
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
22
+ };
23
+ var un64 = (value) => {
24
+ if (!/^[A-Za-z0-9_-]+$/.test(value))
25
+ throw new Error("passkey-hybrid: non-canonical base64url");
26
+ const normal = value.replace(/-/g, "+").replace(/_/g, "/");
27
+ const binary = atob(normal.padEnd(Math.ceil(normal.length / 4) * 4, "="));
28
+ return Uint8Array.from(binary, (character) => character.charCodeAt(0));
29
+ };
30
+ function field(value) {
31
+ if (value.length > 2048 || /[\0\r\n]/.test(value)) {
32
+ throw new Error("passkey-hybrid: invalid binding field");
33
+ }
34
+ return `${utf8(value).length}:${value}`;
35
+ }
36
+ function passkeyHybridMessage(binding, credentialId) {
37
+ if (binding.version !== PASSKEY_HYBRID_VERSION || binding.suite !== PASSKEY_HYBRID_SUITE) {
38
+ throw new Error("passkey-hybrid: unsupported protocol");
39
+ }
40
+ if (!/^[A-Za-z0-9_-]{16,1024}$/.test(credentialId)) {
41
+ throw new Error("passkey-hybrid: invalid credential id");
42
+ }
43
+ return utf8([
44
+ "forgezero-passkey-hybrid-v1",
45
+ binding.suite,
46
+ binding.purpose,
47
+ binding.rpId,
48
+ binding.origin,
49
+ binding.challenge,
50
+ credentialId,
51
+ binding.userKey,
52
+ binding.sessionKey,
53
+ binding.actionRequestKey
54
+ ].map(field).join(`
55
+ `));
56
+ }
57
+ function keys(prfOutput, credentialId) {
58
+ if (prfOutput.length !== 32)
59
+ throw new Error("passkey-hybrid: PRF output must be exactly 32 bytes");
60
+ const seed = hkdf(sha256, prfOutput, utf8("forgezero:passkey:hybrid-auth:ml-dsa-65:v1"), utf8(`credential:${credentialId.length}:${credentialId}`), 32);
61
+ try {
62
+ const pair = ml_dsa65.keygen(seed);
63
+ return {
64
+ publicKey: Uint8Array.from(pair.publicKey),
65
+ secretKey: Uint8Array.from(pair.secretKey)
66
+ };
67
+ } finally {
68
+ seed.fill(0);
69
+ }
70
+ }
71
+ function createPasskeyHybridProof(prfOutput, binding, credentialId) {
72
+ const pair = keys(prfOutput, credentialId);
73
+ try {
74
+ return {
75
+ version: PASSKEY_HYBRID_VERSION,
76
+ suite: PASSKEY_HYBRID_SUITE,
77
+ credentialId,
78
+ publicKey: b64(pair.publicKey),
79
+ signature: b64(ml_dsa65.sign(passkeyHybridMessage(binding, credentialId), pair.secretKey))
80
+ };
81
+ } finally {
82
+ pair.secretKey.fill(0);
83
+ }
84
+ }
85
+ function verifyPasskeyHybridProof(args) {
86
+ try {
87
+ if (args.proof.version !== PASSKEY_HYBRID_VERSION || args.proof.suite !== PASSKEY_HYBRID_SUITE || !Object.keys(args.proof).every((key) => ["version", "suite", "credentialId", "signature"].includes(key)))
88
+ return false;
89
+ const publicKey = un64(args.publicKey);
90
+ const signature = un64(args.proof.signature);
91
+ if (publicKey.length !== ml_dsa65.lengths.publicKey || signature.length !== ml_dsa65.lengths.signature)
92
+ return false;
93
+ if (b64(publicKey) !== args.publicKey || b64(signature) !== args.proof.signature)
94
+ return false;
95
+ return ml_dsa65.verify(signature, passkeyHybridMessage(args.binding, args.proof.credentialId), publicKey);
96
+ } catch {
97
+ return false;
98
+ }
99
+ }
100
+ var PASSKEY_ML_DSA_PUBLIC_KEY_BYTES = ml_dsa65.lengths.publicKey;
101
+ var PASSKEY_ML_DSA_SIGNATURE_BYTES = ml_dsa65.lengths.signature;
102
+ export {
103
+ verifyPasskeyHybridProof,
104
+ passkeyHybridMessage,
105
+ createPasskeyHybridProof,
106
+ PASSKEY_PRF_SALT,
107
+ PASSKEY_ML_DSA_SIGNATURE_BYTES,
108
+ PASSKEY_ML_DSA_PUBLIC_KEY_BYTES,
109
+ PASSKEY_HYBRID_VERSION,
110
+ PASSKEY_HYBRID_SUITE
111
+ };
@@ -0,0 +1,68 @@
1
+ export declare const REALTIME_MAX_EVENTS = 100;
2
+ export declare const REALTIME_MAX_EVENT_BYTES: number;
3
+ export declare const REALTIME_MAX_BATCH_BYTES: number;
4
+ export declare const REALTIME_MAX_SOCKETS_PER_SHARD = 1000;
5
+ export declare const REALTIME_MAX_SHARDS_PER_TOPIC = 1024;
6
+ export interface RealtimeEvent {
7
+ id: string;
8
+ type: string;
9
+ payload: unknown;
10
+ }
11
+ export type RealtimePrincipalKind = 'user' | 'node' | 'api-key' | 'service' | 'header';
12
+ export type RealtimeAudience = Readonly<{
13
+ kind: 'public';
14
+ }> | Readonly<{
15
+ kind: 'principal';
16
+ realmId: string;
17
+ principalKind: RealtimePrincipalKind;
18
+ principalKey: string;
19
+ capability: string;
20
+ }> | Readonly<{
21
+ kind: 'project';
22
+ realmId: string;
23
+ projectKey: string;
24
+ capability: string;
25
+ }> | Readonly<{
26
+ kind: 'group';
27
+ realmId: string;
28
+ group: string;
29
+ capability: string;
30
+ }>;
31
+ export interface RealtimeBatch {
32
+ version: 2;
33
+ batchId: string;
34
+ topic: string;
35
+ audience: RealtimeAudience;
36
+ publishedAtMs: number;
37
+ events: RealtimeEvent[];
38
+ }
39
+ export declare function validateRealtimeAudience(input: unknown): RealtimeAudience;
40
+ export declare function validateRealtimeBatch(input: unknown): RealtimeBatch;
41
+ export declare const realtimeBatchBytes: (input: unknown) => string;
42
+ export interface RealtimeSubscriptionTicket {
43
+ version: 2;
44
+ topic: string;
45
+ principal: Readonly<{
46
+ kind: RealtimePrincipalKind;
47
+ key: string;
48
+ }>;
49
+ realmId: string;
50
+ projectKeys: readonly string[];
51
+ groups: readonly string[];
52
+ capabilities: readonly string[];
53
+ expiresAtSec: number;
54
+ nonce: string;
55
+ }
56
+ export declare function validateRealtimeSubscriptionTicket(input: unknown, nowSec?: number): RealtimeSubscriptionTicket;
57
+ /**
58
+ * The edge has no database authority. It may deliver only when the short-lived,
59
+ * API-issued connection capability contains every coordinate named by the
60
+ * event audience. Topic equality is handled by the shard; it is not an access
61
+ * decision.
62
+ */
63
+ export declare function canReceiveRealtimeAudience(ticket: RealtimeSubscriptionTicket, audience: RealtimeAudience): boolean;
64
+ export declare const realtimeShardKey: (topic: string, shard: number) => string;
65
+ export declare function realtimeHmac(secret: string, message: string): Promise<string>;
66
+ export declare function verifyRealtimeHmac(secret: string, message: string, signature: string): Promise<boolean>;
67
+ export declare function issueRealtimeSubscriptionTicket(secret: string, ticket: RealtimeSubscriptionTicket, nowSec?: number): Promise<string>;
68
+ export declare function verifyRealtimeSubscriptionToken(secret: string, token: string, nowSec?: number): Promise<RealtimeSubscriptionTicket | null>;
@@ -0,0 +1,184 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined")
5
+ return require.apply(this, arguments);
6
+ throw Error('Dynamic require of "' + x + '" is not supported');
7
+ });
8
+
9
+ // src/realtime.ts
10
+ var REALTIME_MAX_EVENTS = 100;
11
+ var REALTIME_MAX_EVENT_BYTES = 64 * 1024;
12
+ var REALTIME_MAX_BATCH_BYTES = 512 * 1024;
13
+ var REALTIME_MAX_SOCKETS_PER_SHARD = 1000;
14
+ var REALTIME_MAX_SHARDS_PER_TOPIC = 1024;
15
+ var ATOM = /^[A-Za-z0-9][A-Za-z0-9_.:@/-]{0,255}$/;
16
+ var PRINCIPAL_KINDS = new Set(["user", "node", "api-key", "service", "header"]);
17
+ var atom = (value) => typeof value === "string" && ATOM.test(value);
18
+ function validateRealtimeAudience(input) {
19
+ if (!input || typeof input !== "object" || Array.isArray(input))
20
+ throw new Error("Realtime audience must be an object.");
21
+ const row = input;
22
+ if (row.kind === "public") {
23
+ if (Object.keys(row).length !== 1)
24
+ throw new Error("Public realtime audience has no additional coordinates.");
25
+ return { kind: "public" };
26
+ }
27
+ if (!atom(row.realmId) || !atom(row.capability))
28
+ throw new Error("Realtime audience scope is invalid.");
29
+ if (row.kind === "principal" && PRINCIPAL_KINDS.has(row.principalKind) && atom(row.principalKey)) {
30
+ return {
31
+ kind: "principal",
32
+ realmId: row.realmId,
33
+ principalKind: row.principalKind,
34
+ principalKey: row.principalKey,
35
+ capability: row.capability
36
+ };
37
+ }
38
+ if (row.kind === "project" && atom(row.projectKey)) {
39
+ return { kind: "project", realmId: row.realmId, projectKey: row.projectKey, capability: row.capability };
40
+ }
41
+ if (row.kind === "group" && atom(row.group)) {
42
+ return { kind: "group", realmId: row.realmId, group: row.group, capability: row.capability };
43
+ }
44
+ throw new Error("Realtime audience coordinates are invalid.");
45
+ }
46
+ function validateRealtimeBatch(input) {
47
+ if (!input || typeof input !== "object" || Array.isArray(input))
48
+ throw new Error("Realtime batch must be an object.");
49
+ const row = input;
50
+ if (row.version !== 2 || !ATOM.test(row.batchId ?? "") || !ATOM.test(row.topic ?? "") || !Number.isSafeInteger(row.publishedAtMs) || row.publishedAtMs < 0 || !Array.isArray(row.events) || row.events.length < 1 || row.events.length > REALTIME_MAX_EVENTS)
51
+ throw new Error("Realtime batch coordinates are invalid.");
52
+ const audience = validateRealtimeAudience(row.audience);
53
+ const events = row.events.map((event) => {
54
+ if (!event || typeof event !== "object" || Array.isArray(event))
55
+ throw new Error("Realtime event must be an object.");
56
+ const value = event;
57
+ if (!ATOM.test(value.id ?? "") || !ATOM.test(value.type ?? ""))
58
+ throw new Error("Realtime event id/type is invalid.");
59
+ const encoded = JSON.stringify(value.payload);
60
+ if (encoded === undefined || new TextEncoder().encode(encoded).byteLength > REALTIME_MAX_EVENT_BYTES) {
61
+ throw new Error("Realtime event payload is too large or not JSON serializable.");
62
+ }
63
+ return { id: value.id, type: value.type, payload: value.payload };
64
+ });
65
+ if (new Set(events.map(({ id }) => id)).size !== events.length)
66
+ throw new Error("Realtime event ids must be unique in a batch.");
67
+ const batch = {
68
+ version: 2,
69
+ batchId: row.batchId,
70
+ topic: row.topic,
71
+ audience,
72
+ publishedAtMs: row.publishedAtMs,
73
+ events
74
+ };
75
+ if (new TextEncoder().encode(JSON.stringify(batch)).byteLength > REALTIME_MAX_BATCH_BYTES) {
76
+ throw new Error("Realtime batch is too large.");
77
+ }
78
+ return batch;
79
+ }
80
+ var realtimeBatchBytes = (input) => JSON.stringify(validateRealtimeBatch(input));
81
+ function boundedUniqueAtoms(value, maximum, label) {
82
+ if (!Array.isArray(value) || value.length > maximum || value.some((item) => !atom(item)) || new Set(value).size !== value.length)
83
+ throw new Error(`Realtime ticket ${label} are invalid.`);
84
+ return [...value];
85
+ }
86
+ function validateRealtimeSubscriptionTicket(input, nowSec = Math.floor(Date.now() / 1000)) {
87
+ if (!input || typeof input !== "object" || Array.isArray(input))
88
+ throw new Error("Realtime ticket must be an object.");
89
+ const row = input;
90
+ if (row.version !== 2 || !atom(row.topic) || !atom(row.realmId) || !atom(row.nonce) || !row.principal || !PRINCIPAL_KINDS.has(row.principal.kind) || !atom(row.principal.key) || !Number.isSafeInteger(row.expiresAtSec) || row.expiresAtSec <= nowSec || row.expiresAtSec > nowSec + 300)
91
+ throw new Error("Realtime ticket is invalid or expired.");
92
+ return {
93
+ version: 2,
94
+ topic: row.topic,
95
+ principal: { kind: row.principal.kind, key: row.principal.key },
96
+ realmId: row.realmId,
97
+ projectKeys: boundedUniqueAtoms(row.projectKeys, 32, "project keys"),
98
+ groups: boundedUniqueAtoms(row.groups, 16, "groups"),
99
+ capabilities: boundedUniqueAtoms(row.capabilities, 64, "capabilities"),
100
+ expiresAtSec: row.expiresAtSec,
101
+ nonce: row.nonce
102
+ };
103
+ }
104
+ function canReceiveRealtimeAudience(ticket, audience) {
105
+ if (audience.kind === "public")
106
+ return true;
107
+ if (ticket.realmId !== audience.realmId || !ticket.capabilities.includes(audience.capability))
108
+ return false;
109
+ if (audience.kind === "principal") {
110
+ return ticket.principal.kind === audience.principalKind && ticket.principal.key === audience.principalKey;
111
+ }
112
+ if (audience.kind === "project")
113
+ return ticket.projectKeys.includes(audience.projectKey);
114
+ return ticket.groups.includes(audience.group);
115
+ }
116
+ var realtimeShardKey = (topic, shard) => {
117
+ if (!ATOM.test(topic) || !Number.isSafeInteger(shard) || shard < 0 || shard >= REALTIME_MAX_SHARDS_PER_TOPIC) {
118
+ throw new Error("Realtime shard coordinates are invalid.");
119
+ }
120
+ return `rt:${topic}:${shard.toString().padStart(4, "0")}`;
121
+ };
122
+ var bytesToHex = (bytes) => [...bytes].map((value) => value.toString(16).padStart(2, "0")).join("");
123
+ var timingEqual = (left, right) => {
124
+ if (left.length !== right.length)
125
+ return false;
126
+ let difference = 0;
127
+ for (let index = 0;index < left.length; index += 1)
128
+ difference |= left.charCodeAt(index) ^ right.charCodeAt(index);
129
+ return difference === 0;
130
+ };
131
+ async function realtimeHmac(secret, message) {
132
+ if (new TextEncoder().encode(secret).byteLength < 32)
133
+ throw new Error("Realtime secret must contain at least 32 bytes.");
134
+ const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
135
+ return bytesToHex(new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(message))));
136
+ }
137
+ async function verifyRealtimeHmac(secret, message, signature) {
138
+ return /^[a-f0-9]{64}$/.test(signature) && timingEqual(await realtimeHmac(secret, message), signature);
139
+ }
140
+ var base64url = (value) => {
141
+ const bytes = new TextEncoder().encode(value);
142
+ let binary = "";
143
+ for (const byte of bytes)
144
+ binary += String.fromCharCode(byte);
145
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
146
+ };
147
+ var fromBase64url = (value) => {
148
+ const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
149
+ const binary = atob(normalized + "=".repeat((4 - normalized.length % 4) % 4));
150
+ return new TextDecoder().decode(Uint8Array.from(binary, (char) => char.charCodeAt(0)));
151
+ };
152
+ async function issueRealtimeSubscriptionTicket(secret, ticket, nowSec = Math.floor(Date.now() / 1000)) {
153
+ const body = base64url(JSON.stringify(validateRealtimeSubscriptionTicket(ticket, nowSec)));
154
+ return `${body}.${await realtimeHmac(secret, `ticket
155
+ ${body}`)}`;
156
+ }
157
+ async function verifyRealtimeSubscriptionToken(secret, token, nowSec = Math.floor(Date.now() / 1000)) {
158
+ const [body, signature, ...extra] = token.split(".");
159
+ if (!body || !signature || extra.length || !await verifyRealtimeHmac(secret, `ticket
160
+ ${body}`, signature))
161
+ return null;
162
+ try {
163
+ return validateRealtimeSubscriptionTicket(JSON.parse(fromBase64url(body)), nowSec);
164
+ } catch {
165
+ return null;
166
+ }
167
+ }
168
+ export {
169
+ verifyRealtimeSubscriptionToken,
170
+ verifyRealtimeHmac,
171
+ validateRealtimeSubscriptionTicket,
172
+ validateRealtimeBatch,
173
+ validateRealtimeAudience,
174
+ realtimeShardKey,
175
+ realtimeHmac,
176
+ realtimeBatchBytes,
177
+ issueRealtimeSubscriptionTicket,
178
+ canReceiveRealtimeAudience,
179
+ REALTIME_MAX_SOCKETS_PER_SHARD,
180
+ REALTIME_MAX_SHARDS_PER_TOPIC,
181
+ REALTIME_MAX_EVENT_BYTES,
182
+ REALTIME_MAX_EVENTS,
183
+ REALTIME_MAX_BATCH_BYTES
184
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@forgezero/runtime",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
4
4
  "type": "module",
5
5
  "publishConfig": {
6
6
  "access": "public",
@@ -47,6 +47,10 @@
47
47
  "types": "./dist/query.d.ts",
48
48
  "default": "./dist/query.js"
49
49
  },
50
+ "./realtime": {
51
+ "types": "./dist/realtime.d.ts",
52
+ "default": "./dist/realtime.js"
53
+ },
50
54
  "./calendar": {
51
55
  "types": "./dist/calendar.d.ts",
52
56
  "default": "./dist/calendar.js"
@@ -55,6 +59,10 @@
55
59
  "types": "./dist/identity.d.ts",
56
60
  "default": "./dist/identity.js"
57
61
  },
62
+ "./passkey-hybrid": {
63
+ "types": "./dist/passkey-hybrid.d.ts",
64
+ "default": "./dist/passkey-hybrid.js"
65
+ },
58
66
  "./totp": {
59
67
  "types": "./dist/totp.d.ts",
60
68
  "default": "./dist/totp.js"
@@ -155,10 +163,6 @@
155
163
  "types": "./dist/phrase.d.ts",
156
164
  "default": "./dist/phrase.js"
157
165
  },
158
- "./ssh-agent": {
159
- "types": "./dist/ssh-agent.d.ts",
160
- "default": "./dist/ssh-agent.js"
161
- },
162
166
  "./slip10": {
163
167
  "types": "./dist/slip10.d.ts",
164
168
  "default": "./dist/slip10.js"
@@ -183,11 +187,11 @@
183
187
  "scripts": {
184
188
  "check": "tsc --noEmit",
185
189
  "prebuild": "rm -rf dist",
186
- "build": "bun build src/query.ts src/jobs.ts src/queue.ts src/outbox.ts src/audit.ts src/backup.ts src/notify.ts src/notify-templates.ts src/calendar.ts src/compliance.ts src/pipeline.ts src/totp.ts src/otpauth.ts src/identity.ts src/slip10.ts src/openssh.ts src/ssh-cert.ts src/importers.ts src/snp.ts src/passkey.ts src/custody-crypto.ts src/custody-share.ts src/phrase.ts src/ssh-agent.ts src/schema.ts src/schema-typebox.ts src/finance/discounts.ts src/finance/money.ts src/finance/storage.ts src/finance/custody.ts src/finance/tax.ts src/finance/derive.ts src/finance/venues.ts src/finance/ledger.ts src/finance/rates.ts src/finance/transfers.ts src/finance/chain.ts src/finance/chain-addresses.ts src/finance/chain-deposits.ts src/finance/chain-withdrawals.ts src/finance/chain-reconcile.ts src/finance/market.ts src/finance/commission.ts --root src --outdir dist --target browser --format esm --packages external && tsc --emitDeclarationOnly --declaration --noEmit false --outDir dist",
190
+ "build": "bun build src/query.ts src/realtime.ts src/jobs.ts src/queue.ts src/outbox.ts src/audit.ts src/backup.ts src/notify.ts src/notify-templates.ts src/calendar.ts src/compliance.ts src/pipeline.ts src/totp.ts src/otpauth.ts src/identity.ts src/slip10.ts src/openssh.ts src/ssh-cert.ts src/importers.ts src/snp.ts src/passkey.ts src/passkey-hybrid.ts src/custody-crypto.ts src/custody-share.ts src/phrase.ts src/schema.ts src/schema-typebox.ts src/finance/discounts.ts src/finance/money.ts src/finance/storage.ts src/finance/custody.ts src/finance/tax.ts src/finance/derive.ts src/finance/venues.ts src/finance/ledger.ts src/finance/rates.ts src/finance/transfers.ts src/finance/chain.ts src/finance/chain-addresses.ts src/finance/chain-deposits.ts src/finance/chain-withdrawals.ts src/finance/chain-reconcile.ts src/finance/market.ts src/finance/commission.ts --root src --outdir dist --target browser --format esm --packages external && tsc --emitDeclarationOnly --declaration --noEmit false --outDir dist",
187
191
  "prepublishOnly": "bun run check && bun run build"
188
192
  },
189
193
  "dependencies": {
190
- "@forgezero/access": "^0.1.0"
194
+ "@forgezero/access": "^0.1.3"
191
195
  },
192
196
  "peerDependencies": {
193
197
  "@noble/ciphers": "^2.2.0",
@@ -1,83 +0,0 @@
1
- /**
2
- * SSH agent as a custody factor.
3
- *
4
- * The ceremony seals every custodian share twice — once under a key derived from
5
- * a WebAuthn PRF output, once under a key derived from a BIP-39 phrase — and
6
- * either alone opens it. That works in a browser and not at all over SSH, which
7
- * is where the platform is first brought up: there is no passkey before there is
8
- * a platform to register one against.
9
- *
10
- * An SSH agent fills the same slot. Both are an agent-held key that produces a
11
- * stable secret without ever exposing the key itself, so the SSH signature over
12
- * a fixed challenge substitutes for the PRF output with no change to the sealing
13
- * code. The custodian later registers a passkey through the UI and the same
14
- * share gains a browser route.
15
- *
16
- * **Ed25519 only, and that is a correctness requirement rather than a
17
- * preference.** The derived key must be identical on every enrolment and every
18
- * unlock, so the signature has to be deterministic. Ed25519 is (RFC 8032). RSA
19
- * with PKCS#1 v1.5 happens to be, but agents are free to offer RSA-PSS for the
20
- * same key, and PSS is randomised — a share sealed under one PSS signature could
21
- * never be opened again. Refusing everything except Ed25519 makes that
22
- * impossible rather than rare.
23
- */
24
- export declare class SshAgentError extends Error {
25
- }
26
- export interface AgentIdentity {
27
- /** Raw SSH public key blob, as the agent returns it. */
28
- blob: Buffer;
29
- comment: string;
30
- /** `ssh-ed25519`, etc. Anything else is refused — see the module note. */
31
- type: string;
32
- /** `SHA256:…`, matching `ssh-add -l`, so a human can confirm which key. */
33
- fingerprint: string;
34
- }
35
- /**
36
- * How long to wait on the agent before giving up.
37
- *
38
- * An agent holding a forwarded key whose upstream is gone, or a confirm-on-use
39
- * key with nobody at the terminal, does not refuse — it simply never answers.
40
- * Without a socket-level deadline those connections are never closed, and a
41
- * caller that races them against its own timer leaks one socket per attempt
42
- * until the agent stops accepting connections entirely.
43
- */
44
- export declare const AGENT_TIMEOUT_MS = 3000;
45
- /** The keys the agent is holding. Matches `ssh-add -l`. */
46
- export declare function listIdentities(socketPath?: string): Promise<AgentIdentity[]>;
47
- /** Ed25519 only. See the module note — determinism is the whole mechanism. */
48
- export declare function listCustodyIdentities(socketPath?: string): Promise<AgentIdentity[]>;
49
- /**
50
- * Sign arbitrary bytes with an identity the agent holds.
51
- *
52
- * Exported because a fresh proof from a terminal needs it: the server issues a
53
- * nonce and this is what turns it into something the server can verify against
54
- * a registered public key. `deriveCustodyKey` signs a FIXED challenge and hashes
55
- * the result — that is a key-derivation, not a proof, and using it as one would
56
- * replay.
57
- *
58
- * Returns the raw ed25519 signature, unwrapped from the agent's blob, because
59
- * that is what a verifier takes.
60
- */
61
- export declare function signWithIdentity(identity: AgentIdentity, data: Uint8Array, socketPath?: string): Promise<Uint8Array>;
62
- /**
63
- * Derive the 32-byte custody key for an identity.
64
- *
65
- * Stable across processes and machines for the same key, which is what lets a
66
- * custodian enrol today and unlock next month from a different laptop with the
67
- * same key in their agent.
68
- *
69
- * HKDF over the signature rather than the signature itself: the signature is a
70
- * value the agent will hand to anything that asks, so using it directly as a
71
- * key would mean any process that can reach the socket holds the custody key.
72
- * The salt and info bind it to this purpose.
73
- */
74
- export declare function deriveCustodyKey(identity: AgentIdentity, socketPath?: string): Promise<Uint8Array>;
75
- /**
76
- * Prove the derivation reproduces before it is trusted with a share.
77
- *
78
- * Signs twice and compares. A non-deterministic agent — a smartcard doing PSS, a
79
- * forwarded agent that swapped keys mid-ceremony — would otherwise seal a share
80
- * under a key that can never be reproduced, and the failure would surface only
81
- * at the worst possible moment: recovery.
82
- */
83
- export declare function assertDeterministic(identity: AgentIdentity, socketPath?: string): Promise<Uint8Array>;
package/dist/ssh-agent.js DELETED
@@ -1,147 +0,0 @@
1
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
- }) : x)(function(x) {
4
- if (typeof require !== "undefined")
5
- return require.apply(this, arguments);
6
- throw Error('Dynamic require of "' + x + '" is not supported');
7
- });
8
-
9
- // src/ssh-agent.ts
10
- import { Socket } from "node:net";
11
- import { createHash, hkdfSync } from "node:crypto";
12
-
13
- class SshAgentError extends Error {
14
- }
15
- var SSH_AGENTC_REQUEST_IDENTITIES = 11;
16
- var SSH_AGENT_IDENTITIES_ANSWER = 12;
17
- var SSH_AGENTC_SIGN_REQUEST = 13;
18
- var SSH_AGENT_SIGN_RESPONSE = 14;
19
- var CUSTODY_CHALLENGE = Buffer.from("forgezero/custody/ssh-agent/v1", "utf8");
20
- function readString(buffer, offset) {
21
- const length = buffer.readUInt32BE(offset);
22
- const start = offset + 4;
23
- return [buffer.subarray(start, start + length), start + length];
24
- }
25
- function writeString(value) {
26
- const length = Buffer.alloc(4);
27
- length.writeUInt32BE(value.length);
28
- return Buffer.concat([length, value]);
29
- }
30
- function frame(payload) {
31
- const length = Buffer.alloc(4);
32
- length.writeUInt32BE(payload.length);
33
- return Buffer.concat([length, payload]);
34
- }
35
- var AGENT_TIMEOUT_MS = 3000;
36
- async function request(socketPath, payload) {
37
- return new Promise((resolve, reject) => {
38
- const socket = new Socket;
39
- const chunks = [];
40
- let expected = null;
41
- let settled = false;
42
- const fail = (message) => {
43
- if (settled)
44
- return;
45
- settled = true;
46
- socket.destroy();
47
- reject(new SshAgentError(message));
48
- };
49
- socket.setTimeout(AGENT_TIMEOUT_MS, () => fail("SSH_AGENT_TIMEOUT"));
50
- socket.on("error", () => fail("SSH_AGENT_UNREACHABLE"));
51
- socket.on("connect", () => socket.write(frame(payload)));
52
- socket.on("data", (chunk) => {
53
- chunks.push(chunk);
54
- const all = Buffer.concat(chunks);
55
- if (expected === null && all.length >= 4)
56
- expected = all.readUInt32BE(0);
57
- if (expected !== null && all.length >= expected + 4) {
58
- if (settled)
59
- return;
60
- settled = true;
61
- socket.end();
62
- resolve(all.subarray(4, expected + 4));
63
- }
64
- });
65
- socket.on("close", () => {
66
- if (expected === null)
67
- fail("SSH_AGENT_CLOSED_EARLY");
68
- });
69
- socket.connect(socketPath);
70
- });
71
- }
72
- function agentSocket(explicit) {
73
- const path = explicit ?? process.env.SSH_AUTH_SOCK;
74
- if (!path)
75
- throw new SshAgentError("SSH_AUTH_SOCK_NOT_SET");
76
- return path;
77
- }
78
- async function listIdentities(socketPath) {
79
- const response = await request(agentSocket(socketPath), Buffer.from([SSH_AGENTC_REQUEST_IDENTITIES]));
80
- if (response[0] !== SSH_AGENT_IDENTITIES_ANSWER) {
81
- throw new SshAgentError("SSH_AGENT_BAD_RESPONSE");
82
- }
83
- const count = response.readUInt32BE(1);
84
- const identities = [];
85
- let offset = 5;
86
- for (let index = 0;index < count; index += 1) {
87
- const [blob, afterBlob] = readString(response, offset);
88
- const [comment, afterComment] = readString(response, afterBlob);
89
- offset = afterComment;
90
- const [type] = readString(blob, 0);
91
- identities.push({
92
- blob,
93
- comment: comment.toString("utf8"),
94
- type: type.toString("utf8"),
95
- fingerprint: `SHA256:${createHash("sha256").update(blob).digest("base64").replace(/=+$/, "")}`
96
- });
97
- }
98
- return identities;
99
- }
100
- async function listCustodyIdentities(socketPath) {
101
- return (await listIdentities(socketPath)).filter((id) => id.type === "ssh-ed25519");
102
- }
103
- async function signWithIdentity(identity, data, socketPath) {
104
- const wrapped = await sign(identity.blob, Buffer.from(data), socketPath);
105
- const [raw] = readString(wrapped, readString(wrapped, 0)[1]);
106
- return new Uint8Array(raw);
107
- }
108
- async function sign(blob, data, socketPath) {
109
- const payload = Buffer.concat([
110
- Buffer.from([SSH_AGENTC_SIGN_REQUEST]),
111
- writeString(blob),
112
- writeString(data),
113
- Buffer.alloc(4)
114
- ]);
115
- const response = await request(agentSocket(socketPath), payload);
116
- if (response[0] !== SSH_AGENT_SIGN_RESPONSE) {
117
- throw new SshAgentError("SSH_AGENT_SIGN_REFUSED");
118
- }
119
- const [signature] = readString(response, 1);
120
- return signature;
121
- }
122
- async function deriveCustodyKey(identity, socketPath) {
123
- if (identity.type !== "ssh-ed25519") {
124
- throw new SshAgentError("SSH_KEY_TYPE_UNSUPPORTED");
125
- }
126
- const signature = await sign(identity.blob, CUSTODY_CHALLENGE, socketPath);
127
- if (signature.length < 32)
128
- throw new SshAgentError("SSH_AGENT_SIGNATURE_TOO_SHORT");
129
- return new Uint8Array(hkdfSync("sha256", signature, identity.blob, Buffer.from("forgezero/custody/ssh-key/v1", "utf8"), 32));
130
- }
131
- async function assertDeterministic(identity, socketPath) {
132
- const first = await deriveCustodyKey(identity, socketPath);
133
- const second = await deriveCustodyKey(identity, socketPath);
134
- if (Buffer.compare(Buffer.from(first), Buffer.from(second)) !== 0) {
135
- throw new SshAgentError("SSH_AGENT_NOT_DETERMINISTIC");
136
- }
137
- return first;
138
- }
139
- export {
140
- signWithIdentity,
141
- listIdentities,
142
- listCustodyIdentities,
143
- deriveCustodyKey,
144
- assertDeterministic,
145
- SshAgentError,
146
- AGENT_TIMEOUT_MS
147
- };