@qntx/wallet 0.3.0 → 0.5.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/dist/{index-Dhf6wGjQ.d.mts → chains-D_jfwTPT.d.mts} +299 -117
- package/dist/chains.d.mts +14 -0
- package/dist/chains.mjs +70 -0
- package/dist/chains.mjs.map +1 -0
- package/dist/{secret-IcTjjaX0.mjs → channel-ChYtMklb.mjs} +19 -155
- package/dist/channel-ChYtMklb.mjs.map +1 -0
- package/dist/{core-QJ66nLLG.mjs → core-Dmz5SbyJ.mjs} +55 -23
- package/dist/core-Dmz5SbyJ.mjs.map +1 -0
- package/dist/host.d.mts +17 -4
- package/dist/host.mjs +37 -9
- package/dist/host.mjs.map +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +2 -2
- package/dist/nostr.d.mts +1 -1
- package/dist/nostr.mjs +2 -1
- package/dist/nostr.mjs.map +1 -1
- package/dist/{protocol-D9xBuMzq.mjs → protocol-DvzlUKB8.mjs} +147 -3
- package/dist/protocol-DvzlUKB8.mjs.map +1 -0
- package/dist/protocol.d.mts +3 -3
- package/dist/protocol.mjs +3 -3
- package/dist/secret-BiyX0Hus.mjs +203 -0
- package/dist/secret-BiyX0Hus.mjs.map +1 -0
- package/dist/spark.d.mts +2 -2
- package/dist/{types-D4OUjGVS.d.mts → types-BD9fuAUj.d.mts} +9 -2
- package/dist/types.d.mts +1 -1
- package/dist/types.mjs.map +1 -1
- package/package.json +19 -7
- package/dist/core-QJ66nLLG.mjs.map +0 -1
- package/dist/protocol-D9xBuMzq.mjs.map +0 -1
- package/dist/secret-IcTjjaX0.mjs.map +0 -1
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { h as ValidationError } from "./core-
|
|
2
|
-
import { a as isProtocolValue, c as responseError, n as METHODS, o as kernelEvent, s as requestBytes } from "./protocol-
|
|
1
|
+
import { h as ValidationError } from "./core-Dmz5SbyJ.mjs";
|
|
2
|
+
import { a as isProtocolValue, c as responseError, n as METHODS, o as kernelEvent, s as requestBytes } from "./protocol-DvzlUKB8.mjs";
|
|
3
3
|
import { WalletError } from "./types.mjs";
|
|
4
|
-
import { base64urlnopad } from "@scure/base";
|
|
5
4
|
//#region src/channel.ts
|
|
6
5
|
/**
|
|
7
6
|
* The host side of the kernel channel (design/enclave.mdx "协议与传输"): port lifecycle, respawn,
|
|
@@ -87,15 +86,17 @@ var Channel = class {
|
|
|
87
86
|
this.unlisten = port.listen((message) => {
|
|
88
87
|
this.onMessage(message, generation);
|
|
89
88
|
});
|
|
90
|
-
this.unlistenExit = port.onExit(() => {
|
|
91
|
-
this.onExit(generation);
|
|
89
|
+
this.unlistenExit = port.onExit((reason) => {
|
|
90
|
+
this.onExit(reason, generation);
|
|
92
91
|
});
|
|
93
92
|
this.port = port;
|
|
94
|
-
} catch {
|
|
95
|
-
|
|
93
|
+
} catch (error) {
|
|
94
|
+
const spawnError = integrity("could not spawn the kernel port");
|
|
95
|
+
spawnError.cause = error;
|
|
96
|
+
this.breakChannel(spawnError);
|
|
96
97
|
}
|
|
97
98
|
}
|
|
98
|
-
onExit(generation) {
|
|
99
|
+
onExit(reason, generation) {
|
|
99
100
|
if (generation !== this.generation || this.destroyed || this.broken !== void 0) return;
|
|
100
101
|
this.session = void 0;
|
|
101
102
|
this.deferredStatus = void 0;
|
|
@@ -103,6 +104,10 @@ var Channel = class {
|
|
|
103
104
|
this.breakChannel(integrity("the kernel port died before its first status"));
|
|
104
105
|
return;
|
|
105
106
|
}
|
|
107
|
+
if (reason === "background") {
|
|
108
|
+
this.lockWith("background");
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
106
111
|
this.failPending(new WalletError("crashed", "the kernel port exited"));
|
|
107
112
|
this.handlers.onCrashed();
|
|
108
113
|
this.respawn();
|
|
@@ -113,11 +118,14 @@ var Channel = class {
|
|
|
113
118
|
* again. Safe mid-commit: IndexedDB transactions are atomic.
|
|
114
119
|
*/
|
|
115
120
|
lockNow() {
|
|
121
|
+
this.lockWith("user");
|
|
122
|
+
}
|
|
123
|
+
lockWith(reason) {
|
|
116
124
|
if (this.destroyed || this.broken !== void 0) return;
|
|
117
125
|
this.session = void 0;
|
|
118
126
|
this.deferredStatus = void 0;
|
|
119
127
|
this.failPending(new WalletError("locked", "the vault locked"));
|
|
120
|
-
this.handlers.onLocked(
|
|
128
|
+
this.handlers.onLocked(reason);
|
|
121
129
|
this.respawn();
|
|
122
130
|
}
|
|
123
131
|
onCallTimeout() {
|
|
@@ -308,150 +316,6 @@ var Channel = class {
|
|
|
308
316
|
}
|
|
309
317
|
};
|
|
310
318
|
//#endregion
|
|
311
|
-
|
|
312
|
-
/**
|
|
313
|
-
* Factor plumbing for the host connector: public `UnlockFactor`/`InitialFactor` inputs become wire
|
|
314
|
-
* `Factor` material, passkey material comes from the host's WebAuthn ceremony, and every secret
|
|
315
|
-
* byte travels in a fresh exact-size buffer on the transfer list.
|
|
316
|
-
*/
|
|
317
|
-
/** Purpose bytes stamped into the first byte of a credential's WebAuthn user handle. */
|
|
318
|
-
const PASSKEY_PURPOSE_WALLET = 1;
|
|
319
|
-
const PASSKEY_PURPOSE_VAULT = 2;
|
|
320
|
-
function vaultSaltBytes(source) {
|
|
321
|
-
return new TextEncoder().encode(source.passkey.vaultSalt);
|
|
322
|
-
}
|
|
323
|
-
function walletSaltBytes(source) {
|
|
324
|
-
return new TextEncoder().encode(source.passkey.walletSalt);
|
|
325
|
-
}
|
|
326
|
-
function backupSaltBytes(source) {
|
|
327
|
-
return new TextEncoder().encode(source.passkey.backupSalt);
|
|
328
|
-
}
|
|
329
|
-
/**
|
|
330
|
-
* Resolves a public `UnlockFactor` to wire backup-factor material: the passkey ceremony evaluates
|
|
331
|
-
* the PRF over `backupSalt` (purpose `0x02`), producing `prfBackup` instead of the vault `prf`.
|
|
332
|
-
*/
|
|
333
|
-
async function resolveBackupFactor(source, factor, transfer) {
|
|
334
|
-
if (factor.kind === "password") return {
|
|
335
|
-
kind: "password",
|
|
336
|
-
password: wireSecretText(factor.password, transfer)
|
|
337
|
-
};
|
|
338
|
-
const result = await requireCeremony(source).assert({
|
|
339
|
-
credentialIds: passkeyCredentialIds(source),
|
|
340
|
-
salts: { first: backupSaltBytes(source) }
|
|
341
|
-
});
|
|
342
|
-
return {
|
|
343
|
-
kind: "passkey",
|
|
344
|
-
credentialId: wireBytes(result.credentialId, transfer),
|
|
345
|
-
prfBackup: wireBytes(result.first, transfer, true)
|
|
346
|
-
};
|
|
347
|
-
}
|
|
348
|
-
/** Passkey credential ids of the current vault factors, for `assert`'s allowCredentials. */
|
|
349
|
-
function passkeyCredentialIds(source) {
|
|
350
|
-
return source.factors().flatMap((factor) => factor.kind === "passkey" ? [base64urlnopad.decode(factor.credentialId)] : []);
|
|
351
|
-
}
|
|
352
|
-
/**
|
|
353
|
-
* A Uint8Array is placed on the wire in a fresh exact-size buffer whose ArrayBuffer goes into the
|
|
354
|
-
* transfer list — the bytes move to the kernel and cannot detach caller-owned memory. Secret
|
|
355
|
-
* sources are wiped after copying.
|
|
356
|
-
*/
|
|
357
|
-
function wireBytes(source, transfer, wipeSource = false) {
|
|
358
|
-
const wire = new Uint8Array(source);
|
|
359
|
-
if (wipeSource) source.fill(0);
|
|
360
|
-
transfer.push(wire.buffer);
|
|
361
|
-
return wire;
|
|
362
|
-
}
|
|
363
|
-
function wireSecretText(text, transfer) {
|
|
364
|
-
return wireBytes(new TextEncoder().encode(text), transfer);
|
|
365
|
-
}
|
|
366
|
-
function requireCeremony(source) {
|
|
367
|
-
if (source.ceremony === void 0) throw new WalletError("factor-unavailable", "no passkey ceremony is configured");
|
|
368
|
-
return source.ceremony;
|
|
369
|
-
}
|
|
370
|
-
/** A passkey credential's display name: trimmed, 1–64 UTF-16 code units, else invalid-input. */
|
|
371
|
-
function passkeyName(name) {
|
|
372
|
-
const trimmed = name.trim();
|
|
373
|
-
if (trimmed.length === 0 || trimmed.length > 64) throw new WalletError("invalid-input", "the passkey name must be 1–64 characters");
|
|
374
|
-
return trimmed;
|
|
375
|
-
}
|
|
376
|
-
/**
|
|
377
|
-
* Resolves a public `UnlockFactor` to wire factor material. `transfer` collects every buffer the
|
|
378
|
-
* port must move. Ceremony errors surface as they are (cancelled / factor-unavailable).
|
|
379
|
-
*/
|
|
380
|
-
async function resolveFactor(source, factor, transfer) {
|
|
381
|
-
if (factor.kind === "password") return {
|
|
382
|
-
kind: "password",
|
|
383
|
-
password: wireSecretText(factor.password, transfer)
|
|
384
|
-
};
|
|
385
|
-
const result = await requireCeremony(source).assert({
|
|
386
|
-
credentialIds: passkeyCredentialIds(source),
|
|
387
|
-
salts: { first: vaultSaltBytes(source) }
|
|
388
|
-
});
|
|
389
|
-
return {
|
|
390
|
-
kind: "passkey",
|
|
391
|
-
credentialId: wireBytes(result.credentialId, transfer),
|
|
392
|
-
prf: wireBytes(result.first, transfer, true)
|
|
393
|
-
};
|
|
394
|
-
}
|
|
395
|
-
/**
|
|
396
|
-
* Resolves a public `InitialFactor` (a factor being created). For `create/restoreWithPasskey` the
|
|
397
|
-
* default passkey factor reuses the wallet ceremony's own credential and `second` PRF output.
|
|
398
|
-
*/
|
|
399
|
-
async function resolveInitialFactor(source, factor, transfer, walletCeremony) {
|
|
400
|
-
if (factor === void 0 || factor.kind === "passkey") {
|
|
401
|
-
const name = factor === void 0 ? void 0 : passkeyName(factor.name);
|
|
402
|
-
if (walletCeremony !== void 0) {
|
|
403
|
-
const { second } = walletCeremony;
|
|
404
|
-
if (second === void 0) throw new WalletError("factor-unavailable", "the ceremony returned no vault PRF output");
|
|
405
|
-
return {
|
|
406
|
-
kind: "passkey",
|
|
407
|
-
credentialId: wireBytes(walletCeremony.credentialId, transfer),
|
|
408
|
-
prf: wireBytes(second, transfer, true)
|
|
409
|
-
};
|
|
410
|
-
}
|
|
411
|
-
if (name === void 0) throw new WalletError("invalid-input", "a passkey factor requires a name");
|
|
412
|
-
const result = await requireCeremony(source).create({
|
|
413
|
-
purpose: "vault",
|
|
414
|
-
name,
|
|
415
|
-
salts: { first: vaultSaltBytes(source) }
|
|
416
|
-
});
|
|
417
|
-
return {
|
|
418
|
-
kind: "passkey",
|
|
419
|
-
credentialId: wireBytes(result.credentialId, transfer),
|
|
420
|
-
prf: wireBytes(result.first, transfer, true)
|
|
421
|
-
};
|
|
422
|
-
}
|
|
423
|
-
if (factor.kind === "password") {
|
|
424
|
-
walletCeremony?.second?.fill(0);
|
|
425
|
-
return {
|
|
426
|
-
kind: "password",
|
|
427
|
-
password: wireSecretText(factor.password, transfer)
|
|
428
|
-
};
|
|
429
|
-
}
|
|
430
|
-
throw new WalletError("factor-unavailable", "hardware factors exist only on React Native");
|
|
431
|
-
}
|
|
432
|
-
//#endregion
|
|
433
|
-
//#region src/secret.ts
|
|
434
|
-
/**
|
|
435
|
-
* One-shot secret bytes handed to the app: `read` returns them exactly once, `wipe` zeroes them.
|
|
436
|
-
* The second `read` fails closed.
|
|
437
|
-
*/
|
|
438
|
-
var SingleUseSecret = class {
|
|
439
|
-
bytes;
|
|
440
|
-
constructor(bytes) {
|
|
441
|
-
this.bytes = bytes;
|
|
442
|
-
}
|
|
443
|
-
read() {
|
|
444
|
-
const { bytes } = this;
|
|
445
|
-
if (bytes === void 0) throw new WalletError("invalid-input", "secret already read or wiped");
|
|
446
|
-
this.bytes = void 0;
|
|
447
|
-
return bytes;
|
|
448
|
-
}
|
|
449
|
-
wipe() {
|
|
450
|
-
this.bytes?.fill(0);
|
|
451
|
-
this.bytes = void 0;
|
|
452
|
-
}
|
|
453
|
-
};
|
|
454
|
-
//#endregion
|
|
455
|
-
export { requireCeremony as a, resolveInitialFactor as c, wireBytes as d, wireSecretText as f, passkeyName as i, vaultSaltBytes as l, integrity as m, PASSKEY_PURPOSE_VAULT as n, resolveBackupFactor as o, Channel as p, PASSKEY_PURPOSE_WALLET as r, resolveFactor as s, SingleUseSecret as t, walletSaltBytes as u };
|
|
319
|
+
export { integrity as n, Channel as t };
|
|
456
320
|
|
|
457
|
-
//# sourceMappingURL=
|
|
321
|
+
//# sourceMappingURL=channel-ChYtMklb.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"channel-ChYtMklb.mjs","names":[],"sources":["../src/channel.ts"],"sourcesContent":["/**\n * The host side of the kernel channel (design/enclave.mdx \"协议与传输\"): port lifecycle, respawn,\n * request/response correlation and wire validation. Internal to the `./host` subpath — reserved for\n * host packages (wallet-worker, wallet-native); applications must not use it.\n */\nimport {\n isProtocolValue,\n kernelEvent,\n MAX_REQUEST_BYTES,\n METHODS,\n PROTOCOL_VERSION,\n requestBytes,\n responseError,\n ValidationError,\n} from \"./protocol/index.ts\";\nimport type { MethodName, ParamsOf, ProtocolValue, ResultOf } from \"./protocol/index.ts\";\nimport { WalletError } from \"./types.ts\";\nimport type { LockReason, StatusPayload } from \"./types.ts\";\n\n/**\n * Why the kernel port ended: a fault in the enclave/transport, or a deliberate host-side lock\n * triggered by the platform (native background expiry — W7).\n */\nexport type PortExit = \"crashed\" | \"background\";\n\n/** The host packages' side of the kernel channel (worker, JSI runtime, in-process test port). */\nexport type MainPort = {\n readonly post: (message: ProtocolValue, transfer: ArrayBuffer[]) => void;\n readonly listen: (handler: (message: unknown) => void) => () => void;\n readonly onExit: (handler: (reason: PortExit) => void) => () => void;\n readonly terminate: () => void;\n};\n\nexport function integrity(message: string): WalletError {\n return new WalletError(\"integrity\", message);\n}\n\n/** Schedules `fn` after `delayMs` and returns a cancel function — injected by the host package. */\nexport type SetTimer = (delayMs: number, fn: () => void) => () => void;\n\n/**\n * A silent kernel is a wedged kernel: the request at the head of the kernel's serial queue gets\n * this long before the port is replaced. Requests still queued behind it are not timed — the kernel\n * answers in order, so only the head can wedge.\n */\nconst CALL_TIMEOUT_MS = 60_000;\n\ntype Pending = {\n readonly method: MethodName;\n readonly resolve: (value: unknown) => void;\n readonly reject: (error: WalletError) => void;\n};\n\n/**\n * State callbacks: the channel owns the port lifecycle and message ordering; the wallet owns the\n * snapshot state these events describe. `onLocked`/`onCrashed` fire before the port is replaced so\n * the wallet can stamp the lock reason.\n */\nexport type ChannelHandlers = {\n readonly onStatus: (status: StatusPayload) => void;\n readonly onLocked: (reason: LockReason) => void;\n readonly onCrashed: () => void;\n};\n\nexport class Channel {\n /** The live kernel session; attached to every request and cleared whenever it is gone. */\n session: string | undefined;\n\n private port: MainPort | undefined;\n private unlisten: (() => void) | undefined;\n private unlistenExit: (() => void) | undefined;\n private generation = 0;\n\n private readonly pending = new Map<number, Pending>();\n /** Times the earliest pending request — the one the kernel is working on. */\n private watchdog: { readonly id: number; readonly cancel: () => void } | undefined;\n private nextId = 1;\n private destroyed = false;\n /** Terminal state: the kernel peer proved untrustworthy; every later call fails with it. */\n private broken: WalletError | undefined;\n /** An unlocked status held back until the session it belongs to is installed. */\n private deferredStatus: StatusPayload | undefined;\n /** Whether the current port has delivered its first valid status event. */\n private portReady = false;\n private readyPromise: Promise<void>;\n private resolveReady: (() => void) | undefined;\n private rejectReady: ((error: WalletError) => void) | undefined;\n\n private readonly spawn: () => MainPort;\n private readonly handlers: ChannelHandlers;\n private readonly setTimer: SetTimer;\n\n constructor(spawn: () => MainPort, handlers: ChannelHandlers, setTimer: SetTimer) {\n this.spawn = spawn;\n this.handlers = handlers;\n this.setTimer = setTimer;\n this.readyPromise = new Promise((resolve, reject) => {\n this.resolveReady = resolve;\n this.rejectReady = reject;\n });\n }\n\n /** Spawns the first kernel and resolves once its initial status event arrives. */\n async start(): Promise<void> {\n this.respawn();\n return this.readyPromise;\n }\n\n /** Resolves when the current port has delivered its first status event. */\n get ready(): Promise<void> {\n return this.readyPromise;\n }\n\n /**\n * Terminates the current port and spawns a fresh secret runtime, keeping the vault image (the\n * host-side store survives the worker). \"Lock destroys the enclave.\"\n */\n respawn(): void {\n if (this.destroyed || this.broken !== undefined) {\n return;\n }\n this.unlisten?.();\n this.unlistenExit?.();\n this.port?.terminate();\n this.port = undefined;\n this.session = undefined;\n this.deferredStatus = undefined;\n this.watchdog?.cancel();\n this.watchdog = undefined;\n this.portReady = false;\n\n const generation = ++this.generation;\n // Settle the previous gate: a call still awaiting it must not hang — the kernel it was\n // waiting for is gone, so \"locked\" (session destroyed) applies.\n // oxlint-disable-next-line promise/prefer-await-to-then -- marks the stale gate as handled without swallowing it for awaiters\n void this.readyPromise.catch(() => undefined);\n this.rejectReady?.(new WalletError(\"locked\", \"the kernel restarted\"));\n this.readyPromise = new Promise((resolve, reject) => {\n this.resolveReady = resolve;\n this.rejectReady = reject;\n });\n // A rejected gate with nobody awaiting it (e.g. destroy() mid-boot) must not surface as\n // an unhandled rejection; callers that do await still observe the rejection.\n // oxlint-disable-next-line promise/prefer-await-to-then -- marks the gate as handled without swallowing it for awaiters\n void this.readyPromise.catch(() => undefined);\n try {\n const port = this.spawn();\n this.unlisten = port.listen((message) => {\n this.onMessage(message, generation);\n });\n this.unlistenExit = port.onExit((reason) => {\n this.onExit(reason, generation);\n });\n this.port = port;\n } catch (error) {\n // A host that cannot spawn has no kernel to talk to — fail closed like a dead peer.\n const spawnError = integrity(\"could not spawn the kernel port\");\n spawnError.cause = error;\n this.breakChannel(spawnError);\n }\n }\n\n private onExit(reason: PortExit, generation: number): void {\n if (generation !== this.generation || this.destroyed || this.broken !== undefined) {\n return;\n }\n this.session = undefined;\n this.deferredStatus = undefined;\n if (!this.portReady) {\n // Death before the first valid status means the runtime never ran honestly (worker\n // blocked by CSP, a script that fails to load, protocol skew): no respawn — a fresh\n // spawn would face the same broken peer. Initial connect rejects with integrity;\n // a respawned port dying this way breaks the wallet.\n this.breakChannel(integrity(\"the kernel port died before its first status\"));\n return;\n }\n if (reason === \"background\") {\n // The platform backgrounded the app past autoLock.backgroundSeconds and locked the\n // enclave: not a crash — take the lock path so the user sees the real reason.\n this.lockWith(\"background\");\n return;\n }\n // A proven port dying is a crash: fail everything in flight, mark it, respawn.\n this.failPending(new WalletError(\"crashed\", \"the kernel port exited\"));\n this.handlers.onCrashed();\n this.respawn();\n }\n\n /**\n * Immediate host-side lock: no kernel round trip. Fails everything in flight with `locked`, drops\n * the session, reports the user lock, and replaces the port — the old worker can never answer\n * again. Safe mid-commit: IndexedDB transactions are atomic.\n */\n lockNow(): void {\n this.lockWith(\"user\");\n }\n\n private lockWith(reason: \"user\" | \"background\"): void {\n if (this.destroyed || this.broken !== undefined) {\n return;\n }\n this.session = undefined;\n this.deferredStatus = undefined;\n this.failPending(new WalletError(\"locked\", \"the vault locked\"));\n this.handlers.onLocked(reason);\n this.respawn();\n }\n\n private onCallTimeout(): void {\n if (this.destroyed || this.broken !== undefined) {\n return;\n }\n this.failPending(new WalletError(\"crashed\", \"the kernel did not answer in time\"));\n this.handlers.onCrashed();\n this.respawn();\n }\n\n private failPending(error: WalletError): void {\n this.watchdog?.cancel();\n this.watchdog = undefined;\n for (const [, pending] of this.pending) {\n pending.reject(error);\n }\n this.pending.clear();\n }\n\n /** (Re)arms the watchdog on `pending`'s insertion-ordered head, or clears it when empty. */\n private armWatchdog(): void {\n this.watchdog?.cancel();\n const head = this.pending.keys().next().value;\n this.watchdog =\n head === undefined\n ? undefined\n : {\n id: head,\n cancel: this.setTimer(CALL_TIMEOUT_MS, () => {\n this.onCallTimeout();\n }),\n };\n }\n\n /** Removes the pending entry, re-timing the watchdog when the head settled, then runs `fn`. */\n private settle(id: number, fn: (pending: Pending) => void): void {\n const pending = this.pending.get(id);\n if (pending !== undefined) {\n this.pending.delete(id);\n if (this.watchdog?.id === id) {\n this.armWatchdog();\n }\n fn(pending);\n }\n }\n\n /**\n * Terminal failure: terminate the port, fail everything in flight, and latch `broken` so every\n * later call rejects with the same error. The snapshot is left untouched.\n */\n private breakChannel(error: WalletError): void {\n this.broken = error;\n this.session = undefined;\n this.deferredStatus = undefined;\n this.failPending(error);\n this.rejectReady?.(error);\n this.unlisten?.();\n this.unlistenExit?.();\n this.port?.terminate();\n this.port = undefined;\n this.generation++; // anything the dead port still emits is stale\n }\n\n /** A malformed protocol peer cannot be trusted — it fails closed, never respawns. */\n private poison(reason: string): void {\n this.breakChannel(integrity(reason));\n }\n\n private onMessage(raw: unknown, generation: number): void {\n if (generation !== this.generation) {\n return; // a dead port must not steer the wallet\n }\n if (\n !isProtocolValue(raw) ||\n typeof raw !== \"object\" ||\n raw === null ||\n raw instanceof Uint8Array ||\n Array.isArray(raw)\n ) {\n this.poison(\"malformed kernel message\");\n return;\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- narrowed to a plain record above\n const message = raw as Readonly<Record<string, ProtocolValue>>;\n if (\"id\" in message) {\n this.onResponse(message);\n return;\n }\n if (\"event\" in message) {\n let event;\n try {\n event = kernelEvent(message);\n } catch (error) {\n if (!(error instanceof ValidationError)) {\n throw error;\n }\n this.poison(\"malformed kernel event\");\n return;\n }\n if (event.event === \"status\") {\n if (event.status.vault !== \"unlocked\") {\n this.session = undefined;\n this.deferredStatus = undefined;\n this.handlers.onStatus(event.status);\n } else if (this.session === undefined) {\n // The unlock/create response has not delivered the session yet — subscribers must\n // never see \"unlocked\" while requests would go out sessionless.\n this.deferredStatus = event.status;\n } else {\n this.handlers.onStatus(event.status);\n }\n this.portReady = true;\n this.resolveReady?.();\n } else {\n // A locked event destroys the enclave: drop the session, tear down the port, respawn.\n this.session = undefined;\n this.deferredStatus = undefined;\n this.handlers.onLocked(event.reason);\n this.failPending(new WalletError(\"locked\", \"the vault locked\"));\n this.respawn();\n }\n return;\n }\n this.poison(\"unrecognised kernel message\");\n }\n\n private onResponse(message: Readonly<Record<string, ProtocolValue>>): void {\n const { id } = message;\n if (typeof id !== \"number\" || !Number.isSafeInteger(id) || message[\"v\"] !== PROTOCOL_VERSION) {\n this.poison(\"malformed response envelope\");\n return;\n }\n const pending = this.pending.get(id);\n if (pending === undefined) {\n // Includes UNATTRIBUTED_ID 0 — never a live request.\n this.poison(\"response for an unknown request\");\n return;\n }\n const hasOk = \"ok\" in message;\n const hasErr = \"err\" in message;\n if (hasOk === hasErr) {\n // Keep the entry so poison's failPending rejects this caller too.\n this.poison(\"malformed response body\");\n return;\n }\n if (hasErr) {\n try {\n const err = responseError(message[\"err\"]);\n this.settle(id, (p) => {\n p.reject(\n new WalletError(\n err.code,\n `kernel returned ${err.code}`,\n typeof err.retryAt === \"number\" ? err.retryAt : undefined,\n ),\n );\n });\n } catch (error) {\n if (!(error instanceof ValidationError)) {\n throw error;\n }\n this.poison(\"malformed error payload\");\n }\n return;\n }\n try {\n const result = METHODS[pending.method].result(message[\"ok\"]);\n this.settle(id, (p) => {\n p.resolve(result);\n });\n } catch (error) {\n if (!(error instanceof ValidationError)) {\n throw error;\n }\n this.poison(\"invalid result from the kernel\");\n }\n }\n\n /**\n * Sends one request and resolves with the validated result. The kernel answers with status →\n * response → locked, so the snapshot is already current when this promise settles.\n */\n async call<M extends MethodName>(\n method: M,\n params: ParamsOf<M>,\n transfer: ArrayBuffer[] = [],\n ): Promise<ResultOf<M>> {\n await this.readyPromise;\n if (this.broken !== undefined) {\n throw this.broken;\n }\n const { port } = this;\n if (this.destroyed || port === undefined) {\n throw new WalletError(\"locked\", \"wallet is destroyed\");\n }\n const id = this.nextId++;\n const message: Record<string, ProtocolValue> = { v: PROTOCOL_VERSION, id, method, params };\n // Attach the session whenever we hold one: the create/import methods are session:false\n // in the table because the rule is dynamic (required exactly when the vault is initialized).\n if (this.session !== undefined) {\n message[\"session\"] = this.session;\n }\n // The whole envelope counts against the cap — an oversized request never reaches the port.\n if (requestBytes(message) > MAX_REQUEST_BYTES) {\n throw new WalletError(\"invalid-input\", \"request exceeds the size limit\");\n }\n const result = await new Promise<unknown>((resolve, reject) => {\n this.pending.set(id, { method, resolve, reject });\n if (this.watchdog === undefined) {\n // Pending went empty → non-empty: this request is the head the kernel works on next.\n this.armWatchdog();\n }\n try {\n port.post(message, transfer);\n } catch {\n this.pending.delete(id);\n if (this.watchdog?.id === id) {\n this.armWatchdog();\n }\n reject(integrity(\"the kernel port refused the message\"));\n }\n });\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- validated by METHODS[method].result\n return result as ResultOf<M>;\n }\n\n /** Fires the deferred unlocked status, if any, once the session is installed. */\n flushStatus(): void {\n const status = this.deferredStatus;\n if (status !== undefined && this.session !== undefined) {\n this.deferredStatus = undefined;\n this.handlers.onStatus(status);\n }\n }\n\n /** Terminates the port without respawn; later calls fail \"locked\". */\n destroy(): void {\n if (this.destroyed) {\n return;\n }\n this.destroyed = true;\n this.unlisten?.();\n this.unlistenExit?.();\n this.port?.terminate();\n this.port = undefined;\n this.session = undefined;\n this.deferredStatus = undefined;\n this.rejectReady?.(new WalletError(\"locked\", \"wallet is destroyed\"));\n this.failPending(new WalletError(\"locked\", \"wallet is destroyed\"));\n }\n}\n"],"mappings":";;;;;;;;;AAiCA,SAAgB,UAAU,SAA8B;CACtD,OAAO,IAAI,YAAY,aAAa,OAAO;AAC7C;;;;;;AAUA,MAAM,kBAAkB;AAmBxB,IAAa,UAAb,MAAqB;;CAEnB;CAEA;CACA;CACA;CACA,aAAqB;CAErB,0BAA2B,IAAI,IAAqB;;CAEpD;CACA,SAAiB;CACjB,YAAoB;;CAEpB;;CAEA;;CAEA,YAAoB;CACpB;CACA;CACA;CAEA;CACA;CACA;CAEA,YAAY,OAAuB,UAA2B,UAAoB;EAChF,KAAK,QAAQ;EACb,KAAK,WAAW;EAChB,KAAK,WAAW;EAChB,KAAK,eAAe,IAAI,SAAS,SAAS,WAAW;GACnD,KAAK,eAAe;GACpB,KAAK,cAAc;EACrB,CAAC;CACH;;CAGA,MAAM,QAAuB;EAC3B,KAAK,QAAQ;EACb,OAAO,KAAK;CACd;;CAGA,IAAI,QAAuB;EACzB,OAAO,KAAK;CACd;;;;;CAMA,UAAgB;EACd,IAAI,KAAK,aAAa,KAAK,WAAW,KAAA,GACpC;EAEF,KAAK,WAAW;EAChB,KAAK,eAAe;EACpB,KAAK,MAAM,UAAU;EACrB,KAAK,OAAO,KAAA;EACZ,KAAK,UAAU,KAAA;EACf,KAAK,iBAAiB,KAAA;EACtB,KAAK,UAAU,OAAO;EACtB,KAAK,WAAW,KAAA;EAChB,KA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AO,UAAU,qCAAqC,CAAC;GACzD;EACF,CAAC;CAGH;;CAGA,cAAoB;EAClB,MAAM,SAAS,KAAK;EACpB,IAAI,WAAW,KAAA,KAAa,KAAK,YAAY,KAAA,GAAW;GACtD,KAAK,iBAAiB,KAAA;GACtB,KAAK,SAAS,SAAS,MAAM;EAC/B;CACF;;CAGA,UAAgB;EACd,IAAI,KAAK,WACP;EAEF,KAAK,YAAY;EACjB,KAAK,WAAW;EAChB,KAAK,eAAe;EACpB,KAAK,MAAM,UAAU;EACrB,KAAK,OAAO,KAAA;EACZ,KAAK,UAAU,KAAA;EACf,KAAK,iBAAiB,KAAA;EACtB,KAAK,cAAc,IAAI,YAAY,UAAU,qBAAqB,CAAC;EACnE,KAAK,YAAY,IAAI,YAAY,UAAU,qBAAqB,CAAC;CACnE;AACF"}
|
|
@@ -130,7 +130,7 @@ const publicKey = str(64, /^[0-9a-f]{64}$/);
|
|
|
130
130
|
const credentialId = str(1364, /^[A-Za-z0-9_-]+$/);
|
|
131
131
|
const safeTime = int(0, Number.MAX_SAFE_INTEGER);
|
|
132
132
|
const groupIndex = int(0, 2147483647);
|
|
133
|
-
const factor = union(obj({
|
|
133
|
+
const factor = union(obj({ kind: literal("hardware") }), obj({
|
|
134
134
|
kind: literal("password"),
|
|
135
135
|
password: bytes(1, 1024)
|
|
136
136
|
}), obj({
|
|
@@ -138,15 +138,11 @@ const factor = union(obj({
|
|
|
138
138
|
credentialId: bytes(1, 1023),
|
|
139
139
|
prf: bytes(32)
|
|
140
140
|
}));
|
|
141
|
-
const
|
|
142
|
-
kind: literal("
|
|
143
|
-
|
|
141
|
+
const factorInfo = union(obj({
|
|
142
|
+
kind: literal("hardware"),
|
|
143
|
+
id: sessionId,
|
|
144
|
+
createdAt: safeTime
|
|
144
145
|
}), obj({
|
|
145
|
-
kind: literal("passkey"),
|
|
146
|
-
credentialId: bytes(1, 1023),
|
|
147
|
-
prfBackup: bytes(32)
|
|
148
|
-
}));
|
|
149
|
-
const factorInfo = union(obj({ kind: literal("hardware") }), obj({
|
|
150
146
|
kind: literal("passkey"),
|
|
151
147
|
id: sessionId,
|
|
152
148
|
credentialId,
|
|
@@ -156,6 +152,52 @@ const factorInfo = union(obj({ kind: literal("hardware") }), obj({
|
|
|
156
152
|
id: sessionId,
|
|
157
153
|
createdAt: safeTime
|
|
158
154
|
}));
|
|
155
|
+
const RP_ID = /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/;
|
|
156
|
+
const label = (max) => str(max, /^\S(?:.*\S)?$/su);
|
|
157
|
+
const hostEvidence = {
|
|
158
|
+
ceremony: literal("host"),
|
|
159
|
+
credentialId: bytes(1, 1023),
|
|
160
|
+
prfWallet: bytes(32),
|
|
161
|
+
synced: bool,
|
|
162
|
+
factor: opt(factor)
|
|
163
|
+
};
|
|
164
|
+
const createWithPasskeyParams = union(obj(hostEvidence), obj({
|
|
165
|
+
ceremony: literal("kernel"),
|
|
166
|
+
rpId: str(253, RP_ID),
|
|
167
|
+
rpName: label(64),
|
|
168
|
+
name: label(64),
|
|
169
|
+
walletSalt: label(64),
|
|
170
|
+
factor: opt(factor)
|
|
171
|
+
}));
|
|
172
|
+
const restoreWithPasskeyParams = union(obj(hostEvidence), obj({
|
|
173
|
+
ceremony: literal("kernel"),
|
|
174
|
+
rpId: str(253, RP_ID),
|
|
175
|
+
walletSalt: label(64),
|
|
176
|
+
factor: opt(factor)
|
|
177
|
+
}));
|
|
178
|
+
const hostBackupPasskey = obj({
|
|
179
|
+
kind: literal("passkey"),
|
|
180
|
+
ceremony: literal("host"),
|
|
181
|
+
credentialId: bytes(1, 1023),
|
|
182
|
+
prfBackup: bytes(32)
|
|
183
|
+
});
|
|
184
|
+
const backupPassword = obj({
|
|
185
|
+
kind: literal("password"),
|
|
186
|
+
password: bytes(1, 1024)
|
|
187
|
+
});
|
|
188
|
+
const backupFactor = union(backupPassword, hostBackupPasskey, obj({
|
|
189
|
+
kind: literal("passkey"),
|
|
190
|
+
ceremony: literal("kernel"),
|
|
191
|
+
rpId: str(253, RP_ID),
|
|
192
|
+
rpName: label(64),
|
|
193
|
+
backupSalt: label(64)
|
|
194
|
+
}));
|
|
195
|
+
const backupUnlockFactor = union(backupPassword, hostBackupPasskey, obj({
|
|
196
|
+
kind: literal("passkey"),
|
|
197
|
+
ceremony: literal("kernel"),
|
|
198
|
+
rpId: str(253, RP_ID),
|
|
199
|
+
backupSalt: label(64)
|
|
200
|
+
}));
|
|
159
201
|
const walletInfo = obj({
|
|
160
202
|
walletId,
|
|
161
203
|
origin: union(literal("passkey"), literal("mnemonic")),
|
|
@@ -208,23 +250,13 @@ const CORE_METHODS = {
|
|
|
208
250
|
"wallet.createWithPasskey": {
|
|
209
251
|
session: false,
|
|
210
252
|
presence: true,
|
|
211
|
-
params:
|
|
212
|
-
credentialId: bytes(1, 1023),
|
|
213
|
-
prfWallet: bytes(32),
|
|
214
|
-
synced: bool,
|
|
215
|
-
factor: opt(factor)
|
|
216
|
-
}),
|
|
253
|
+
params: createWithPasskeyParams,
|
|
217
254
|
result: createdResult
|
|
218
255
|
},
|
|
219
256
|
"wallet.restoreWithPasskey": {
|
|
220
257
|
session: false,
|
|
221
258
|
presence: true,
|
|
222
|
-
params:
|
|
223
|
-
credentialId: bytes(1, 1023),
|
|
224
|
-
prfWallet: bytes(32),
|
|
225
|
-
synced: bool,
|
|
226
|
-
factor: opt(factor)
|
|
227
|
-
}),
|
|
259
|
+
params: restoreWithPasskeyParams,
|
|
228
260
|
result: createdResult
|
|
229
261
|
},
|
|
230
262
|
"wallet.createMnemonic": {
|
|
@@ -281,7 +313,7 @@ const CORE_METHODS = {
|
|
|
281
313
|
presence: true,
|
|
282
314
|
params: obj({
|
|
283
315
|
envelope: str(4e6),
|
|
284
|
-
backupFactor,
|
|
316
|
+
backupFactor: backupUnlockFactor,
|
|
285
317
|
factor: opt(factor)
|
|
286
318
|
}),
|
|
287
319
|
result: obj({
|
|
@@ -326,4 +358,4 @@ const CORE_METHODS = {
|
|
|
326
358
|
//#endregion
|
|
327
359
|
export { opt as C, validate as D, union as E, obj as S, str as T, bool as _, MAX_TEXT as a, literal as b, groupIndex as c, sessionId as d, walletErrorCode as f, arr as g, ValidationError as h, MAX_TAG_ITEM as i, publicKey as l, walletInfo as m, MAX_SNAPSHOT_ITEMS as n, factor as o, walletId as p, MAX_TAGS as r, factorInfo as s, CORE_METHODS as t, safeTime as u, bytes as v, record as w, nullValue as x, int as y };
|
|
328
360
|
|
|
329
|
-
//# sourceMappingURL=core-
|
|
361
|
+
//# sourceMappingURL=core-Dmz5SbyJ.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"core-Dmz5SbyJ.mjs","names":[],"sources":["../src/protocol/validate.ts","../src/protocol/core.ts"],"sourcesContent":["/**\n * Strict validator combinators for the secret-area protocol. Both sides share them: the kernel\n * validates every request, the host validates every response. Anything that does not match is a\n * `ValidationError` — never a partially-accepted value.\n */\nimport type { NullValue } from \"./index.ts\";\n\nexport class ValidationError extends Error {\n override name = \"ValidationError\";\n}\n\nexport type Validator<T> = (value: unknown) => T;\n\nfunction fail(): never {\n throw new ValidationError();\n}\n\nexport function literal<T extends NullValue | boolean | number | string>(\n expected: T,\n): Validator<T> {\n return (value) => {\n if (value !== expected) {\n fail();\n }\n return expected;\n };\n}\n\nexport const nullValue: Validator<NullValue> = literal(null);\nexport const bool: Validator<boolean> = (value) => {\n if (typeof value !== \"boolean\") {\n fail();\n }\n return value;\n};\n\nexport function int(min: number, max: number): Validator<number> {\n return (value) => {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < min || value > max) {\n fail();\n }\n return value;\n };\n}\n\nexport function str(max: number, pattern?: RegExp): Validator<string> {\n return (value) => {\n if (\n typeof value !== \"string\" ||\n value.length > max ||\n (pattern !== undefined && !pattern.test(value))\n ) {\n fail();\n }\n return value;\n };\n}\n\nexport function bytes(min: number, max?: number): Validator<Uint8Array> {\n const high = max ?? min;\n return (value) => {\n if (!(value instanceof Uint8Array) || value.length < min || value.length > high) {\n fail();\n }\n return value;\n };\n}\n\nexport function arr<T>(item: Validator<T>, max: number, min = 0): Validator<ReadonlyArray<T>> {\n return (value) => {\n if (!Array.isArray(value) || value.length < min || value.length > max) {\n fail();\n }\n const out: T[] = [];\n for (const element of value) {\n out.push(item(element));\n }\n return out;\n };\n}\n\nclass Opt<T> {\n readonly validator: Validator<T>;\n\n constructor(validator: Validator<T>) {\n this.validator = validator;\n }\n}\n\nexport function opt<T>(validator: Validator<T>): Opt<T> {\n return new Opt(validator);\n}\n\ntype Field = Validator<unknown> | Opt<unknown>;\ntype Shape = Record<string, Field>;\n\ntype RequiredKeys<S extends Shape> = {\n readonly [K in keyof S as S[K] extends Opt<unknown> ? never : K]: S[K] extends Validator<infer T>\n ? T\n : never;\n};\ntype OptionalKeys<S extends Shape> = {\n readonly [K in keyof S as S[K] extends Opt<unknown> ? K : never]?: S[K] extends Opt<infer T>\n ? T\n : never;\n};\ntype ShapeResult<S extends Shape> = RequiredKeys<S> & OptionalKeys<S>;\n\n/** Exact key set: required keys present, optional keys allowed, nothing else. */\nexport function obj<S extends Shape>(shape: S): Validator<ShapeResult<S>> {\n const keys = Object.keys(shape);\n return (value) => {\n if (\n typeof value !== \"object\" ||\n value === null ||\n Array.isArray(value) ||\n value instanceof Uint8Array\n ) {\n fail();\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- narrowed to a plain object above\n const record = value as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (!Object.hasOwn(shape, key)) {\n fail();\n }\n }\n const out: Record<string, unknown> = {};\n for (const key of keys) {\n const field = shape[key];\n if (field === undefined) {\n fail();\n }\n const raw = record[key];\n if (field instanceof Opt) {\n if (raw !== undefined) {\n out[key] = field.validator(raw);\n }\n } else {\n if (!Object.hasOwn(record, key)) {\n fail();\n }\n out[key] = field(raw);\n }\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the shape guarantees the keys\n return out as ShapeResult<S>;\n };\n}\n\nconst FORBIDDEN_RECORD_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/**\n * A `Record<K, V>` wire value: plain objects only, every key checked by `key`, every value by\n * `value`, at most `max` entries. Prototype-polluting keys are rejected outright — a validated\n * record must be safe to copy key-by-key.\n */\nexport function record<K extends string, V>(\n key: Validator<K>,\n value: Validator<V>,\n max: number,\n): Validator<Record<K, V>> {\n return (input) => {\n if (\n typeof input !== \"object\" ||\n input === null ||\n Array.isArray(input) ||\n input instanceof Uint8Array ||\n Object.getPrototypeOf(input) !== Object.prototype\n ) {\n fail();\n }\n const out: Record<string, V> = {};\n const entries = Object.entries(input);\n if (entries.length > max) {\n fail();\n }\n for (const [name, item] of entries) {\n if (FORBIDDEN_RECORD_KEYS.has(name)) {\n fail();\n }\n out[key(name)] = value(item);\n }\n return out;\n };\n}\n\n/** Tries each branch in order; the first match wins. */\nexport function union<Vs extends ReadonlyArray<Validator<unknown>>>(\n ...branches: Vs\n): Validator<ReturnType<Vs[number]>> {\n return (value) => {\n for (const branch of branches) {\n try {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- ReturnType of the branch union\n return branch(value) as ReturnType<Vs[number]>;\n } catch (error) {\n if (!(error instanceof ValidationError)) {\n throw error;\n }\n }\n }\n return fail();\n };\n}\n\n/** Validates a value and returns it, or undefined on a shape mismatch. */\nexport function validate<T>(validator: Validator<T>, value: unknown): T | undefined {\n try {\n return validator(value);\n } catch (error) {\n if (error instanceof ValidationError) {\n return undefined;\n }\n throw error;\n }\n}\n","/**\n * The core method table: vault, wallet and data-key commands — nothing protocol-specific. \"Create\n * or import\" commands (createWithPasskey/restoreWithPasskey/createMnemonic/importMnemonic) are\n * `session: false` here because the rule is dynamic: with an uninitialized vault they carry\n * `factor` and establish the vault in one commit; with an established vault `factor` must be absent\n * and a valid session is required.\n *\n * The shared wire validators (factor, wallet info, ids) live here too so the nostr module's table\n * can reuse them — `protocol/nostr.ts` imports only from this file.\n */\nimport type { FactorInfo, WalletErrorCode, WalletInfo } from \"../types.ts\";\nimport type { NullValue } from \"./index.ts\";\nimport type { Validator } from \"./validate.ts\";\nimport { arr, bool, bytes, int, literal, nullValue, obj, opt, str, union } from \"./validate.ts\";\n\nexport type MethodSpec<P, R> = {\n readonly session: boolean;\n /** Whether a successful call refreshes the idle timer — presence-bearing methods only. */\n readonly presence: boolean;\n readonly params: Validator<P>;\n readonly result: Validator<R>;\n};\n\n// Size caps (UTF-16 units for strings, bytes for Uint8Array). These bound individual fields; the\n// whole-request cap MAX_REQUEST_BYTES (protocol/index.ts) is enforced by host and kernel.\nexport const MAX_TEXT = 262_144;\nexport const MAX_TAGS = 1024;\nexport const MAX_TAG_ITEMS = 64;\nexport const MAX_TAG_ITEM = 4096;\nexport const MAX_BATCH = 64;\nexport const MAX_SNAPSHOT_ITEMS = 4096;\n\nexport const sessionId: Validator<string> = str(32, /^[0-9a-f]{32}$/);\nexport const draftId: Validator<string> = str(32, /^[0-9a-f]{32}$/);\nexport const walletId: Validator<string> = str(16, /^[0-9a-f]{16}$/);\nexport const publicKey: Validator<string> = str(64, /^[0-9a-f]{64}$/);\nexport const credentialId: Validator<string> = str(1364, /^[A-Za-z0-9_-]+$/);\nexport const safeTime: Validator<number> = int(0, Number.MAX_SAFE_INTEGER);\nexport const groupIndex: Validator<number> = int(0, 0x7fffffff);\n\n/**\n * Vault factor material on the wire. `hardware` carries nothing: the kernel runs the platform\n * keystore ceremony itself, so the main runtime never touches the KEK.\n */\nexport type Factor =\n | { readonly kind: \"hardware\" }\n | { readonly kind: \"password\"; readonly password: Uint8Array }\n | { readonly kind: \"passkey\"; readonly credentialId: Uint8Array; readonly prf: Uint8Array };\n\nexport const factor: Validator<Factor> = union(\n obj({ kind: literal(\"hardware\") }),\n obj({ kind: literal(\"password\"), password: bytes(1, 1024) }),\n obj({ kind: literal(\"passkey\"), credentialId: bytes(1, 1023), prf: bytes(32) }),\n);\n\n/** A host-run backup passkey ceremony's evidence: the PRF over `backupSalt` (web). */\ntype HostBackupPasskey = {\n readonly kind: \"passkey\";\n readonly ceremony: \"host\";\n readonly credentialId: Uint8Array;\n readonly prfBackup: Uint8Array;\n};\n\n/**\n * A factor that seals a new backup key. On React Native the kernel registers a protection\n * credential (`kernel`) itself and names it; on the web the host hands over its ceremony's\n * evidence.\n */\nexport type BackupFactor =\n | { readonly kind: \"password\"; readonly password: Uint8Array }\n | HostBackupPasskey\n | {\n readonly kind: \"passkey\";\n readonly ceremony: \"kernel\";\n readonly rpId: string;\n readonly rpName: string;\n readonly backupSalt: string;\n };\n\n/**\n * A factor that opens a backup envelope. The `kernel` passkey arm asserts one of the envelope's own\n * credentials.\n */\nexport type BackupUnlockFactor =\n | { readonly kind: \"password\"; readonly password: Uint8Array }\n | HostBackupPasskey\n | {\n readonly kind: \"passkey\";\n readonly ceremony: \"kernel\";\n readonly rpId: string;\n readonly backupSalt: string;\n };\n\nexport const factorInfo: Validator<FactorInfo> = union(\n obj({ kind: literal(\"hardware\"), id: sessionId, createdAt: safeTime }),\n obj({\n kind: literal(\"passkey\"),\n id: sessionId,\n credentialId,\n createdAt: safeTime,\n }),\n obj({ kind: literal(\"password\"), id: sessionId, createdAt: safeTime }),\n);\n\n/**\n * Passkey wallet creation. `host`: the host ran the WebAuthn ceremony and hands over the PRF\n * evidence (web). `kernel`: the kernel runs the platform ceremony itself and nothing secret crosses\n * the channel (React Native). The kernel accepts exactly the shape its platform supports.\n */\nexport type CreateWithPasskeyParams =\n | {\n readonly ceremony: \"host\";\n readonly credentialId: Uint8Array;\n readonly prfWallet: Uint8Array;\n readonly synced: boolean;\n readonly factor?: Factor;\n }\n | {\n readonly ceremony: \"kernel\";\n readonly rpId: string;\n readonly rpName: string;\n readonly name: string;\n readonly walletSalt: string;\n readonly factor?: Factor;\n };\n\nexport type RestoreWithPasskeyParams =\n | {\n readonly ceremony: \"host\";\n readonly credentialId: Uint8Array;\n readonly prfWallet: Uint8Array;\n readonly synced: boolean;\n readonly factor?: Factor;\n }\n | {\n readonly ceremony: \"kernel\";\n readonly rpId: string;\n readonly walletSalt: string;\n readonly factor?: Factor;\n };\n\n// An RP id is a lowercase DNS name; the platform rejects anything its associated domains do not\n// list, so this only bounds the shape.\nconst RP_ID =\n /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/;\nconst label = (max: number): Validator<string> => str(max, /^\\S(?:.*\\S)?$/su);\n\nconst hostEvidence = {\n ceremony: literal(\"host\"),\n credentialId: bytes(1, 1023),\n prfWallet: bytes(32),\n synced: bool,\n factor: opt(factor),\n};\n\nconst createWithPasskeyParams: Validator<CreateWithPasskeyParams> = union(\n obj(hostEvidence),\n obj({\n ceremony: literal(\"kernel\"),\n rpId: str(253, RP_ID),\n rpName: label(64),\n name: label(64),\n walletSalt: label(64),\n factor: opt(factor),\n }),\n);\n\nconst restoreWithPasskeyParams: Validator<RestoreWithPasskeyParams> = union(\n obj(hostEvidence),\n obj({\n ceremony: literal(\"kernel\"),\n rpId: str(253, RP_ID),\n walletSalt: label(64),\n factor: opt(factor),\n }),\n);\n\nconst hostBackupPasskey = obj({\n kind: literal(\"passkey\"),\n ceremony: literal(\"host\"),\n credentialId: bytes(1, 1023),\n prfBackup: bytes(32),\n});\nconst backupPassword = obj({ kind: literal(\"password\"), password: bytes(1, 1024) });\n\nexport const backupFactor: Validator<BackupFactor> = union(\n backupPassword,\n hostBackupPasskey,\n obj({\n kind: literal(\"passkey\"),\n ceremony: literal(\"kernel\"),\n rpId: str(253, RP_ID),\n rpName: label(64),\n backupSalt: label(64),\n }),\n);\n\nexport const backupUnlockFactor: Validator<BackupUnlockFactor> = union(\n backupPassword,\n hostBackupPasskey,\n obj({\n kind: literal(\"passkey\"),\n ceremony: literal(\"kernel\"),\n rpId: str(253, RP_ID),\n backupSalt: label(64),\n }),\n);\n\nexport const walletInfo: Validator<WalletInfo> = obj({\n walletId,\n origin: union(literal(\"passkey\"), literal(\"mnemonic\")),\n words: union(literal(12), literal(15), literal(18), literal(21), literal(24)),\n backup: union(literal(\"none\"), literal(\"passkey\"), literal(\"mnemonic\")),\n createdAt: safeTime,\n});\n\nexport const walletErrorCode: Validator<WalletErrorCode> = union(\n literal(\"locked\"),\n literal(\"cancelled\"),\n literal(\"factor-unavailable\"),\n literal(\"factor-invalidated\"),\n literal(\"wrong-password\"),\n literal(\"wrong-passkey\"),\n literal(\"rate-limited\"),\n literal(\"invalid-input\"),\n literal(\"not-found\"),\n literal(\"already-exists\"),\n literal(\"conflict\"),\n literal(\"unsupported\"),\n literal(\"unavailable\"),\n literal(\"integrity\"),\n literal(\"approval-required\"),\n literal(\"crashed\"),\n);\n\n/**\n * The result of every \"create or import\" wallet command: the new wallet's public info plus the\n * session it opened. Creating a wallet derives no protocol keys — modules add keys separately.\n */\nexport type CreatedResult = {\n readonly wallet: WalletInfo;\n readonly session: string;\n};\n\nconst createdResult: Validator<CreatedResult> = obj({ wallet: walletInfo, session: sessionId });\n\n// `status` itself is a core method, but its result validator composes every module's status\n// section — it is wired in protocol/index.ts, not here.\nexport const CORE_METHODS: {\n readonly \"vault.unlock\": MethodSpec<{ readonly factor: Factor }, { readonly session: string }>;\n readonly \"vault.reset\": MethodSpec<NullValue, NullValue>;\n readonly \"vault.addFactor\": MethodSpec<\n { readonly verify: Factor; readonly factor: Factor },\n FactorInfo\n >;\n readonly \"vault.removeFactor\": MethodSpec<\n { readonly verify: Factor; readonly id: string },\n NullValue\n >;\n readonly \"session.touch\": MethodSpec<NullValue, NullValue>;\n readonly \"wallet.createWithPasskey\": MethodSpec<CreateWithPasskeyParams, CreatedResult>;\n readonly \"wallet.restoreWithPasskey\": MethodSpec<RestoreWithPasskeyParams, CreatedResult>;\n readonly \"wallet.createMnemonic\": MethodSpec<\n { readonly words: 12 | 24; readonly factor?: Factor },\n { readonly draft: string; readonly words: Uint8Array; readonly quiz: ReadonlyArray<number> }\n >;\n readonly \"wallet.confirmMnemonic\": MethodSpec<\n { readonly draft: string; readonly answers: ReadonlyArray<Uint8Array> },\n CreatedResult\n >;\n readonly \"wallet.discardMnemonic\": MethodSpec<{ readonly draft: string }, NullValue>;\n readonly \"backup.enable\": MethodSpec<\n {\n readonly verify: Factor;\n readonly factors: ReadonlyArray<BackupFactor>;\n },\n NullValue\n >;\n readonly \"backup.update\": MethodSpec<NullValue, { readonly envelope: string }>;\n readonly \"backup.disable\": MethodSpec<NullValue, NullValue>;\n readonly \"backup.restore\": MethodSpec<\n {\n readonly envelope: string;\n readonly backupFactor: BackupUnlockFactor;\n readonly factor?: Factor;\n },\n { readonly wallets: ReadonlyArray<WalletInfo>; readonly session: string }\n >;\n readonly \"wallet.importMnemonic\": MethodSpec<\n { readonly mnemonic: Uint8Array; readonly factor?: Factor },\n CreatedResult\n >;\n readonly \"wallet.exportMnemonic\": MethodSpec<\n { readonly verify: Factor; readonly walletId: string },\n Uint8Array\n >;\n readonly \"wallet.delete\": MethodSpec<\n { readonly verify: Factor; readonly walletId: string },\n NullValue\n >;\n readonly \"dataKeys.get\": MethodSpec<{ readonly purpose: string }, Uint8Array>;\n} = {\n \"session.touch\": {\n session: true,\n presence: true,\n params: nullValue,\n result: nullValue,\n },\n \"vault.unlock\": {\n session: false,\n presence: true,\n params: obj({ factor }),\n result: obj({ session: sessionId }),\n },\n \"vault.reset\": { session: false, presence: false, params: nullValue, result: nullValue },\n \"vault.addFactor\": {\n session: true,\n presence: true,\n params: obj({ verify: factor, factor }),\n result: factorInfo,\n },\n \"vault.removeFactor\": {\n session: true,\n presence: true,\n params: obj({ verify: factor, id: sessionId }),\n result: nullValue,\n },\n \"wallet.createWithPasskey\": {\n session: false,\n presence: true,\n params: createWithPasskeyParams,\n result: createdResult,\n },\n \"wallet.restoreWithPasskey\": {\n session: false,\n presence: true,\n params: restoreWithPasskeyParams,\n result: createdResult,\n },\n \"wallet.createMnemonic\": {\n session: false,\n presence: true,\n params: obj({ words: union(literal(12), literal(24)), factor: opt(factor) }),\n result: obj({\n draft: draftId,\n words: bytes(16, 1024),\n quiz: arr(int(0, 23), 3, 3),\n }),\n },\n \"wallet.confirmMnemonic\": {\n session: false,\n presence: true,\n params: obj({ draft: draftId, answers: arr(bytes(1, 64), 3, 3) }),\n result: createdResult,\n },\n \"wallet.discardMnemonic\": {\n session: false,\n presence: false,\n params: obj({ draft: draftId }),\n result: nullValue,\n },\n \"backup.enable\": {\n session: true,\n presence: true,\n params: obj({ verify: factor, factors: arr(backupFactor, 5, 1) }),\n result: nullValue,\n },\n \"backup.update\": {\n session: true,\n presence: false,\n params: nullValue,\n result: obj({ envelope: str(4_000_000) }),\n },\n \"backup.disable\": {\n session: true,\n presence: true,\n params: nullValue,\n result: nullValue,\n },\n \"backup.restore\": {\n session: false,\n presence: true,\n params: obj({\n envelope: str(4_000_000),\n backupFactor: backupUnlockFactor,\n factor: opt(factor),\n }),\n result: obj({ wallets: arr(walletInfo, 1000), session: sessionId }),\n },\n \"wallet.importMnemonic\": {\n session: false,\n presence: true,\n params: obj({ mnemonic: bytes(1, 1024), factor: opt(factor) }),\n result: createdResult,\n },\n \"wallet.exportMnemonic\": {\n session: true,\n presence: true,\n params: obj({ verify: factor, walletId }),\n result: bytes(16, 1024),\n },\n \"wallet.delete\": {\n session: true,\n presence: true,\n params: obj({ verify: factor, walletId }),\n result: nullValue,\n },\n \"dataKeys.get\": {\n session: true,\n presence: false,\n params: obj({ purpose: str(32, /^[a-z0-9-]{1,32}$/) }),\n result: bytes(32),\n },\n};\n"],"mappings":";AAOA,IAAa,kBAAb,cAAqC,MAAM;CACzC,OAAgB;AAClB;AAIA,SAAS,OAAc;CACrB,MAAM,IAAI,gBAAgB;AAC5B;AAEA,SAAgB,QACd,UACc;CACd,QAAQ,UAAU;EAChB,IAAI,UAAU,UACZ,KAAK;EAEP,OAAO;CACT;AACF;AAEA,MAAa,YAAkC,QAAQ,IAAI;AAC3D,MAAa,Q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E;CAClB;AACF"}
|
package/dist/host.d.mts
CHANGED
|
@@ -1,11 +1,16 @@
|
|
|
1
|
-
import { p as PasskeyConfig, v as Wallet } from "./types-
|
|
2
|
-
import {
|
|
1
|
+
import { p as PasskeyConfig, v as Wallet } from "./types-BD9fuAUj.mjs";
|
|
2
|
+
import { T as ProtocolValue } from "./chains-D_jfwTPT.mjs";
|
|
3
3
|
//#region src/channel.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Why the kernel port ended: a fault in the enclave/transport, or a deliberate host-side lock
|
|
6
|
+
* triggered by the platform (native background expiry — W7).
|
|
7
|
+
*/
|
|
8
|
+
type PortExit = "crashed" | "background";
|
|
4
9
|
/** The host packages' side of the kernel channel (worker, JSI runtime, in-process test port). */
|
|
5
10
|
type MainPort = {
|
|
6
11
|
readonly post: (message: ProtocolValue, transfer: ArrayBuffer[]) => void;
|
|
7
12
|
readonly listen: (handler: (message: unknown) => void) => () => void;
|
|
8
|
-
readonly onExit: (handler: () => void) => () => void;
|
|
13
|
+
readonly onExit: (handler: (reason: PortExit) => void) => () => void;
|
|
9
14
|
readonly terminate: () => void;
|
|
10
15
|
};
|
|
11
16
|
/** Schedules `fn` after `delayMs` and returns a cancel function — injected by the host package. */
|
|
@@ -44,10 +49,18 @@ type PasskeyCeremony = {
|
|
|
44
49
|
readonly salts: PrfSalts;
|
|
45
50
|
}) => Promise<PrfResult>;
|
|
46
51
|
};
|
|
52
|
+
/**
|
|
53
|
+
* Which vault factors a host offers: `hardware` (React Native — the platform keystore is the only
|
|
54
|
+
* factor, and omitted factors mean it) or `software` (web/node — passkey and password). The kernel
|
|
55
|
+
* enforces the same rule; resolving here keeps a doomed request from firing a ceremony.
|
|
56
|
+
*/
|
|
57
|
+
type FactorMode = "hardware" | "software";
|
|
47
58
|
//#endregion
|
|
48
59
|
//#region src/wallet.d.ts
|
|
49
60
|
type ConnectOptions = {
|
|
50
61
|
readonly spawn: () => MainPort;
|
|
62
|
+
/** Fixed by the host entry: `hardware` on React Native, `software` on web and node. */
|
|
63
|
+
readonly factors: FactorMode;
|
|
51
64
|
readonly passkey: PasskeyConfig;
|
|
52
65
|
readonly ceremony: PasskeyCeremony | undefined;
|
|
53
66
|
/** Timer source injected by the host package (globalThis timers on web/node). */
|
|
@@ -66,5 +79,5 @@ type ConnectOptions = {
|
|
|
66
79
|
*/
|
|
67
80
|
export declare function connectKernel(options: ConnectOptions): Promise<Wallet>;
|
|
68
81
|
//#endregion
|
|
69
|
-
export type { ConnectOptions, MainPort, PasskeyCeremony, PrfResult, PrfSalts, SetTimer };
|
|
82
|
+
export type { ConnectOptions, FactorMode, MainPort, PasskeyCeremony, PortExit, PrfResult, PrfSalts, SetTimer };
|
|
70
83
|
//# sourceMappingURL=host.d.mts.map
|
package/dist/host.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { WalletError } from "./types.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { t as Channel } from "./channel-ChYtMklb.mjs";
|
|
3
3
|
import { n as registerInternals } from "./internal-LBHal13j.mjs";
|
|
4
|
+
import { a as passkeyName, c as resolveBackupUnlockFactor, d as vaultSaltBytes, f as walletSaltBytes, i as defaultUnlockFactor, l as resolveFactor, m as wireSecretText, n as PASSKEY_PURPOSE_VAULT, o as requireCeremony, p as wireBytes, r as PASSKEY_PURPOSE_WALLET, s as resolveBackupFactor, t as SingleUseSecret, u as resolveInitialFactor } from "./secret-BiyX0Hus.mjs";
|
|
4
5
|
//#region src/wallet.ts
|
|
5
6
|
/**
|
|
6
7
|
* The host-facing `Wallet` (design/entry.mdx "API"): snapshot state, the core API groups, and the
|
|
@@ -22,6 +23,7 @@ function deepEqual(a, b) {
|
|
|
22
23
|
}
|
|
23
24
|
var KernelWallet = class KernelWallet {
|
|
24
25
|
channel;
|
|
26
|
+
factorMode;
|
|
25
27
|
passkeyCfg;
|
|
26
28
|
ceremony;
|
|
27
29
|
setTimer;
|
|
@@ -36,6 +38,7 @@ var KernelWallet = class KernelWallet {
|
|
|
36
38
|
snapshotValue;
|
|
37
39
|
listeners = /* @__PURE__ */ new Set();
|
|
38
40
|
constructor(options) {
|
|
41
|
+
this.factorMode = options.factors;
|
|
39
42
|
this.passkeyCfg = options.passkey;
|
|
40
43
|
this.ceremony = options.ceremony;
|
|
41
44
|
this.setTimer = options.setTimer;
|
|
@@ -55,7 +58,7 @@ var KernelWallet = class KernelWallet {
|
|
|
55
58
|
},
|
|
56
59
|
onLocked: (reason) => {
|
|
57
60
|
this.lockReason = reason;
|
|
58
|
-
this.
|
|
61
|
+
this.markLocked();
|
|
59
62
|
},
|
|
60
63
|
onCrashed: () => {
|
|
61
64
|
this.lockReason = "crashed";
|
|
@@ -147,6 +150,7 @@ var KernelWallet = class KernelWallet {
|
|
|
147
150
|
};
|
|
148
151
|
get factorSource() {
|
|
149
152
|
return {
|
|
153
|
+
mode: this.factorMode,
|
|
150
154
|
passkey: this.passkeyCfg,
|
|
151
155
|
ceremony: this.ceremony,
|
|
152
156
|
factors: () => this.snapshotValue.factors
|
|
@@ -172,7 +176,7 @@ var KernelWallet = class KernelWallet {
|
|
|
172
176
|
if (factor !== void 0) throw new WalletError("invalid-input", "the vault is already initialized");
|
|
173
177
|
return;
|
|
174
178
|
}
|
|
175
|
-
if (factor === void 0) throw new WalletError("invalid-input", "an initial factor is required");
|
|
179
|
+
if (factor === void 0 && this.factorMode === "software") throw new WalletError("invalid-input", "an initial factor is required");
|
|
176
180
|
return resolveInitialFactor(this.factorSource, factor, transfer);
|
|
177
181
|
}
|
|
178
182
|
sessionOf(result) {
|
|
@@ -182,7 +186,7 @@ var KernelWallet = class KernelWallet {
|
|
|
182
186
|
vault = {
|
|
183
187
|
unlock: async (factor) => this.withVerifying(async () => {
|
|
184
188
|
const transfer = [];
|
|
185
|
-
const wire = await resolveFactor(this.factorSource, factor ??
|
|
189
|
+
const wire = await resolveFactor(this.factorSource, factor ?? defaultUnlockFactor(this.factorSource), transfer);
|
|
186
190
|
const result = await this.channel.call("vault.unlock", { factor: wire }, transfer);
|
|
187
191
|
this.sessionOf(result);
|
|
188
192
|
}),
|
|
@@ -213,10 +217,22 @@ var KernelWallet = class KernelWallet {
|
|
|
213
217
|
};
|
|
214
218
|
wallets = {
|
|
215
219
|
createWithPasskey: async (options) => this.withVerifying(async () => {
|
|
216
|
-
const ceremony = requireCeremony(this.factorSource);
|
|
217
220
|
const name = passkeyName(options.name);
|
|
218
221
|
const transfer = [];
|
|
219
|
-
|
|
222
|
+
if (this.factorMode === "hardware") {
|
|
223
|
+
const factor = await this.createFactorParam(options.factor, transfer);
|
|
224
|
+
const created = await this.channel.call("wallet.createWithPasskey", {
|
|
225
|
+
ceremony: "kernel",
|
|
226
|
+
rpId: this.passkeyCfg.rpId,
|
|
227
|
+
rpName: this.passkeyCfg.rpName,
|
|
228
|
+
name,
|
|
229
|
+
walletSalt: this.passkeyCfg.walletSalt,
|
|
230
|
+
...factor === void 0 ? {} : { factor }
|
|
231
|
+
}, transfer);
|
|
232
|
+
this.sessionOf(created);
|
|
233
|
+
return created.wallet;
|
|
234
|
+
}
|
|
235
|
+
const result = await requireCeremony(this.factorSource).create({
|
|
220
236
|
purpose: "wallet",
|
|
221
237
|
name,
|
|
222
238
|
salts: {
|
|
@@ -230,6 +246,7 @@ var KernelWallet = class KernelWallet {
|
|
|
230
246
|
result.second?.fill(0);
|
|
231
247
|
} else factor = await resolveInitialFactor(this.factorSource, options.factor, transfer, result);
|
|
232
248
|
const created = await this.channel.call("wallet.createWithPasskey", {
|
|
249
|
+
ceremony: "host",
|
|
233
250
|
credentialId: wireBytes(result.credentialId, transfer),
|
|
234
251
|
prfWallet: wireBytes(result.first, transfer, true),
|
|
235
252
|
synced: result.synced,
|
|
@@ -239,9 +256,19 @@ var KernelWallet = class KernelWallet {
|
|
|
239
256
|
return created.wallet;
|
|
240
257
|
}),
|
|
241
258
|
restoreWithPasskey: async (options) => this.withVerifying(async () => {
|
|
242
|
-
const ceremony = requireCeremony(this.factorSource);
|
|
243
259
|
const transfer = [];
|
|
244
|
-
|
|
260
|
+
if (this.factorMode === "hardware") {
|
|
261
|
+
const factor = await this.createFactorParam(options?.factor, transfer);
|
|
262
|
+
const created = await this.channel.call("wallet.restoreWithPasskey", {
|
|
263
|
+
ceremony: "kernel",
|
|
264
|
+
rpId: this.passkeyCfg.rpId,
|
|
265
|
+
walletSalt: this.passkeyCfg.walletSalt,
|
|
266
|
+
...factor === void 0 ? {} : { factor }
|
|
267
|
+
}, transfer);
|
|
268
|
+
this.sessionOf(created);
|
|
269
|
+
return created.wallet;
|
|
270
|
+
}
|
|
271
|
+
const result = await requireCeremony(this.factorSource).assert({ salts: {
|
|
245
272
|
first: walletSaltBytes(this.factorSource),
|
|
246
273
|
second: vaultSaltBytes(this.factorSource)
|
|
247
274
|
} });
|
|
@@ -256,6 +283,7 @@ var KernelWallet = class KernelWallet {
|
|
|
256
283
|
result.second?.fill(0);
|
|
257
284
|
} else factor = await resolveInitialFactor(this.factorSource, options?.factor, transfer, result);
|
|
258
285
|
const created = await this.channel.call("wallet.restoreWithPasskey", {
|
|
286
|
+
ceremony: "host",
|
|
259
287
|
credentialId: wireBytes(result.credentialId, transfer),
|
|
260
288
|
prfWallet: wireBytes(result.first, transfer, true),
|
|
261
289
|
synced: result.synced,
|
|
@@ -338,7 +366,7 @@ var KernelWallet = class KernelWallet {
|
|
|
338
366
|
},
|
|
339
367
|
restore: async (options) => this.withVerifying(async () => {
|
|
340
368
|
const transfer = [];
|
|
341
|
-
const backupFactor = await
|
|
369
|
+
const backupFactor = await resolveBackupUnlockFactor(this.factorSource, options.backupFactor, transfer);
|
|
342
370
|
const factor = await this.createFactorParam(options.factor, transfer);
|
|
343
371
|
const result = await this.channel.call("backup.restore", {
|
|
344
372
|
envelope: options.envelope,
|