@qntx/wallet 0.5.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/chains-CuKVAJMN.d.mts +333 -0
  2. package/dist/chains.d.mts +2 -4
  3. package/dist/chains.mjs +3 -4
  4. package/dist/{channel-ChYtMklb.mjs → channel-Iiz28m-e.mjs} +6 -7
  5. package/dist/{channel-ChYtMklb.mjs.map → channel-Iiz28m-e.mjs.map} +1 -1
  6. package/dist/{core-Dmz5SbyJ.mjs → core-Cq5h9X0X.mjs} +11 -6
  7. package/dist/core-Cq5h9X0X.mjs.map +1 -0
  8. package/dist/host.d.mts +2 -8
  9. package/dist/host.mjs +18 -23
  10. package/dist/host.mjs.map +1 -1
  11. package/dist/{chains-D_jfwTPT.d.mts → index-CIZzbqqv.d.mts} +42 -402
  12. package/dist/index.d.mts +2 -6
  13. package/dist/index.mjs +3 -6
  14. package/dist/index.mjs.map +1 -1
  15. package/dist/{internal-LBHal13j.mjs → internal-CAKfHjIg.mjs} +2 -3
  16. package/dist/{internal-LBHal13j.mjs.map → internal-CAKfHjIg.mjs.map} +1 -1
  17. package/dist/nostr.d.mts +19 -22
  18. package/dist/nostr.mjs +59 -51
  19. package/dist/nostr.mjs.map +1 -1
  20. package/dist/{protocol-DvzlUKB8.mjs → protocol-DbpLncEB.mjs} +81 -117
  21. package/dist/protocol-DbpLncEB.mjs.map +1 -0
  22. package/dist/protocol.d.mts +4 -3
  23. package/dist/protocol.mjs +2 -2
  24. package/dist/{secret-BiyX0Hus.mjs → secret-Dz_ItVt6.mjs} +3 -5
  25. package/dist/{secret-BiyX0Hus.mjs.map → secret-Dz_ItVt6.mjs.map} +1 -1
  26. package/dist/spark.d.mts +2 -6
  27. package/dist/spark.mjs +4 -7
  28. package/dist/spark.mjs.map +1 -1
  29. package/dist/{types-BD9fuAUj.d.mts → types-BgFsXgyI.d.mts} +5 -19
  30. package/dist/types.d.mts +1 -1
  31. package/dist/types.mjs +1 -2
  32. package/dist/types.mjs.map +1 -1
  33. package/package.json +4 -4
  34. package/dist/core-Dmz5SbyJ.mjs.map +0 -1
  35. package/dist/protocol-DvzlUKB8.mjs.map +0 -1
