@qntx/wallet 0.13.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +145 -22
- package/dist/backup-CLzMs8DP.mjs +51 -0
- package/dist/backup-CLzMs8DP.mjs.map +1 -0
- package/dist/card.d.mts +12 -0
- package/dist/card.mjs +119 -0
- package/dist/card.mjs.map +1 -0
- package/dist/{chains-B-FmFmuV.d.mts → chains-u1M0CWkT.d.mts} +148 -31
- package/dist/chains.d.mts +11 -4
- package/dist/chains.mjs +19 -67
- package/dist/chains.mjs.map +1 -1
- package/dist/{channel-BLwce5hh.mjs → channel-BCZXU3pt.mjs} +105 -44
- package/dist/channel-BCZXU3pt.mjs.map +1 -0
- package/dist/check-C1fUpgva.mjs +193 -0
- package/dist/check-C1fUpgva.mjs.map +1 -0
- package/dist/{core-DaRwkTaV.mjs → core-Cx7p-0nG.mjs} +99 -19
- package/dist/core-Cx7p-0nG.mjs.map +1 -0
- package/dist/hardware-BL6zvhQh.d.mts +107 -0
- package/dist/hardware.d.mts +81 -0
- package/dist/hardware.mjs +446 -0
- package/dist/hardware.mjs.map +1 -0
- package/dist/host.d.mts +27 -19
- package/dist/host.mjs +440 -164
- package/dist/host.mjs.map +1 -1
- package/dist/{index-CEhrd0Pl.d.mts → index-UclKfprm.d.mts} +269 -19
- package/dist/index.d.mts +5 -3
- package/dist/index.mjs +3 -33
- package/dist/{internal-CAKfHjIg.mjs → internal-DwCus_Ws.mjs} +1 -6
- package/dist/internal-DwCus_Ws.mjs.map +1 -0
- package/dist/nostr.d.mts +2 -2
- package/dist/nostr.mjs +14 -14
- package/dist/nostr.mjs.map +1 -1
- package/dist/{protocol-fXHXJguP.mjs → protocol-DLE6lHmP.mjs} +475 -49
- package/dist/protocol-DLE6lHmP.mjs.map +1 -0
- package/dist/protocol.d.mts +5 -4
- package/dist/protocol.mjs +3 -3
- package/dist/secret-CbjbY5-f.mjs +25 -0
- package/dist/secret-CbjbY5-f.mjs.map +1 -0
- package/dist/sessions.d.mts +52 -0
- package/dist/sessions.mjs +71 -0
- package/dist/sessions.mjs.map +1 -0
- package/dist/spark.d.mts +3 -3
- package/dist/spark.mjs +5 -8
- package/dist/spark.mjs.map +1 -1
- package/dist/types-CRnacSqJ.d.mts +390 -0
- package/dist/types.d.mts +2 -2
- package/dist/types.mjs +7 -1
- package/dist/types.mjs.map +1 -1
- package/package.json +27 -13
- package/dist/channel-BLwce5hh.mjs.map +0 -1
- package/dist/core-DaRwkTaV.mjs.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/internal-CAKfHjIg.mjs.map +0 -1
- package/dist/protocol-fXHXJguP.mjs.map +0 -1
- package/dist/secret-CcjyF8D3.mjs +0 -205
- package/dist/secret-CcjyF8D3.mjs.map +0 -1
- package/dist/types-cAQAJBLi.d.mts +0 -260
|
@@ -1,21 +1,30 @@
|
|
|
1
|
-
import { g as ValidationError } from "./core-DaRwkTaV.mjs";
|
|
2
|
-
import { a as isProtocolValue, c as responseError, n as METHODS, o as kernelEvent, s as requestBytes } from "./protocol-fXHXJguP.mjs";
|
|
3
1
|
import { WalletError } from "./types.mjs";
|
|
2
|
+
import { v as ValidationError } from "./core-Cx7p-0nG.mjs";
|
|
3
|
+
import { c as requestBytes, l as responseError, n as METHODS, o as isProtocolValue, s as kernelEvent } from "./protocol-DLE6lHmP.mjs";
|
|
4
4
|
// src/channel.ts
|
|
5
|
-
/**
|
|
6
|
-
* The host side of the kernel channel (design/enclave.mdx "协议与传输"): port lifecycle, respawn,
|
|
7
|
-
* request/response correlation and wire validation. Internal to the `./host` subpath — reserved for
|
|
8
|
-
* host packages (wallet-worker, wallet-native); applications must not use it.
|
|
9
|
-
*/
|
|
10
5
|
function integrity(message) {
|
|
11
6
|
return new WalletError("integrity", message);
|
|
12
7
|
}
|
|
13
8
|
/**
|
|
9
|
+
* Detects the port's own "cannot encode" refusal: a WalletError-shaped throw whose code is exactly
|
|
10
|
+
* "invalid-input". Matched by brand rather than `instanceof` — the port may carry a copy of the
|
|
11
|
+
* class loaded through a different module resolution; the exact-code check keeps any other refusal
|
|
12
|
+
* (including a foreign WalletError-shaped one) an integrity failure.
|
|
13
|
+
*/
|
|
14
|
+
const isEncodingRefusal = (error) => error instanceof Error && error.name === "WalletError" && "code" in error && error.code === "invalid-input";
|
|
15
|
+
/**
|
|
14
16
|
* A silent kernel is a wedged kernel: the request at the head of the kernel's serial queue gets
|
|
15
|
-
* this long before the port is replaced
|
|
16
|
-
*
|
|
17
|
+
* this long before the port is replaced, not counting time spent inside a system verification
|
|
18
|
+
* prompt (the kernel's `ceremony` events suspend the timer). Requests still queued behind the head
|
|
19
|
+
* are not timed — the kernel answers in order, so only the head can wedge.
|
|
17
20
|
*/
|
|
18
21
|
const CALL_TIMEOUT_MS = 6e4;
|
|
22
|
+
/**
|
|
23
|
+
* Posted-but-unanswered requests. Kept well below the native runtime's inbound cap of 64
|
|
24
|
+
* (KernelRuntime's kMaxInboundFrames, past which it fails closed) so a busy kernel delays requests
|
|
25
|
+
* instead of killing the session; Web/Node get the same bound so all hosts behave alike.
|
|
26
|
+
*/
|
|
27
|
+
const MAX_IN_FLIGHT = 32;
|
|
19
28
|
var Channel = class {
|
|
20
29
|
/** The live kernel session; attached to every request and cleared whenever it is gone. */
|
|
21
30
|
session;
|
|
@@ -23,7 +32,10 @@ var Channel = class {
|
|
|
23
32
|
unlisten;
|
|
24
33
|
unlistenExit;
|
|
25
34
|
generation = 0;
|
|
35
|
+
/** The kernel reported a pending system verification prompt — the watchdog is suspended. */
|
|
36
|
+
ceremony = false;
|
|
26
37
|
pending = /* @__PURE__ */ new Map();
|
|
38
|
+
queue = [];
|
|
27
39
|
/** Times the earliest pending request — the one the kernel is working on. */
|
|
28
40
|
watchdog;
|
|
29
41
|
nextId = 1;
|
|
@@ -70,6 +82,7 @@ var Channel = class {
|
|
|
70
82
|
this.port = void 0;
|
|
71
83
|
this.session = void 0;
|
|
72
84
|
this.deferredStatus = void 0;
|
|
85
|
+
this.ceremony = false;
|
|
73
86
|
this.watchdog?.cancel();
|
|
74
87
|
this.watchdog = void 0;
|
|
75
88
|
this.portReady = false;
|
|
@@ -135,22 +148,37 @@ var Channel = class {
|
|
|
135
148
|
this.respawn();
|
|
136
149
|
}
|
|
137
150
|
failPending(error) {
|
|
151
|
+
this.ceremony = false;
|
|
138
152
|
this.watchdog?.cancel();
|
|
139
153
|
this.watchdog = void 0;
|
|
140
154
|
for (const [, pending] of this.pending) pending.reject(error);
|
|
141
155
|
this.pending.clear();
|
|
156
|
+
for (const outbound of this.queue) {
|
|
157
|
+
outbound.wire?.wipe();
|
|
158
|
+
outbound.reject(error);
|
|
159
|
+
}
|
|
160
|
+
this.queue.length = 0;
|
|
142
161
|
}
|
|
143
162
|
/** (Re)arms the watchdog on `pending`'s insertion-ordered head, or clears it when empty. */
|
|
144
163
|
armWatchdog() {
|
|
145
164
|
this.watchdog?.cancel();
|
|
146
165
|
const head = this.pending.keys().next().value;
|
|
147
|
-
this.watchdog = head === void 0 ? void 0 : {
|
|
166
|
+
this.watchdog = head === void 0 || this.ceremony ? void 0 : {
|
|
148
167
|
id: head,
|
|
149
168
|
cancel: this.setTimer(CALL_TIMEOUT_MS, () => {
|
|
150
169
|
this.onCallTimeout();
|
|
151
170
|
})
|
|
152
171
|
};
|
|
153
172
|
}
|
|
173
|
+
/** A `ceremony` event suspends (active) or re-arms (inactive) the watchdog on the current head. */
|
|
174
|
+
onCeremony(active) {
|
|
175
|
+
if (this.ceremony === active) return;
|
|
176
|
+
this.ceremony = active;
|
|
177
|
+
if (active) {
|
|
178
|
+
this.watchdog?.cancel();
|
|
179
|
+
this.watchdog = void 0;
|
|
180
|
+
} else this.armWatchdog();
|
|
181
|
+
}
|
|
154
182
|
/** Removes the pending entry, re-timing the watchdog when the head settled, then runs `fn`. */
|
|
155
183
|
settle(id, fn) {
|
|
156
184
|
const pending = this.pending.get(id);
|
|
@@ -158,6 +186,27 @@ var Channel = class {
|
|
|
158
186
|
this.pending.delete(id);
|
|
159
187
|
if (this.watchdog?.id === id) this.armWatchdog();
|
|
160
188
|
fn(pending);
|
|
189
|
+
this.drainQueue();
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Posts queued requests in FIFO order while under the in-flight bound. Only posted requests are
|
|
194
|
+
* in `pending` (and timed by the watchdog) — queued ones are not the kernel's head yet.
|
|
195
|
+
*/
|
|
196
|
+
drainQueue() {
|
|
197
|
+
while (this.queue.length > 0 && this.pending.size < 32 && this.port !== void 0) {
|
|
198
|
+
const outbound = this.queue.shift();
|
|
199
|
+
if (outbound === void 0) return;
|
|
200
|
+
this.pending.set(outbound.id, outbound);
|
|
201
|
+
if (this.watchdog === void 0) this.armWatchdog();
|
|
202
|
+
try {
|
|
203
|
+
this.port.post(outbound.message, outbound.wire?.transfer ?? []);
|
|
204
|
+
} catch (error) {
|
|
205
|
+
this.pending.delete(outbound.id);
|
|
206
|
+
if (this.watchdog?.id === outbound.id) this.armWatchdog();
|
|
207
|
+
outbound.wire?.wipe();
|
|
208
|
+
outbound.reject(isEncodingRefusal(error) ? new WalletError("invalid-input", "the kernel port cannot encode the request") : integrity("the kernel port refused the message"));
|
|
209
|
+
}
|
|
161
210
|
}
|
|
162
211
|
}
|
|
163
212
|
/**
|
|
@@ -209,20 +258,20 @@ var Channel = class {
|
|
|
209
258
|
else this.handlers.onStatus(event.status);
|
|
210
259
|
this.portReady = true;
|
|
211
260
|
this.resolveReady?.();
|
|
212
|
-
} else {
|
|
261
|
+
} else if (event.event === "locked") {
|
|
213
262
|
this.session = void 0;
|
|
214
263
|
this.deferredStatus = void 0;
|
|
215
264
|
this.handlers.onLocked(event.reason);
|
|
216
265
|
this.failPending(new WalletError("locked", "the vault locked"));
|
|
217
266
|
this.respawn();
|
|
218
|
-
}
|
|
267
|
+
} else this.onCeremony(event.active);
|
|
219
268
|
return;
|
|
220
269
|
}
|
|
221
270
|
this.poison("unrecognised kernel message");
|
|
222
271
|
}
|
|
223
272
|
onResponse(message) {
|
|
224
273
|
const { id } = message;
|
|
225
|
-
if (typeof id !== "number" || !Number.isSafeInteger(id) || message["v"] !==
|
|
274
|
+
if (typeof id !== "number" || !Number.isSafeInteger(id) || message["v"] !== 3) {
|
|
226
275
|
this.poison("malformed response envelope");
|
|
227
276
|
return;
|
|
228
277
|
}
|
|
@@ -260,38 +309,50 @@ var Channel = class {
|
|
|
260
309
|
}
|
|
261
310
|
}
|
|
262
311
|
/**
|
|
263
|
-
* Sends one request and resolves with the validated result. The kernel
|
|
264
|
-
* response → locked, so the snapshot is already current when this
|
|
312
|
+
* Sends one request carrying no secret bytes and resolves with the validated result. The kernel
|
|
313
|
+
* answers with status → response → locked, so the snapshot is already current when this settles.
|
|
265
314
|
*/
|
|
266
|
-
async call(method, params
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
315
|
+
async call(method, params) {
|
|
316
|
+
return this.send(method, params);
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Sends one request whose params carry secret bytes. Invariant: every wire handed in is either on
|
|
320
|
+
* the transfer list of exactly one successful `port.post`, or wiped — on every path that does not
|
|
321
|
+
* post: ready-gate rejection, broken, destroyed/no port, oversize, `port.post` throwing.
|
|
322
|
+
*/
|
|
323
|
+
async callWithSecrets(method, params, wire) {
|
|
324
|
+
return this.send(method, params, wire);
|
|
325
|
+
}
|
|
326
|
+
async send(method, params, wire) {
|
|
327
|
+
try {
|
|
328
|
+
await this.readyPromise;
|
|
329
|
+
if (this.broken !== void 0) throw this.broken;
|
|
330
|
+
const { port } = this;
|
|
331
|
+
if (this.destroyed || port === void 0) throw new WalletError("locked", "wallet is destroyed");
|
|
332
|
+
const id = this.nextId++;
|
|
333
|
+
const message = {
|
|
334
|
+
v: 3,
|
|
335
|
+
id,
|
|
282
336
|
method,
|
|
283
|
-
|
|
284
|
-
|
|
337
|
+
params
|
|
338
|
+
};
|
|
339
|
+
if (this.session !== void 0) message["session"] = this.session;
|
|
340
|
+
if (requestBytes(message) > 1048576) throw new WalletError("invalid-input", "request exceeds the size limit");
|
|
341
|
+
return await new Promise((resolve, reject) => {
|
|
342
|
+
this.queue.push({
|
|
343
|
+
id,
|
|
344
|
+
method,
|
|
345
|
+
message,
|
|
346
|
+
wire,
|
|
347
|
+
resolve,
|
|
348
|
+
reject
|
|
349
|
+
});
|
|
350
|
+
this.drainQueue();
|
|
285
351
|
});
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
this.pending.delete(id);
|
|
291
|
-
if (this.watchdog?.id === id) this.armWatchdog();
|
|
292
|
-
reject(integrity("the kernel port refused the message"));
|
|
293
|
-
}
|
|
294
|
-
});
|
|
352
|
+
} catch (error) {
|
|
353
|
+
wire?.wipe();
|
|
354
|
+
throw error;
|
|
355
|
+
}
|
|
295
356
|
}
|
|
296
357
|
/** Fires the deferred unlocked status, if any, once the session is installed. */
|
|
297
358
|
flushStatus() {
|
|
@@ -315,6 +376,6 @@ var Channel = class {
|
|
|
315
376
|
this.failPending(new WalletError("locked", "wallet is destroyed"));
|
|
316
377
|
}
|
|
317
378
|
};
|
|
318
|
-
export {
|
|
379
|
+
export { MAX_IN_FLIGHT as n, integrity as r, Channel as t };
|
|
319
380
|
|
|
320
|
-
//# sourceMappingURL=channel-
|
|
381
|
+
//# sourceMappingURL=channel-BCZXU3pt.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"channel-BCZXU3pt.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 type { PlainMethod, SecretMethod, SecretWire } from \"./factors.ts\";\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/**\n * Detects the port's own \"cannot encode\" refusal: a WalletError-shaped throw whose code is exactly\n * \"invalid-input\". Matched by brand rather than `instanceof` — the port may carry a copy of the\n * class loaded through a different module resolution; the exact-code check keeps any other refusal\n * (including a foreign WalletError-shaped one) an integrity failure.\n */\nconst isEncodingRefusal = (error: unknown): boolean =>\n error instanceof Error &&\n error.name === \"WalletError\" &&\n \"code\" in error &&\n error.code === \"invalid-input\";\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, not counting time spent inside a system verification\n * prompt (the kernel's `ceremony` events suspend the timer). Requests still queued behind the head\n * are not timed — the kernel answers in order, so only the head can wedge.\n */\nconst CALL_TIMEOUT_MS = 60_000;\n\n/**\n * Posted-but-unanswered requests. Kept well below the native runtime's inbound cap of 64\n * (KernelRuntime's kMaxInboundFrames, past which it fails closed) so a busy kernel delays requests\n * instead of killing the session; Web/Node get the same bound so all hosts behave alike.\n */\nexport const MAX_IN_FLIGHT = 32;\n\ntype Pending = {\n readonly method: MethodName;\n readonly resolve: (value: unknown) => void;\n readonly reject: (error: WalletError) => void;\n};\n\n/** A fully validated request waiting for an in-flight slot; only posted entries are in `pending`. */\ntype Outbound = Pending & {\n readonly id: number;\n readonly message: Record<string, ProtocolValue>;\n readonly wire: SecretWire | undefined;\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 /** The kernel reported a pending system verification prompt — the watchdog is suspended. */\n private ceremony = false;\n\n private readonly pending = new Map<number, Pending>();\n private readonly queue: Outbound[] = [];\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.ceremony = false;\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.ceremony = false;\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 // Queued requests never reached the port — their wires are still live buffers to wipe.\n for (const outbound of this.queue) {\n outbound.wire?.wipe();\n outbound.reject(error);\n }\n this.queue.length = 0;\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 || this.ceremony\n ? undefined\n : {\n id: head,\n cancel: this.setTimer(CALL_TIMEOUT_MS, () => {\n this.onCallTimeout();\n }),\n };\n }\n\n /** A `ceremony` event suspends (active) or re-arms (inactive) the watchdog on the current head. */\n private onCeremony(active: boolean): void {\n if (this.ceremony === active) {\n return;\n }\n this.ceremony = active;\n if (active) {\n this.watchdog?.cancel();\n this.watchdog = undefined;\n } else {\n this.armWatchdog();\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 this.drainQueue();\n }\n }\n\n /**\n * Posts queued requests in FIFO order while under the in-flight bound. Only posted requests are\n * in `pending` (and timed by the watchdog) — queued ones are not the kernel's head yet.\n */\n private drainQueue(): void {\n while (this.queue.length > 0 && this.pending.size < MAX_IN_FLIGHT && this.port !== undefined) {\n const outbound = this.queue.shift();\n if (outbound === undefined) {\n return;\n }\n this.pending.set(outbound.id, outbound);\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 this.port.post(outbound.message, outbound.wire?.transfer ?? []);\n } catch (error) {\n this.pending.delete(outbound.id);\n if (this.watchdog?.id === outbound.id) {\n this.armWatchdog();\n }\n outbound.wire?.wipe();\n // A port that cannot encode the request says so itself (\"invalid-input\") — re-issued\n // fresh so the message names the failure regardless of what the refusal carried. Any\n // other refusal is the port refusing the message: integrity.\n outbound.reject(\n isEncodingRefusal(error)\n ? new WalletError(\"invalid-input\", \"the kernel port cannot encode the request\")\n : integrity(\"the kernel port refused the message\"),\n );\n }\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 if (event.event === \"locked\") {\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 } else {\n this.onCeremony(event.active);\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 err.detail,\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 carrying no secret bytes and resolves with the validated result. The kernel\n * answers with status → response → locked, so the snapshot is already current when this settles.\n */\n async call<M extends PlainMethod>(method: M, params: ParamsOf<M>): Promise<ResultOf<M>> {\n return this.send(method, params);\n }\n\n /**\n * Sends one request whose params carry secret bytes. Invariant: every wire handed in is either on\n * the transfer list of exactly one successful `port.post`, or wiped — on every path that does not\n * post: ready-gate rejection, broken, destroyed/no port, oversize, `port.post` throwing.\n */\n async callWithSecrets<M extends SecretMethod>(\n method: M,\n params: ParamsOf<M>,\n wire: SecretWire,\n ): Promise<ResultOf<M>> {\n return this.send(method, params, wire);\n }\n\n private async send<M extends MethodName>(\n method: M,\n params: ParamsOf<M>,\n wire?: SecretWire,\n ): Promise<ResultOf<M>> {\n try {\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.queue.push({ id, method, message, wire, resolve, reject });\n this.drainQueue();\n });\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- validated by METHODS[method].result\n return result as ResultOf<M>;\n } catch (error) {\n wire?.wipe();\n throw error;\n }\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":";;;;AAkCA,SAAgB,UAAU,SAA8B;CACtD,OAAO,IAAI,YAAY,aAAa,OAAO;AAC7C;;;;;;;AAQA,MAAM,qBAAqB,UACzB,iBAAiB,SACjB,MAAM,SAAS,iBACf,UAAU,SACV,MAAM,SAAS;;;;;;;AAWjB,MAAM,kBAAkB;;;;;;AAOxB,MAAa,gBAAgB;AA0B7B,IAAa,UAAb,MAAqB;;CAEnB;CAEA;CACA;CACA;CACA,aAAqB;;CAErB,WAAmB;CAEnB,0BAA2B,IAAI,IAAqB;CACpD,QAAqC,CAAC;;CAEtC;CACA,SAAiB;CACjB,YAAoB;;CAEpB;;CAEA;;CAEA,YAAoB;CACpB;CACA;CACA;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;GAChB,MAAM,UAAyC;IAAE,GAAA;IAAqB;IAAI;IAAQ;GAAO;GAGzF,IAAI,KAAK,YAAY,KAAA,GACnB,QAAQ,aAAa,KAAK;GAG5B,IAAI,aAAa,OAAO,IAAA,SACtB,MAAM,IAAI,YAAY,iBAAiB,gCAAgC;GAOzE,OAAO,MALc,IAAI,SAAkB,SAAS,WAAW;IAC7D,KAAK,MAAM,KAAK;KAAE;KAAI;KAAQ;KAAS;KAAM;KAAS;IAAO,CAAC;IAC9D,KAAK,WAAW;GAClB,CAAC;EAGH,SAAS,OAAO;GACd,MAAM,KAAK;GACX,MAAM;EACR;CACF;;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"}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { r as integrity } from "./channel-BCZXU3pt.mjs";
|
|
2
|
+
import { base58 } from "@scure/base";
|
|
3
|
+
import { ChainError } from "@qntx/wallet-chains";
|
|
4
|
+
import { bitcoinAddressFromXpub, bitcoinNetwork, samePsbtContent, verifyBitcoinMessage, verifyBitcoinPsbtSignatures, verifyLegacyBitcoinMessage } from "@qntx/wallet-chains/bitcoin";
|
|
5
|
+
import { evmAddressFromPublicKey, recoverEvmSigner } from "@qntx/wallet-chains/evm";
|
|
6
|
+
import { solanaAddressFromPublicKey, verifySolanaSignature } from "@qntx/wallet-chains/solana";
|
|
7
|
+
import { tronAddressFromPublicKey, verifyTronMessageSignature, verifyTronTransactionSignature, verifyTronTypedDataSignature } from "@qntx/wallet-chains/tron";
|
|
8
|
+
// src/chains/check.ts
|
|
9
|
+
/**
|
|
10
|
+
* The shared `chain.sign` / `hardware.sign` / card `sign` result verification: a result whose kind
|
|
11
|
+
* is not the request's is refused for every request kind, then the family's check verifies the
|
|
12
|
+
* signature (or signed content) against the account. Fails closed with `integrity`. Internal —
|
|
13
|
+
* reached through chains(), hardware() and card() only.
|
|
14
|
+
*/
|
|
15
|
+
/**
|
|
16
|
+
* The PSBT check: each sign entry names its template, so the account is fetched once per distinct
|
|
17
|
+
* template and each group's signatures verify against that template's xpub.
|
|
18
|
+
*/
|
|
19
|
+
const checkPsbt = async (internals, request, result) => {
|
|
20
|
+
if (result.kind !== request.kind) throw integrity("result kind does not match the request");
|
|
21
|
+
if (!samePsbtContent(request.psbt, result.signedPsbt)) throw integrity("signed psbt does not match the request");
|
|
22
|
+
const byTemplate = /* @__PURE__ */ new Map();
|
|
23
|
+
for (const { index, template } of request.sign) {
|
|
24
|
+
const group = byTemplate.get(template) ?? [];
|
|
25
|
+
group.push(index);
|
|
26
|
+
byTemplate.set(template, group);
|
|
27
|
+
}
|
|
28
|
+
for (const [template, indices] of byTemplate) {
|
|
29
|
+
const account = await internals.call("wallet.accounts", {
|
|
30
|
+
walletId: request.account.walletId,
|
|
31
|
+
groupIndex: request.account.groupIndex,
|
|
32
|
+
template,
|
|
33
|
+
network: request.network
|
|
34
|
+
});
|
|
35
|
+
if (!("xpub" in account)) throw integrity("chain account has no xpub");
|
|
36
|
+
if (!verifyBitcoinPsbtSignatures(result.signedPsbt, indices, account.xpub, template, request.network)) throw integrity("psbt signatures do not verify for the account");
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* The account the request names: the hd template account via `wallet.accounts`, or the imported
|
|
41
|
+
* key's address via `keys.list` — a keyId the vault does not list is refused.
|
|
42
|
+
*/
|
|
43
|
+
const signAccount = async (internals, request) => {
|
|
44
|
+
if (request.account.kind === "hd") return internals.call("wallet.accounts", {
|
|
45
|
+
walletId: request.account.walletId,
|
|
46
|
+
groupIndex: request.account.groupIndex,
|
|
47
|
+
template: request.account.template,
|
|
48
|
+
network: request.network
|
|
49
|
+
});
|
|
50
|
+
const { keyId } = request.account;
|
|
51
|
+
const key = (await internals.call("keys.list", null)).find((k) => k.keyId === keyId);
|
|
52
|
+
if (key === void 0) throw integrity("chain.sign answered for a key not in the vault");
|
|
53
|
+
return { address: key.address };
|
|
54
|
+
};
|
|
55
|
+
const checkEvm = async (internals, request, result) => {
|
|
56
|
+
if (result.kind !== request.kind) throw integrity("result kind does not match the request");
|
|
57
|
+
const account = await signAccount(internals, request);
|
|
58
|
+
if (!("address" in account)) throw integrity("chain account has no address");
|
|
59
|
+
let signer;
|
|
60
|
+
try {
|
|
61
|
+
signer = recoverEvmSigner(request, result);
|
|
62
|
+
} catch (error) {
|
|
63
|
+
if (error instanceof ChainError) throw integrity("signed content does not match the request");
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
if (signer.toLowerCase() !== account.address.toLowerCase()) throw integrity("signer does not match the account");
|
|
67
|
+
};
|
|
68
|
+
const checkSolana = async (internals, request, result) => {
|
|
69
|
+
if (result.kind !== request.kind) throw integrity("result kind does not match the request");
|
|
70
|
+
const account = await signAccount(internals, request);
|
|
71
|
+
if (!("address" in account)) throw integrity("chain account has no address");
|
|
72
|
+
if (!verifySolanaSignature(request.message, result.signature, account.address)) throw integrity("signature does not verify for the account");
|
|
73
|
+
};
|
|
74
|
+
const checkTron = async (internals, request, result) => {
|
|
75
|
+
if (result.kind !== request.kind) throw integrity("result kind does not match the request");
|
|
76
|
+
const account = await signAccount(internals, request);
|
|
77
|
+
if (!("address" in account)) throw integrity("chain account has no address");
|
|
78
|
+
if (!(request.kind === "tron.transaction" ? verifyTronTransactionSignature(request.rawData, result.signature, account.address) : request.kind === "tron.message" ? verifyTronMessageSignature(request.message, result.signature, account.address) : verifyTronTypedDataSignature(request.typedData, result.signature, account.address))) throw integrity("signature does not verify for the account");
|
|
79
|
+
};
|
|
80
|
+
const checkBitcoinMessage = async (internals, request, result) => {
|
|
81
|
+
if (result.kind !== request.kind) throw integrity("result kind does not match the request");
|
|
82
|
+
const account = await signAccount(internals, request);
|
|
83
|
+
if (!("xpub" in account)) throw integrity("chain account has no xpub");
|
|
84
|
+
if (bitcoinAddressFromXpub(account.xpub, account.template, request.network, request.change, request.index) !== request.address || !(request.format === "legacy" ? verifyLegacyBitcoinMessage : verifyBitcoinMessage)(request.address, request.message, result.signature, request.network)) throw integrity("message signature does not verify for the account");
|
|
85
|
+
};
|
|
86
|
+
/**
|
|
87
|
+
* The `chain.sign` result check: a result whose kind is not the request's is refused for every
|
|
88
|
+
* request kind, then the family's check verifies the signature (or signed content) against the
|
|
89
|
+
* account. The switch is exhaustive over the request union; a trailing return is unreachable
|
|
90
|
+
* (TS7027).
|
|
91
|
+
*/
|
|
92
|
+
const checkSignResult = async (internals, request, result) => {
|
|
93
|
+
switch (request.kind) {
|
|
94
|
+
case "evm.transaction":
|
|
95
|
+
case "evm.personal-message":
|
|
96
|
+
case "evm.fiat24-session":
|
|
97
|
+
case "evm.typed-data": return checkEvm(internals, request, result);
|
|
98
|
+
case "solana.transaction":
|
|
99
|
+
case "solana.message": return checkSolana(internals, request, result);
|
|
100
|
+
case "tron.transaction":
|
|
101
|
+
case "tron.message":
|
|
102
|
+
case "tron.typed-data": return checkTron(internals, request, result);
|
|
103
|
+
case "bitcoin.message": return checkBitcoinMessage(internals, request, result);
|
|
104
|
+
case "bitcoin.psbt": return checkPsbt(internals, request, result);
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
const HARDENED = 2147483648;
|
|
108
|
+
const sameNode = (a, b) => {
|
|
109
|
+
if (a.kind !== b.kind) return false;
|
|
110
|
+
if (a.kind === "leaf" && b.kind === "leaf") return a.template === b.template;
|
|
111
|
+
if (a.kind === "btc.account" && b.kind === "btc.account") return a.template === b.template && a.network === b.network;
|
|
112
|
+
return a.kind === "evm.account";
|
|
113
|
+
};
|
|
114
|
+
/**
|
|
115
|
+
* The network `wallet.accounts` is asked with for a network-free leaf node — a mainnet per family;
|
|
116
|
+
* the address is network-independent, the id only has to be a valid one.
|
|
117
|
+
*/
|
|
118
|
+
const LEAF = {
|
|
119
|
+
"evm.bip44": {
|
|
120
|
+
network: "eip155:1",
|
|
121
|
+
curve: "secp256k1",
|
|
122
|
+
path: (g) => `m/44'/60'/0'/0/${String(g)}`,
|
|
123
|
+
address: evmAddressFromPublicKey
|
|
124
|
+
},
|
|
125
|
+
"tron.bip44": {
|
|
126
|
+
network: "tron:728126428",
|
|
127
|
+
curve: "secp256k1",
|
|
128
|
+
path: (g) => `m/44'/195'/0'/0/${String(g)}`,
|
|
129
|
+
address: tronAddressFromPublicKey
|
|
130
|
+
},
|
|
131
|
+
"solana.bip44-change": {
|
|
132
|
+
network: "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",
|
|
133
|
+
curve: "ed25519",
|
|
134
|
+
path: (g) => `m/44'/501'/${String(g)}'/0'`,
|
|
135
|
+
address: solanaAddressFromPublicKey
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
/** The 78-byte BIP-32 serialization of an account node's extended public key. */
|
|
139
|
+
const xpubPayload = (version, parentFingerprint, index, chainCode, publicKey) => {
|
|
140
|
+
const out = /* @__PURE__ */ new Uint8Array(78);
|
|
141
|
+
const view = new DataView(out.buffer);
|
|
142
|
+
view.setUint32(0, version);
|
|
143
|
+
out[4] = 3;
|
|
144
|
+
view.setUint32(5, parentFingerprint);
|
|
145
|
+
view.setUint32(9, index);
|
|
146
|
+
out.set(chainCode, 13);
|
|
147
|
+
out.set(publicKey, 45);
|
|
148
|
+
return out;
|
|
149
|
+
};
|
|
150
|
+
const checkExportLeaf = async (internals, params, node, key) => {
|
|
151
|
+
const spec = LEAF[node.template];
|
|
152
|
+
if (key.curve !== spec.curve || key.chainCode !== void 0 || key.parentFingerprint !== void 0 || key.path !== spec.path(params.groupIndex)) throw integrity("exported leaf does not match the node");
|
|
153
|
+
const account = await internals.call("wallet.accounts", {
|
|
154
|
+
walletId: params.walletId,
|
|
155
|
+
groupIndex: params.groupIndex,
|
|
156
|
+
template: node.template,
|
|
157
|
+
network: spec.network
|
|
158
|
+
});
|
|
159
|
+
if (!("address" in account) || spec.address(key.publicKey) !== account.address) throw integrity("exported public key does not match the account");
|
|
160
|
+
};
|
|
161
|
+
const checkExportBtc = async (internals, params, node, key, fingerprint) => {
|
|
162
|
+
const account = await internals.call("wallet.accounts", {
|
|
163
|
+
walletId: params.walletId,
|
|
164
|
+
groupIndex: params.groupIndex,
|
|
165
|
+
template: node.template,
|
|
166
|
+
network: node.network
|
|
167
|
+
});
|
|
168
|
+
if (!("xpub" in account)) throw integrity("chain account has no xpub");
|
|
169
|
+
const net = bitcoinNetwork(node.network);
|
|
170
|
+
const expected = key.curve === "secp256k1" && key.publicKey.length === 33 && key.chainCode !== void 0 && key.parentFingerprint !== void 0 ? xpubPayload(net.bip32.public, Number.parseInt(key.parentFingerprint, 16), params.groupIndex + HARDENED, key.chainCode, key.publicKey) : void 0;
|
|
171
|
+
const decoded = base58.decode(account.xpub);
|
|
172
|
+
if (expected === void 0 || decoded.length !== 82 || !expected.every((byte, i) => byte === decoded[i]) || key.path !== account.path || fingerprint !== account.fingerprint) throw integrity("exported account key does not match the account xpub");
|
|
173
|
+
};
|
|
174
|
+
/**
|
|
175
|
+
* The `chain.exportAccount` result check: keys echo the requested nodes in order, leaves hash to
|
|
176
|
+
* the address `wallet.accounts` serves for the template, and the Bitcoin account key re-serializes
|
|
177
|
+
* to the account xpub. `evm.account` carries the shared account node — re-deriving the group's leaf
|
|
178
|
+
* from it needs `@scure/bip32`, which is not a runtime dependency of this package, so the main
|
|
179
|
+
* runtime checks its fixed path, curve and account fields only. A mismatch is `integrity`.
|
|
180
|
+
*/
|
|
181
|
+
const checkExportResult = async (internals, params, result) => {
|
|
182
|
+
if (result.keys.length !== params.nodes.length) throw integrity("export result does not match the request");
|
|
183
|
+
for (const [i, node] of params.nodes.entries()) {
|
|
184
|
+
const key = result.keys[i];
|
|
185
|
+
if (key === void 0 || !sameNode(key.node, node)) throw integrity("export result does not match the request");
|
|
186
|
+
if (node.kind === "leaf") await checkExportLeaf(internals, params, node, key);
|
|
187
|
+
else if (node.kind === "btc.account") await checkExportBtc(internals, params, node, key, result.fingerprint);
|
|
188
|
+
else if (key.curve !== "secp256k1" || key.publicKey.length !== 33 || key.chainCode === void 0 || key.parentFingerprint === void 0 || key.path !== "m/44'/60'/0'") throw integrity("exported account key does not match the node");
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
export { checkSignResult as n, checkExportResult as t };
|
|
192
|
+
|
|
193
|
+
//# sourceMappingURL=check-C1fUpgva.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"check-C1fUpgva.mjs","names":[],"sources":["../src/chains/check.ts"],"sourcesContent":["/**\n * The shared `chain.sign` / `hardware.sign` / card `sign` result verification: a result whose kind\n * is not the request's is refused for every request kind, then the family's check verifies the\n * signature (or signed content) against the account. Fails closed with `integrity`. Internal —\n * reached through chains(), hardware() and card() only.\n */\nimport { base58 } from \"@scure/base\";\n\nimport { ChainError } from \"@qntx/wallet-chains\";\nimport {\n bitcoinAddressFromXpub,\n bitcoinNetwork,\n samePsbtContent,\n verifyBitcoinMessage,\n verifyLegacyBitcoinMessage,\n verifyBitcoinPsbtSignatures,\n} from \"@qntx/wallet-chains/bitcoin\";\nimport { evmAddressFromPublicKey, recoverEvmSigner } from \"@qntx/wallet-chains/evm\";\nimport { solanaAddressFromPublicKey, verifySolanaSignature } from \"@qntx/wallet-chains/solana\";\nimport {\n tronAddressFromPublicKey,\n verifyTronMessageSignature,\n verifyTronTransactionSignature,\n verifyTronTypedDataSignature,\n} from \"@qntx/wallet-chains/tron\";\n\nimport { integrity } from \"../channel.ts\";\nimport type { WalletInternals } from \"../internal.ts\";\nimport type {\n ChainAccount,\n ChainExportedKey,\n ChainExportNode,\n ChainExportParams,\n ChainExportResult,\n ChainSignRequest,\n ChainSignResult,\n} from \"../protocol/chains.ts\";\n\n/**\n * The PSBT check: each sign entry names its template, so the account is fetched once per distinct\n * template and each group's signatures verify against that template's xpub.\n */\nconst checkPsbt = async (\n internals: WalletInternals,\n request: Extract<ChainSignRequest, { kind: \"bitcoin.psbt\" }>,\n result: ChainSignResult,\n): Promise<void> => {\n if (result.kind !== request.kind) {\n throw integrity(\"result kind does not match the request\");\n }\n if (!samePsbtContent(request.psbt, result.signedPsbt)) {\n throw integrity(\"signed psbt does not match the request\");\n }\n const byTemplate = new Map<\"btc.bip44\" | \"btc.bip49\" | \"btc.bip84\" | \"btc.bip86\", number[]>();\n for (const { index, template } of request.sign) {\n const group = byTemplate.get(template) ?? [];\n group.push(index);\n byTemplate.set(template, group);\n }\n for (const [template, indices] of byTemplate) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- one wallet.accounts call per template.\n const account = await internals.call(\"wallet.accounts\", {\n walletId: request.account.walletId,\n groupIndex: request.account.groupIndex,\n template,\n network: request.network,\n });\n if (!(\"xpub\" in account)) {\n throw integrity(\"chain account has no xpub\");\n }\n if (\n !verifyBitcoinPsbtSignatures(\n result.signedPsbt,\n indices,\n account.xpub,\n template,\n request.network,\n )\n ) {\n throw integrity(\"psbt signatures do not verify for the account\");\n }\n }\n};\n\n/**\n * The account the request names: the hd template account via `wallet.accounts`, or the imported\n * key's address via `keys.list` — a keyId the vault does not list is refused.\n */\nconst signAccount = async (\n internals: WalletInternals,\n request: Exclude<ChainSignRequest, { kind: \"bitcoin.psbt\" }>,\n): Promise<ChainAccount | { readonly address: string }> => {\n if (request.account.kind === \"hd\") {\n return internals.call(\"wallet.accounts\", {\n walletId: request.account.walletId,\n groupIndex: request.account.groupIndex,\n template: request.account.template,\n network: request.network,\n });\n }\n const { keyId } = request.account;\n const keys = await internals.call(\"keys.list\", null);\n const key = keys.find((k) => k.keyId === keyId);\n if (key === undefined) {\n throw integrity(\"chain.sign answered for a key not in the vault\");\n }\n return { address: key.address };\n};\n\nconst checkEvm = async (\n internals: WalletInternals,\n request: Extract<ChainSignRequest, { kind: `evm.${string}` }>,\n result: ChainSignResult,\n): Promise<void> => {\n if (result.kind !== request.kind) {\n throw integrity(\"result kind does not match the request\");\n }\n const account = await signAccount(internals, request);\n if (!(\"address\" in account)) {\n throw integrity(\"chain account has no address\");\n }\n let signer: string;\n try {\n signer = recoverEvmSigner(request, result);\n } catch (error) {\n if (error instanceof ChainError) {\n throw integrity(\"signed content does not match the request\");\n }\n throw error;\n }\n if (signer.toLowerCase() !== account.address.toLowerCase()) {\n throw integrity(\"signer does not match the account\");\n }\n};\n\nconst checkSolana = async (\n internals: WalletInternals,\n request: Extract<ChainSignRequest, { kind: `solana.${string}` }>,\n result: ChainSignResult,\n): Promise<void> => {\n if (result.kind !== request.kind) {\n throw integrity(\"result kind does not match the request\");\n }\n const account = await signAccount(internals, request);\n if (!(\"address\" in account)) {\n throw integrity(\"chain account has no address\");\n }\n if (!verifySolanaSignature(request.message, result.signature, account.address)) {\n throw integrity(\"signature does not verify for the account\");\n }\n};\n\nconst checkTron = async (\n internals: WalletInternals,\n request: Extract<ChainSignRequest, { kind: `tron.${string}` }>,\n result: ChainSignResult,\n): Promise<void> => {\n if (result.kind !== request.kind) {\n throw integrity(\"result kind does not match the request\");\n }\n const account = await signAccount(internals, request);\n if (!(\"address\" in account)) {\n throw integrity(\"chain account has no address\");\n }\n const verified =\n request.kind === \"tron.transaction\"\n ? verifyTronTransactionSignature(request.rawData, result.signature, account.address)\n : request.kind === \"tron.message\"\n ? verifyTronMessageSignature(request.message, result.signature, account.address)\n : verifyTronTypedDataSignature(request.typedData, result.signature, account.address);\n if (!verified) {\n throw integrity(\"signature does not verify for the account\");\n }\n};\n\nconst checkBitcoinMessage = async (\n internals: WalletInternals,\n request: Extract<ChainSignRequest, { kind: \"bitcoin.message\" }>,\n result: ChainSignResult,\n): Promise<void> => {\n if (result.kind !== request.kind) {\n throw integrity(\"result kind does not match the request\");\n }\n const account = await signAccount(internals, request);\n if (!(\"xpub\" in account)) {\n throw integrity(\"chain account has no xpub\");\n }\n const derived = bitcoinAddressFromXpub(\n account.xpub,\n account.template,\n request.network,\n request.change,\n request.index,\n );\n if (\n derived !== request.address ||\n !(request.format === \"legacy\" ? verifyLegacyBitcoinMessage : verifyBitcoinMessage)(\n request.address,\n request.message,\n result.signature,\n request.network,\n )\n ) {\n throw integrity(\"message signature does not verify for the account\");\n }\n};\n\n/**\n * The `chain.sign` result check: a result whose kind is not the request's is refused for every\n * request kind, then the family's check verifies the signature (or signed content) against the\n * account. The switch is exhaustive over the request union; a trailing return is unreachable\n * (TS7027).\n */\nexport const checkSignResult = async (\n internals: WalletInternals,\n request: ChainSignRequest,\n result: ChainSignResult,\n): Promise<void> => {\n switch (request.kind) {\n case \"evm.transaction\":\n case \"evm.personal-message\":\n case \"evm.fiat24-session\":\n case \"evm.typed-data\":\n return checkEvm(internals, request, result);\n case \"solana.transaction\":\n case \"solana.message\":\n return checkSolana(internals, request, result);\n case \"tron.transaction\":\n case \"tron.message\":\n case \"tron.typed-data\":\n return checkTron(internals, request, result);\n case \"bitcoin.message\":\n return checkBitcoinMessage(internals, request, result);\n case \"bitcoin.psbt\":\n return checkPsbt(internals, request, result);\n }\n};\n\nconst HARDENED = 0x80000000;\n\nconst sameNode = (a: ChainExportNode, b: ChainExportNode): boolean => {\n if (a.kind !== b.kind) {\n return false;\n }\n if (a.kind === \"leaf\" && b.kind === \"leaf\") {\n return a.template === b.template;\n }\n if (a.kind === \"btc.account\" && b.kind === \"btc.account\") {\n return a.template === b.template && a.network === b.network;\n }\n return a.kind === \"evm.account\";\n};\n\n/**\n * The network `wallet.accounts` is asked with for a network-free leaf node — a mainnet per family;\n * the address is network-independent, the id only has to be a valid one.\n */\nconst LEAF: Readonly<\n Record<\n \"evm.bip44\" | \"tron.bip44\" | \"solana.bip44-change\",\n {\n readonly network: string;\n readonly curve: \"secp256k1\" | \"ed25519\";\n readonly path: (groupIndex: number) => string;\n readonly address: (publicKey: Uint8Array) => string;\n }\n >\n> = {\n \"evm.bip44\": {\n network: \"eip155:1\",\n curve: \"secp256k1\",\n path: (g) => `m/44'/60'/0'/0/${String(g)}`,\n address: evmAddressFromPublicKey,\n },\n \"tron.bip44\": {\n network: \"tron:728126428\",\n curve: \"secp256k1\",\n path: (g) => `m/44'/195'/0'/0/${String(g)}`,\n address: tronAddressFromPublicKey,\n },\n \"solana.bip44-change\": {\n network: \"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp\",\n curve: \"ed25519\",\n path: (g) => `m/44'/501'/${String(g)}'/0'`,\n address: solanaAddressFromPublicKey,\n },\n};\n\n/** The 78-byte BIP-32 serialization of an account node's extended public key. */\nconst xpubPayload = (\n version: number,\n parentFingerprint: number,\n index: number,\n chainCode: Uint8Array,\n publicKey: Uint8Array,\n): Uint8Array => {\n const out = new Uint8Array(78);\n const view = new DataView(out.buffer);\n view.setUint32(0, version);\n out[4] = 3;\n view.setUint32(5, parentFingerprint);\n view.setUint32(9, index);\n out.set(chainCode, 13);\n out.set(publicKey, 45);\n return out;\n};\n\ntype ExportRequest = Pick<ChainExportParams, \"walletId\" | \"groupIndex\" | \"nodes\">;\n\nconst checkExportLeaf = async (\n internals: WalletInternals,\n params: ExportRequest,\n node: Extract<ChainExportNode, { kind: \"leaf\" }>,\n key: ChainExportedKey,\n): Promise<void> => {\n const spec = LEAF[node.template];\n if (\n key.curve !== spec.curve ||\n key.chainCode !== undefined ||\n key.parentFingerprint !== undefined ||\n key.path !== spec.path(params.groupIndex)\n ) {\n throw integrity(\"exported leaf does not match the node\");\n }\n const account = await internals.call(\"wallet.accounts\", {\n walletId: params.walletId,\n groupIndex: params.groupIndex,\n template: node.template,\n network: spec.network,\n });\n if (!(\"address\" in account) || spec.address(key.publicKey) !== account.address) {\n throw integrity(\"exported public key does not match the account\");\n }\n};\n\nconst checkExportBtc = async (\n internals: WalletInternals,\n params: ExportRequest,\n node: Extract<ChainExportNode, { kind: \"btc.account\" }>,\n key: ChainExportedKey,\n fingerprint: string,\n): Promise<void> => {\n const account = await internals.call(\"wallet.accounts\", {\n walletId: params.walletId,\n groupIndex: params.groupIndex,\n template: node.template,\n network: node.network,\n });\n if (!(\"xpub\" in account)) {\n throw integrity(\"chain account has no xpub\");\n }\n const net = bitcoinNetwork(node.network);\n const expected =\n key.curve === \"secp256k1\" &&\n key.publicKey.length === 33 &&\n key.chainCode !== undefined &&\n key.parentFingerprint !== undefined\n ? xpubPayload(\n net.bip32.public,\n Number.parseInt(key.parentFingerprint, 16),\n params.groupIndex + HARDENED,\n key.chainCode,\n key.publicKey,\n )\n : undefined;\n const decoded = base58.decode(account.xpub);\n if (\n expected === undefined ||\n decoded.length !== 82 ||\n !expected.every((byte, i) => byte === decoded[i]) ||\n key.path !== account.path ||\n fingerprint !== account.fingerprint\n ) {\n throw integrity(\"exported account key does not match the account xpub\");\n }\n};\n\n/**\n * The `chain.exportAccount` result check: keys echo the requested nodes in order, leaves hash to\n * the address `wallet.accounts` serves for the template, and the Bitcoin account key re-serializes\n * to the account xpub. `evm.account` carries the shared account node — re-deriving the group's leaf\n * from it needs `@scure/bip32`, which is not a runtime dependency of this package, so the main\n * runtime checks its fixed path, curve and account fields only. A mismatch is `integrity`.\n */\nexport const checkExportResult = async (\n internals: WalletInternals,\n params: ExportRequest,\n result: ChainExportResult,\n): Promise<void> => {\n if (result.keys.length !== params.nodes.length) {\n throw integrity(\"export result does not match the request\");\n }\n for (const [i, node] of params.nodes.entries()) {\n const key = result.keys[i];\n if (key === undefined || !sameNode(key.node, node)) {\n throw integrity(\"export result does not match the request\");\n }\n if (node.kind === \"leaf\") {\n // oxlint-disable-next-line eslint/no-await-in-loop -- one wallet.accounts call per node.\n await checkExportLeaf(internals, params, node, key);\n } else if (node.kind === \"btc.account\") {\n // oxlint-disable-next-line eslint/no-await-in-loop -- one wallet.accounts call per node.\n await checkExportBtc(internals, params, node, key, result.fingerprint);\n } else if (\n key.curve !== \"secp256k1\" ||\n key.publicKey.length !== 33 ||\n key.chainCode === undefined ||\n key.parentFingerprint === undefined ||\n key.path !== \"m/44'/60'/0'\"\n ) {\n throw integrity(\"exported account key does not match the node\");\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AA0CA,MAAM,YAAY,OAChB,WACA,SACA,WACkB;CAClB,IAAI,OAAO,SAAS,QAAQ,MAC1B,MAAM,UAAU,wCAAwC;CAE1D,IAAI,CAAC,gBAAgB,QAAQ,MAAM,OAAO,UAAU,GAClD,MAAM,UAAU,wCAAwC;CAE1D,MAAM,6BAAa,IAAI,IAAqE;CAC5F,KAAK,MAAM,EAAE,OAAO,cAAc,QAAQ,MAAM;EAC9C,MAAM,QAAQ,WAAW,IAAI,QAAQ,KAAK,CAAC;EAC3C,MAAM,KAAK,KAAK;EAChB,WAAW,IAAI,UAAU,KAAK;CAChC;CACA,KAAK,MAAM,CAAC,UAAU,YAAY,YAAY;EAE5C,MAAM,UAAU,MAAM,UAAU,KAAK,mBAAmB;GACtD,UAAU,QAAQ,QAAQ;GAC1B,YAAY,QAAQ,QAAQ;GAC5B;GACA,SAAS,QAAQ;EACnB,CAAC;EACD,IAAI,EAAE,UAAU,UACd,MAAM,UAAU,2BAA2B;EAE7C,IACE,CAAC,4BACC,OAAO,YACP,SACA,QAAQ,MACR,UACA,QAAQ,OACV,GAEA,MAAM,UAAU,+CAA+C;CAEnE;AACF;;;;;AAMA,MAAM,cAAc,OAClB,WACA,YACyD;CACzD,IAAI,QAAQ,QAAQ,SAAS,MAC3B,OAAO,UAAU,KAAK,mBAAmB;EACvC,UAAU,QAAQ,QAAQ;EAC1B,YAAY,QAAQ,QAAQ;EAC5B,UAAU,QAAQ,QAAQ;EAC1B,SAAS,QAAQ;CACnB,CAAC;CAEH,MAAM,EAAE,UA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