@@ -0,0 +1,333 @@
1
+ import { b as WalletErrorCode, s as FactorInfo, x as WalletInfo } from "./types-BgFsXgyI.mjs";
2
+ /**
3
+ * Strict validator combinators for the secret-area protocol. Both sides share them: the kernel
4
+ * validates every request, the host validates every response. Anything that does not match is a
5
+ * `ValidationError` — never a partially-accepted value.
6
+ */
7
+ declare class ValidationError extends Error {
8
+ name: string;
9
+ }
10
+ type Validator<T> = (value: unknown) => T;
11
+ type NullValue = null;
12
+ declare function literal<T extends NullValue | boolean | number | string>(expected: T): Validator<T>;
13
+ declare const nullValue: Validator<NullValue>;
14
+ declare const bool: Validator<boolean>;
15
+ declare function int(min: number, max: number): Validator<number>;
16
+ declare function str(max: number, pattern?: RegExp): Validator<string>;
17
+ declare function bytes(min: number, max?: number): Validator<Uint8Array>;
18
+ declare function arr<T>(item: Validator<T>, max: number, min?: number): Validator<ReadonlyArray<T>>;
19
+ declare class Opt<T> {
20
+ readonly validator: Validator<T>;
21
+ constructor(validator: Validator<T>);
22
+ }
23
+ declare function opt<T>(validator: Validator<T>): Opt<T>;
24
+ type Field = Validator<unknown> | Opt<unknown>;
25
+ type Shape = Record<string, Field>;
26
+ type RequiredKeys<S extends Shape> = { readonly [K in keyof S as S[K] extends Opt<unknown> ? never : K]: S[K] extends Validator<infer T> ? T : never; };
27
+ type OptionalKeys<S extends Shape> = { readonly [K in keyof S as S[K] extends Opt<unknown> ? K : never]?: S[K] extends Opt<infer T> ? T : never; };
28
+ type ShapeResult<S extends Shape> = RequiredKeys<S> & OptionalKeys<S>;
29
+ /** Exact key set: required keys present, optional keys allowed, nothing else. */
30
+ declare function obj<S extends Shape>(shape: S): Validator<ShapeResult<S>>;
31
+ /**
32
+ * A `Record<K, V>` wire value: plain objects only, every key checked by `key`, every value by
33
+ * `value`, at most `max` entries. Prototype-polluting keys are rejected outright — a validated
34
+ * record must be safe to copy key-by-key.
35
+ */
36
+ declare function record<K extends string, V>(key: Validator<K>, value: Validator<V>, max: number): Validator<Record<K, V>>;
37
+ /** Tries each branch in order; the first match wins. */
38
+ declare function union<Vs extends ReadonlyArray<Validator<unknown>>>(...branches: Vs): Validator<ReturnType<Vs[number]>>;
39
+ /** Validates a value and returns it, or undefined on a shape mismatch. */
40
+ declare function validate<T>(validator: Validator<T>, value: unknown): T | undefined;
41
+ type MethodSpec<P, R> = {
42
+ readonly session: boolean;
43
+ /** Whether a successful call refreshes the idle timer — presence-bearing methods only. */
44
+ readonly presence: boolean;
45
+ readonly params: Validator<P>;
46
+ readonly result: Validator<R>;
47
+ };
48
+ /**
49
+ * Vault factor material on the wire. `hardware` carries nothing: the kernel runs the platform
50
+ * keystore ceremony itself, so the main runtime never touches the KEK.
51
+ */
52
+ type Factor = {
53
+ readonly kind: "hardware";
54
+ } | {
55
+ readonly kind: "password";
56
+ readonly password: Uint8Array;
57
+ } | {
58
+ readonly kind: "passkey";
59
+ readonly credentialId: Uint8Array;
60
+ readonly prf: Uint8Array;
61
+ };
62
+ /** A host-run backup passkey ceremony's evidence: the PRF over `backupSalt` (web). */
63
+ type HostBackupPasskey = {
64
+ readonly kind: "passkey";
65
+ readonly ceremony: "host";
66
+ readonly credentialId: Uint8Array;
67
+ readonly prfBackup: Uint8Array;
68
+ };
69
+ /**
70
+ * A factor that seals a new backup key. On React Native the kernel registers a protection
71
+ * credential (`kernel`) itself and names it; on the web the host hands over its ceremony's
72
+ * evidence.
73
+ */
74
+ type BackupFactor = {
75
+ readonly kind: "password";
76
+ readonly password: Uint8Array;
77
+ } | HostBackupPasskey | {
78
+ readonly kind: "passkey";
79
+ readonly ceremony: "kernel";
80
+ readonly rpId: string;
81
+ readonly rpName: string;
82
+ readonly backupSalt: string;
83
+ };
84
+ /**
85
+ * A factor that opens a backup envelope. The `kernel` passkey arm asserts one of the envelope's own
86
+ * credentials.
87
+ */
88
+ type BackupUnlockFactor = {
89
+ readonly kind: "password";
90
+ readonly password: Uint8Array;
91
+ } | HostBackupPasskey | {
92
+ readonly kind: "passkey";
93
+ readonly ceremony: "kernel";
94
+ readonly rpId: string;
95
+ readonly backupSalt: string;
96
+ };
97
+ /**
98
+ * Passkey wallet creation. `host`: the host ran the WebAuthn ceremony and hands over the PRF
99
+ * evidence (web). `kernel`: the kernel runs the platform ceremony itself and nothing secret crosses
100
+ * the channel (React Native). The kernel accepts exactly the shape its platform supports.
101
+ */
102
+ type CreateWithPasskeyParams = {
103
+ readonly ceremony: "host";
104
+ readonly credentialId: Uint8Array;
105
+ readonly prfWallet: Uint8Array;
106
+ readonly synced: boolean;
107
+ readonly factor?: Factor;
108
+ } | {
109
+ readonly ceremony: "kernel";
110
+ readonly rpId: string;
111
+ readonly rpName: string;
112
+ readonly name: string;
113
+ readonly walletSalt: string;
114
+ readonly factor?: Factor;
115
+ };
116
+ type RestoreWithPasskeyParams = {
117
+ readonly ceremony: "host";
118
+ readonly credentialId: Uint8Array;
119
+ readonly prfWallet: Uint8Array;
120
+ readonly synced: boolean;
121
+ readonly factor?: Factor;
122
+ } | {
123
+ readonly ceremony: "kernel";
124
+ readonly rpId: string;
125
+ readonly walletSalt: string;
126
+ readonly factor?: Factor;
127
+ };
128
+ declare const walletErrorCode: Validator<WalletErrorCode>;
129
+ /**
130
+ * The result of every "create or import" wallet command: the new wallet's public info plus the
131
+ * session it opened. Creating a wallet derives no protocol keys — modules add keys separately.
132
+ */
133
+ type CreatedResult = {
134
+ readonly wallet: WalletInfo;
135
+ readonly session: string;
136
+ };
137
+ declare const CORE_METHODS: {
138
+ readonly "vault.unlock": MethodSpec<{
139
+ readonly factor: Factor;
140
+ }, {
141
+ readonly session: string;
142
+ }>;
143
+ readonly "vault.reset": MethodSpec<NullValue, NullValue>;
144
+ readonly "vault.addFactor": MethodSpec<{
145
+ readonly verify: Factor;
146
+ readonly factor: Factor;
147
+ }, FactorInfo>;
148
+ readonly "vault.removeFactor": MethodSpec<{
149
+ readonly verify: Factor;
150
+ readonly id: string;
151
+ }, NullValue>;
152
+ readonly "session.touch": MethodSpec<NullValue, NullValue>;
153
+ readonly "wallet.createWithPasskey": MethodSpec<CreateWithPasskeyParams, CreatedResult>;
154
+ readonly "wallet.restoreWithPasskey": MethodSpec<RestoreWithPasskeyParams, CreatedResult>;
155
+ readonly "wallet.createMnemonic": MethodSpec<{
156
+ readonly words: 12 | 24;
157
+ readonly factor?: Factor;
158
+ }, {
159
+ readonly draft: string;
160
+ readonly words: Uint8Array;
161
+ readonly quiz: ReadonlyArray<number>;
162
+ }>;
163
+ readonly "wallet.confirmMnemonic": MethodSpec<{
164
+ readonly draft: string;
165
+ readonly answers: ReadonlyArray<Uint8Array>;
166
+ }, CreatedResult>;
167
+ readonly "wallet.discardMnemonic": MethodSpec<{
168
+ readonly draft: string;
169
+ }, NullValue>;
170
+ readonly "backup.enable": MethodSpec<{
171
+ readonly verify: Factor;
172
+ readonly factors: ReadonlyArray<BackupFactor>;
173
+ }, NullValue>;
174
+ readonly "backup.update": MethodSpec<NullValue, {
175
+ readonly envelope: string;
176
+ }>;
177
+ readonly "backup.disable": MethodSpec<NullValue, NullValue>;
178
+ readonly "backup.restore": MethodSpec<{
179
+ readonly envelope: string;
180
+ readonly backupFactor: BackupUnlockFactor;
181
+ readonly factor?: Factor;
182
+ }, {
183
+ readonly wallets: ReadonlyArray<WalletInfo>;
184
+ readonly session: string;
185
+ }>;
186
+ readonly "wallet.importMnemonic": MethodSpec<{
187
+ readonly mnemonic: Uint8Array;
188
+ readonly factor?: Factor;
189
+ }, CreatedResult>;
190
+ readonly "wallet.exportMnemonic": MethodSpec<{
191
+ readonly verify: Factor;
192
+ readonly walletId: string;
193
+ }, Uint8Array>;
194
+ readonly "wallet.delete": MethodSpec<{
195
+ readonly verify: Factor;
196
+ readonly walletId: string;
197
+ }, NullValue>;
198
+ readonly "dataKeys.get": MethodSpec<{
199
+ readonly purpose: string;
200
+ }, Uint8Array>;
201
+ };
202
+ type ChainTemplate = "evm.bip44" | "solana.bip44-change" | "btc.bip44" | "btc.bip49" | "btc.bip84" | "btc.bip86";
203
+ type ChainAccountsParams = {
204
+ readonly walletId: string;
205
+ readonly groupIndex: number;
206
+ readonly template: ChainTemplate;
207
+ readonly network: string;
208
+ };
209
+ type ChainAccount = {
210
+ readonly template: "evm.bip44";
211
+ readonly network: string;
212
+ readonly address: string;
213
+ } | {
214
+ readonly template: "solana.bip44-change";
215
+ readonly network: string;
216
+ readonly address: string;
217
+ } | {
218
+ readonly template: "btc.bip44" | "btc.bip49" | "btc.bip84" | "btc.bip86";
219
+ readonly network: string;
220
+ readonly xpub: string;
221
+ /** Master-key fingerprint as 8 lowercase hex chars (PSBT bip32Derivation). */
222
+ readonly fingerprint: string;
223
+ /** Account derivation path, e.g. "m/84'/0'/0'". */
224
+ readonly path: string;
225
+ };
226
+ type AccountRef = {
227
+ readonly kind: "hd";
228
+ readonly walletId: string;
229
+ readonly groupIndex: number;
230
+ readonly template: ChainTemplate;
231
+ } | {
232
+ readonly kind: "imported";
233
+ readonly keyId: string;
234
+ readonly family: "evm" | "solana" | "bitcoin";
235
+ };
236
+ type EvmAccessListEntryWire = {
237
+ readonly address: string;
238
+ readonly storageKeys: ReadonlyArray<string>;
239
+ };
240
+ type EvmTransactionBase = {
241
+ readonly chainId: number;
242
+ readonly nonce: number;
243
+ readonly gas: string;
244
+ readonly value: string;
245
+ readonly data: string;
246
+ readonly to?: string;
247
+ };
248
+ type EvmTransactionWire = (EvmTransactionBase & {
249
+ readonly type: "legacy";
250
+ readonly gasPrice: string;
251
+ }) | (EvmTransactionBase & {
252
+ readonly type: "eip2930";
253
+ readonly gasPrice: string;
254
+ readonly accessList: ReadonlyArray<EvmAccessListEntryWire>;
255
+ }) | (EvmTransactionBase & {
256
+ readonly type: "eip1559";
257
+ readonly maxFeePerGas: string;
258
+ readonly maxPriorityFeePerGas: string;
259
+ readonly accessList: ReadonlyArray<EvmAccessListEntryWire>;
260
+ });
261
+ /** `chain.sign`'s request — the wire mirror of @qntx/wallet-chains `SignRequest`. */
262
+ type ChainSignRequest = {
263
+ readonly kind: "evm.transaction";
264
+ readonly network: string;
265
+ readonly account: AccountRef;
266
+ readonly tx: EvmTransactionWire;
267
+ } | {
268
+ readonly kind: "evm.personal-message";
269
+ readonly network: string;
270
+ readonly account: AccountRef;
271
+ readonly message: Uint8Array;
272
+ } | {
273
+ readonly kind: "evm.typed-data";
274
+ readonly network: string;
275
+ readonly account: AccountRef;
276
+ readonly typedData: string;
277
+ } | {
278
+ readonly kind: "solana.transaction";
279
+ readonly network: string;
280
+ readonly account: AccountRef;
281
+ readonly message: Uint8Array;
282
+ readonly lookupTables?: ReadonlyArray<{
283
+ readonly address: string;
284
+ readonly addresses: ReadonlyArray<string>;
285
+ }>;
286
+ } | {
287
+ readonly kind: "solana.message";
288
+ readonly network: string;
289
+ readonly account: AccountRef;
290
+ readonly message: Uint8Array;
291
+ readonly format: "raw";
292
+ } | {
293
+ readonly kind: "bitcoin.psbt";
294
+ readonly network: string;
295
+ readonly account: AccountRef;
296
+ readonly psbt: Uint8Array;
297
+ readonly sign: ReadonlyArray<number>;
298
+ } | {
299
+ readonly kind: "bitcoin.message";
300
+ readonly network: string;
301
+ readonly account: AccountRef;
302
+ readonly address: string;
303
+ readonly message: string;
304
+ readonly format: "bip322-simple" | "legacy";
305
+ readonly change: 0 | 1;
306
+ readonly index: number;
307
+ };
308
+ type ChainSignResult = {
309
+ readonly kind: "evm.transaction";
310
+ readonly signedTransaction: Uint8Array;
311
+ } | {
312
+ readonly kind: "evm.personal-message" | "evm.typed-data";
313
+ readonly signature: Uint8Array;
314
+ } | {
315
+ readonly kind: "solana.transaction" | "solana.message";
316
+ readonly signature: Uint8Array;
317
+ } | {
318
+ readonly kind: "bitcoin.psbt";
319
+ readonly signedPsbt: Uint8Array;
320
+ } | {
321
+ readonly kind: "bitcoin.message";
322
+ readonly signature: string;
323
+ };
324
+ type ChainSignParams = {
325
+ readonly request: ChainSignRequest;
326
+ readonly verify: Factor;
327
+ };
328
+ declare const CHAINS_METHODS: {
329
+ readonly "wallet.accounts": MethodSpec<ChainAccountsParams, ChainAccount>;
330
+ readonly "chain.sign": MethodSpec<ChainSignParams, ChainSignResult>;
331
+ };
332
+ export { validate as A, literal as C, record as D, opt as E, str as O, int as S, obj as T, ValidationError as _, ChainSignResult as a, bool as b, BackupUnlockFactor as c, CreatedResult as d, Factor as f, NullValue as g, walletErrorCode as h, ChainSignRequest as i, union as k, CORE_METHODS as l, RestoreWithPasskeyParams as m, ChainAccount as n, ChainTemplate as o, MethodSpec as p, ChainAccountsParams as r, BackupFactor as s, CHAINS_METHODS as t, CreateWithPasskeyParams as u, Validator as v, nullValue as w, bytes as x, arr as y };
333
+ //# sourceMappingURL=chains-CuKVAJMN.d.mts.map
package/dist/chains.d.mts CHANGED
@@ -1,6 +1,5 @@
1
- import { h as UnlockFactor, v as Wallet } from "./types-BD9fuAUj.mjs";
2
- import { a as ChainSignResult, i as ChainSignRequest, n as ChainAccount, o as ChainTemplate, r as ChainAccountsParams } from "./chains-D_jfwTPT.mjs";
3
- //#region src/chains/index.d.ts
1
+ import { h as UnlockFactor, v as Wallet } from "./types-BgFsXgyI.mjs";
2
+ import { a as ChainSignResult, i as ChainSignRequest, n as ChainAccount, o as ChainTemplate, r as ChainAccountsParams } from "./chains-CuKVAJMN.mjs";
4
3
  export type ChainsApi = {
5
4
  readonly account: (params: ChainAccountsParams) => Promise<ChainAccount>;
6
5
  readonly sign: (params: {
@@ -9,6 +8,5 @@ export type ChainsApi = {
9
8
  }) => Promise<ChainSignResult>;
10
9
  };
11
10
  export declare function chains(wallet: Wallet): ChainsApi;
12
- //#endregion
13
11
  export type { ChainAccount, ChainAccountsParams, ChainSignRequest, ChainSignResult, ChainTemplate };
14
12
  //# sourceMappingURL=chains.d.mts.map
package/dist/chains.mjs CHANGED
@@ -1,9 +1,9 @@
1
- import { n as integrity } from "./channel-ChYtMklb.mjs";
2
- import { t as internalsOf } from "./internal-LBHal13j.mjs";
1
+ import { n as integrity } from "./channel-Iiz28m-e.mjs";
2
+ import { t as internalsOf } from "./internal-CAKfHjIg.mjs";
3
3
  import { bitcoinAddressFromXpub, verifyBitcoinMessage, verifyBitcoinPsbtSignatures } from "@qntx/wallet-chains/bitcoin";
4
4
  import { recoverEvmSigner } from "@qntx/wallet-chains/evm";
5
5
  import { verifySolanaSignature } from "@qntx/wallet-chains/solana";
6
- //#region src/chains/index.ts
6
+ // src/chains/index.ts
7
7
  /**
8
8
  * The chains module of @qntx/wallet: `chains(wallet)` returns the wallet's chain API. `account`
9
9
  * calls the kernel's `wallet.accounts`; `sign` calls `chain.sign` and then verifies the returned
@@ -64,7 +64,6 @@ function chains(wallet) {
64
64
  }
65
65
  return api;
66
66
  }
67
- //#endregion
68
67
  export { chains };
69
68
 
70
69
  //# sourceMappingURL=chains.mjs.map
@@ -1,7 +1,7 @@
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";
1
+ import { h as ValidationError } from "./core-Cq5h9X0X.mjs";
2
+ import { a as isProtocolValue, c as responseError, n as METHODS, o as kernelEvent, s as requestBytes } from "./protocol-DbpLncEB.mjs";
3
3
  import { WalletError } from "./types.mjs";
4
- //#region src/channel.ts
4
+ // src/channel.ts
5
5
  /**
6
6
  * The host side of the kernel channel (design/enclave.mdx "协议与传输"): port lifecycle, respawn,
7
7
  * request/response correlation and wire validation. Internal to the `./host` subpath — reserved for
@@ -222,7 +222,7 @@ var Channel = class {
222
222
  }
223
223
  onResponse(message) {
224
224
  const { id } = message;
225
- if (typeof id !== "number" || !Number.isSafeInteger(id) || message["v"] !== 1) {
225
+ if (typeof id !== "number" || !Number.isSafeInteger(id) || message["v"] !== 2) {
226
226
  this.poison("malformed response envelope");
227
227
  return;
228
228
  }
@@ -270,7 +270,7 @@ var Channel = class {
270
270
  if (this.destroyed || port === void 0) throw new WalletError("locked", "wallet is destroyed");
271
271
  const id = this.nextId++;
272
272
  const message = {
273
- v: 1,
273
+ v: 2,
274
274
  id,
275
275
  method,
276
276
  params
@@ -315,7 +315,6 @@ var Channel = class {
315
315
  this.failPending(new WalletError("locked", "wallet is destroyed"));
316
316
  }
317
317
  };
318
- //#endregion
319
318
  export { integrity as n, Channel as t };
320
319
 
321
- //# sourceMappingURL=channel-ChYtMklb.mjs.map
320
+ //# sourceMappingURL=channel-Iiz28m-e.mjs.map
@@ -1 +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;C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BzE,OAAO,MAjBc,IAAI,SAAkB,SAAS,WAAW;GAC7D,KAAK,QAAQ,IAAI,IAAI;IAAE;IAAQ;IAAS;GAAO,CAAC;GAChD,IAAI,KAAK,aAAa,KAAA,GAEpB,KAAK,YAAY;GAEnB,IAAI;IACF,KAAK,KAAK,SAAS,QAAQ;GAC7B,QAAQ;IACN,KAAK,QAAQ,OAAO,EAAE;IACtB,IAAI,KAAK,UAAU,OAAO,IACxB,KAAK,YAAY;IAEnB,OAAO,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"}
1
+ {"version":3,"file":"channel-Iiz28m-e.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,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AC;CACnE;AACF"}
@@ -1,4 +1,9 @@
1
- //#region src/protocol/validate.ts
1
+ // src/protocol/validate.ts
2
+ /**
3
+ * Strict validator combinators for the secret-area protocol. Both sides share them: the kernel
4
+ * validates every request, the host validates every response. Anything that does not match is a
5
+ * `ValidationError` — never a partially-accepted value.
6
+ */
2
7
  var ValidationError = class extends Error {
3
8
  name = "ValidationError";
4
9
  };
@@ -117,8 +122,7 @@ function validate(validator, value) {
117
122
  throw error;
118
123
  }
119
124
  }
120
- //#endregion
121
- //#region src/protocol/core.ts
125
+ // src/protocol/core.ts
122
126
  const MAX_TEXT = 262144;
123
127
  const MAX_TAGS = 1024;
124
128
  const MAX_TAG_ITEM = 4096;
@@ -130,6 +134,8 @@ const publicKey = str(64, /^[0-9a-f]{64}$/);
130
134
  const credentialId = str(1364, /^[A-Za-z0-9_-]+$/);
131
135
  const safeTime = int(0, Number.MAX_SAFE_INTEGER);
132
136
  const groupIndex = int(0, 2147483647);
137
+ /** Identity indices stop below 2^31 - 1 — the top segment derives the wallet sync key. */
138
+ const identityIndex = int(0, 2147483646);
133
139
  const factor = union(obj({ kind: literal("hardware") }), obj({
134
140
  kind: literal("password"),
135
141
  password: bytes(1, 1024)
@@ -355,7 +361,6 @@ const CORE_METHODS = {
355
361
  result: bytes(32)
356
362
  }
357
363
  };
358
- //#endregion
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 };
364
+ 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, safeTime as d, walletErrorCode as f, arr as g, ValidationError as h, MAX_TAG_ITEM as i, identityIndex 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, publicKey as u, bytes as v, record as w, nullValue as x, int as y };
360
365
 
361
- //# sourceMappingURL=core-Dmz5SbyJ.mjs.map
366
+ //# sourceMappingURL=core-Cq5h9X0X.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core-Cq5h9X0X.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 */\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\n// oxlint-disable-next-line typescript/no-restricted-types -- JSON null is a protocol value\nexport type NullValue = null;\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, 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/** Identity indices stop below 2^31 - 1 — the top segment derives the wallet sync key. */\nexport const identityIndex: Validator<number> = int(0, 0x7ffffffe);\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":";;;;;;AAMA,IAAa,kBAAb,cAAqC,MAAM;CACzC,OAAgB;AAClB;AAIA,SAAS,OAAc;CACrB,MAAM,IAAI,gBAAgB;AAC5B;AAKA,SAAgB,QACd,UACc;CACd,QAAQ,UAAU;EAChB,IAAI,UAAU,UACZ,KAAK;EAEP,OAAO;CACT;AACF;AAEA,MAAa,YAAkC,QAAQ,IAAI;AAC3D,MAAa,QAA4B,UAAU;CACjD,IAAI,OAAO,UAAU,WACnB,KAAK;CAEP,OAAO;AACT;AAEA,SAAgB,IAAI,KAAa,KAAgC;CAC/D,QAAQ,UAAU;EAChB,IAAI,OAAO,UAAU,YA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