@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
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
import { WalletError } from "./types.mjs";
|
|
2
|
+
import { t as internalsOf } from "./internal-DwCus_Ws.mjs";
|
|
3
|
+
import { r as integrity$2 } from "./channel-BCZXU3pt.mjs";
|
|
4
|
+
import { n as checkSignResult } from "./check-C1fUpgva.mjs";
|
|
5
|
+
import { UrDecoder, UrEncoder, isUrType, toQrString } from "@qntx/ur";
|
|
6
|
+
const APDU_TAG = 5;
|
|
7
|
+
const MTU_TAG = 8;
|
|
8
|
+
const integrity$1 = (message) => new WalletError("integrity", message);
|
|
9
|
+
const input$1 = (message) => new WalletError("invalid-input", message);
|
|
10
|
+
const checkApdu = (apdu) => {
|
|
11
|
+
if (apdu.length < 5 || apdu.length > 260) throw input$1("APDU is not 5..260 bytes");
|
|
12
|
+
};
|
|
13
|
+
/** `channel(2) ‖ 05 ‖ seq(2) ‖ [len(2) on frame 0] ‖ data`, zero padded to 64. */
|
|
14
|
+
function hidFrames(apdu, channel) {
|
|
15
|
+
checkApdu(apdu);
|
|
16
|
+
if (!Number.isSafeInteger(channel) || channel < 0 || channel > 65535) throw input$1("HID channel is not a u16");
|
|
17
|
+
const data = new Uint8Array(2 + apdu.length);
|
|
18
|
+
new DataView(data.buffer).setUint16(0, apdu.length);
|
|
19
|
+
data.set(apdu, 2);
|
|
20
|
+
const blockSize = 59;
|
|
21
|
+
const frames = [];
|
|
22
|
+
for (let seq = 0; seq * blockSize < data.length; seq += 1) {
|
|
23
|
+
const frame = /* @__PURE__ */ new Uint8Array(64);
|
|
24
|
+
const head = new DataView(frame.buffer);
|
|
25
|
+
head.setUint16(0, channel);
|
|
26
|
+
head.setUint8(2, APDU_TAG);
|
|
27
|
+
head.setUint16(3, seq);
|
|
28
|
+
frame.set(data.subarray(seq * blockSize, (seq + 1) * blockSize), 5);
|
|
29
|
+
frames.push(frame);
|
|
30
|
+
}
|
|
31
|
+
return frames;
|
|
32
|
+
}
|
|
33
|
+
/** Reassembles one HID response; every violation is `integrity`. */
|
|
34
|
+
function hidAssembler(channel) {
|
|
35
|
+
let sequence = 0;
|
|
36
|
+
let announced = 0;
|
|
37
|
+
let received = 0;
|
|
38
|
+
let data = /* @__PURE__ */ new Uint8Array(0);
|
|
39
|
+
let done = false;
|
|
40
|
+
return { push(frame) {
|
|
41
|
+
if (done) throw integrity$1("frame received after the response completed");
|
|
42
|
+
if (frame.length !== 64) throw integrity$1("HID frame is not 64 bytes");
|
|
43
|
+
const view = new DataView(frame.buffer, frame.byteOffset, frame.byteLength);
|
|
44
|
+
if (view.getUint16(0) !== channel) throw integrity$1("HID frame on the wrong channel");
|
|
45
|
+
if (view.getUint8(2) !== APDU_TAG) throw integrity$1("HID frame carries a foreign tag");
|
|
46
|
+
if (view.getUint16(3) !== sequence) throw integrity$1("HID frame out of sequence");
|
|
47
|
+
if (sequence === 0) {
|
|
48
|
+
announced = view.getUint16(5);
|
|
49
|
+
if (announced < 2) throw integrity$1("announced response length is shorter than a status word");
|
|
50
|
+
data = new Uint8Array(announced);
|
|
51
|
+
received = Math.min(announced, frame.length - 7);
|
|
52
|
+
data.set(frame.subarray(7, 7 + received));
|
|
53
|
+
} else {
|
|
54
|
+
const take = Math.min(announced - received, frame.length - 5);
|
|
55
|
+
data.set(frame.subarray(5, 5 + take), received);
|
|
56
|
+
received += take;
|
|
57
|
+
}
|
|
58
|
+
sequence += 1;
|
|
59
|
+
if (received === announced) {
|
|
60
|
+
done = true;
|
|
61
|
+
return data;
|
|
62
|
+
}
|
|
63
|
+
} };
|
|
64
|
+
}
|
|
65
|
+
/** The BLE MTU negotiation request (device replies with the frame size at byte 5). */
|
|
66
|
+
const BLE_MTU_REQUEST = Uint8Array.of(8, 0, 0, 0, 0);
|
|
67
|
+
function bleMtu(frame) {
|
|
68
|
+
if (frame.length < 6 || frame[0] !== MTU_TAG) throw integrity$1("not an MTU negotiation frame");
|
|
69
|
+
const { 5: mtu } = frame;
|
|
70
|
+
if (mtu === void 0 || mtu < 6) throw integrity$1("negotiated MTU is not usable");
|
|
71
|
+
return mtu;
|
|
72
|
+
}
|
|
73
|
+
/** `05 ‖ seq(2) ‖ [len(2) on frame 0] ‖ data`, frames ≤ mtu, no padding. */
|
|
74
|
+
function bleFrames(apdu, mtu) {
|
|
75
|
+
checkApdu(apdu);
|
|
76
|
+
if (!Number.isSafeInteger(mtu) || mtu < 6 || mtu > 255) throw input$1("BLE MTU is not 6..255");
|
|
77
|
+
const frames = [];
|
|
78
|
+
for (let seq = 0, offset = 0; offset < apdu.length; seq += 1) {
|
|
79
|
+
const head = seq === 0 ? 5 : 3;
|
|
80
|
+
const take = Math.min(apdu.length - offset, mtu - head);
|
|
81
|
+
const frame = new Uint8Array(head + take);
|
|
82
|
+
const view = new DataView(frame.buffer);
|
|
83
|
+
view.setUint8(0, APDU_TAG);
|
|
84
|
+
view.setUint16(1, seq);
|
|
85
|
+
if (seq === 0) view.setUint16(3, apdu.length);
|
|
86
|
+
frame.set(apdu.subarray(offset, offset + take), head);
|
|
87
|
+
frames.push(frame);
|
|
88
|
+
offset += take;
|
|
89
|
+
}
|
|
90
|
+
return frames;
|
|
91
|
+
}
|
|
92
|
+
/** Reassembles one BLE response; every violation is `integrity`. */
|
|
93
|
+
function bleAssembler(mtu) {
|
|
94
|
+
if (!Number.isSafeInteger(mtu) || mtu < 6 || mtu > 255) throw input$1("BLE MTU is not 6..255");
|
|
95
|
+
let sequence = 0;
|
|
96
|
+
let announced = 0;
|
|
97
|
+
let received = 0;
|
|
98
|
+
let chunks = [];
|
|
99
|
+
let done = false;
|
|
100
|
+
return { push(frame) {
|
|
101
|
+
if (done) throw integrity$1("frame received after the response completed");
|
|
102
|
+
if (frame.length > mtu) throw integrity$1("BLE frame exceeds the negotiated MTU");
|
|
103
|
+
if (frame[0] !== APDU_TAG) throw integrity$1("BLE frame carries a foreign tag");
|
|
104
|
+
if (frame.length < 3) throw integrity$1("BLE frame is too short for the sequence header");
|
|
105
|
+
const view = new DataView(frame.buffer, frame.byteOffset, frame.byteLength);
|
|
106
|
+
if (view.getUint16(1) !== sequence) throw integrity$1("BLE frame out of sequence");
|
|
107
|
+
let chunk = frame.subarray(3);
|
|
108
|
+
if (sequence === 0) {
|
|
109
|
+
if (chunk.length < 2) throw integrity$1("first BLE frame is too short for the announced length");
|
|
110
|
+
announced = view.getUint16(3);
|
|
111
|
+
chunk = chunk.subarray(2);
|
|
112
|
+
}
|
|
113
|
+
sequence += 1;
|
|
114
|
+
if (received + chunk.length > announced) throw integrity$1("BLE data exceeds the announced response length");
|
|
115
|
+
chunks.push(chunk);
|
|
116
|
+
received += chunk.length;
|
|
117
|
+
if (received === announced) {
|
|
118
|
+
done = true;
|
|
119
|
+
const out = new Uint8Array(announced);
|
|
120
|
+
let offset = 0;
|
|
121
|
+
for (const part of chunks) {
|
|
122
|
+
out.set(part, offset);
|
|
123
|
+
offset += part.length;
|
|
124
|
+
}
|
|
125
|
+
chunks = [];
|
|
126
|
+
return out;
|
|
127
|
+
}
|
|
128
|
+
} };
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* One APDU exchange over HID: frames the request, reassembles the response. One call at a time — an
|
|
132
|
+
* interleaved call while a previous one is in flight is `invalid-input`.
|
|
133
|
+
*/
|
|
134
|
+
function ledgerHidExchange(port, channel) {
|
|
135
|
+
if (!Number.isSafeInteger(channel) || channel < 0 || channel > 65535) throw input$1("HID channel is not a u16");
|
|
136
|
+
let inFlight = false;
|
|
137
|
+
return async (apdu) => {
|
|
138
|
+
if (inFlight) throw input$1("exchange is already in flight on this link");
|
|
139
|
+
inFlight = true;
|
|
140
|
+
try {
|
|
141
|
+
for (const frame of hidFrames(apdu, channel)) await port.write(frame);
|
|
142
|
+
const assemble = hidAssembler(channel);
|
|
143
|
+
for (;;) {
|
|
144
|
+
const complete = assemble.push(await port.read());
|
|
145
|
+
if (complete !== void 0) return complete;
|
|
146
|
+
}
|
|
147
|
+
} finally {
|
|
148
|
+
inFlight = false;
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
/** Negotiates the BLE MTU once, then returns the framed exchange. */
|
|
153
|
+
async function ledgerBleExchange(port) {
|
|
154
|
+
await port.write(BLE_MTU_REQUEST);
|
|
155
|
+
const mtu = bleMtu(await port.read());
|
|
156
|
+
let inFlight = false;
|
|
157
|
+
return async (apdu) => {
|
|
158
|
+
if (inFlight) throw input$1("exchange is already in flight on this link");
|
|
159
|
+
inFlight = true;
|
|
160
|
+
try {
|
|
161
|
+
for (const frame of bleFrames(apdu, mtu)) await port.write(frame);
|
|
162
|
+
const assemble = bleAssembler(mtu);
|
|
163
|
+
for (;;) {
|
|
164
|
+
const complete = assemble.push(await port.read());
|
|
165
|
+
if (complete !== void 0) return complete;
|
|
166
|
+
}
|
|
167
|
+
} finally {
|
|
168
|
+
inFlight = false;
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* A `DeviceIo` backed by a raw APDU exchange: `message` requests are answered with `apdu`, any
|
|
174
|
+
* other request kind is `unsupported` — a Ledger device cannot take a QR or compare exchange.
|
|
175
|
+
*/
|
|
176
|
+
function ledgerIo(apdu) {
|
|
177
|
+
return { exchange: async (request) => {
|
|
178
|
+
if (request.kind !== "message") throw new WalletError("unsupported", "the ledger transport only carries APDU messages");
|
|
179
|
+
return {
|
|
180
|
+
kind: "message",
|
|
181
|
+
data: await apdu(request.data)
|
|
182
|
+
};
|
|
183
|
+
} };
|
|
184
|
+
}
|
|
185
|
+
// src/hardware/onekey.ts
|
|
186
|
+
const REPORT_SIZE = 64;
|
|
187
|
+
const input = (message) => new WalletError("invalid-input", message);
|
|
188
|
+
const integrity = (message) => new WalletError("integrity", message);
|
|
189
|
+
const oneKeyAnswerLength = (firstChunk, transport) => {
|
|
190
|
+
if (firstChunk.length < 9 || firstChunk[0] !== 63 || firstChunk[1] !== 35 || firstChunk[2] !== 35) throw input("the device answer does not start with the OneKey header");
|
|
191
|
+
const length = new DataView(firstChunk.buffer, firstChunk.byteOffset, firstChunk.length).getUint32(5);
|
|
192
|
+
return transport === "usb" ? 64 * Math.max(1, Math.ceil((8 + length) / 63)) : 9 + length;
|
|
193
|
+
};
|
|
194
|
+
/**
|
|
195
|
+
* Reads `port` until `answerLength(first chunk)` bytes have arrived; returns the whole sequence.
|
|
196
|
+
* Over USB every report is exactly 64 bytes; over BLE a notification may be any size, but the
|
|
197
|
+
* stream must stop exactly at the announced length — a short or long transport read is `integrity`,
|
|
198
|
+
* like the Ledger assembler's violations.
|
|
199
|
+
*/
|
|
200
|
+
const collect = async (port, transport) => {
|
|
201
|
+
const first = await port.read();
|
|
202
|
+
if (transport === "usb" && first.length !== REPORT_SIZE) throw integrity("a HID answer report is not 64 bytes");
|
|
203
|
+
const total = oneKeyAnswerLength(first, transport);
|
|
204
|
+
const chunks = [first];
|
|
205
|
+
let collected = first.length;
|
|
206
|
+
while (collected < total) {
|
|
207
|
+
const chunk = await port.read();
|
|
208
|
+
if (chunk.length === 0) throw integrity("the device answer stalled on an empty read");
|
|
209
|
+
if (transport === "usb" && chunk.length !== REPORT_SIZE) throw integrity("a HID answer report is not 64 bytes");
|
|
210
|
+
chunks.push(chunk);
|
|
211
|
+
collected += chunk.length;
|
|
212
|
+
}
|
|
213
|
+
if (collected !== total) throw integrity("the device answer overshot its announced length");
|
|
214
|
+
const data = new Uint8Array(collected);
|
|
215
|
+
let at = 0;
|
|
216
|
+
for (const chunk of chunks) {
|
|
217
|
+
data.set(chunk, at);
|
|
218
|
+
at += chunk.length;
|
|
219
|
+
}
|
|
220
|
+
return data;
|
|
221
|
+
};
|
|
222
|
+
/**
|
|
223
|
+
* One framed command exchange over USB HID: writes `data` report by report, then collects the whole
|
|
224
|
+
* report sequence of the answer. One call at a time — an interleaved call while a previous one is
|
|
225
|
+
* in flight is `invalid-input`.
|
|
226
|
+
*/
|
|
227
|
+
function oneKeyHidExchange(port) {
|
|
228
|
+
let inFlight = false;
|
|
229
|
+
return async (data) => {
|
|
230
|
+
if (inFlight) throw input("exchange is already in flight on this link");
|
|
231
|
+
if (data.length === 0 || data.length % REPORT_SIZE !== 0) throw input("the request is not a whole number of 64-byte HID reports");
|
|
232
|
+
inFlight = true;
|
|
233
|
+
try {
|
|
234
|
+
for (let at = 0; at < data.length; at += REPORT_SIZE) await port.write(data.subarray(at, at + REPORT_SIZE));
|
|
235
|
+
return await collect(port, "usb");
|
|
236
|
+
} finally {
|
|
237
|
+
inFlight = false;
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* The same exchange over BLE: `data` — the same 64-byte report sequence — is split into writes of
|
|
243
|
+
* at most `mtu` bytes (the chip counts reports, not write calls), and the answer is the
|
|
244
|
+
* concatenated notification stream. One call at a time — interleaving is `invalid-input`.
|
|
245
|
+
*/
|
|
246
|
+
function oneKeyBleExchange(port, mtu) {
|
|
247
|
+
if (!Number.isSafeInteger(mtu) || mtu < 1) throw input("BLE MTU is not a positive integer");
|
|
248
|
+
let inFlight = false;
|
|
249
|
+
return async (data) => {
|
|
250
|
+
if (inFlight) throw input("exchange is already in flight on this link");
|
|
251
|
+
if (data.length === 0) throw input("the request is empty");
|
|
252
|
+
inFlight = true;
|
|
253
|
+
try {
|
|
254
|
+
for (let at = 0; at < data.length; at += mtu) await port.write(data.subarray(at, at + mtu));
|
|
255
|
+
return await collect(port, "ble");
|
|
256
|
+
} finally {
|
|
257
|
+
inFlight = false;
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* A `DeviceIo` backed by a framed exchange: `message` requests are written verbatim, any other
|
|
263
|
+
* request kind is `unsupported` — a OneKey device cannot take a QR or compare exchange.
|
|
264
|
+
*/
|
|
265
|
+
function oneKeyIo(exchange) {
|
|
266
|
+
return { exchange: async (request) => {
|
|
267
|
+
if (request.kind !== "message") throw new WalletError("unsupported", "the onekey transport only carries framed messages");
|
|
268
|
+
return {
|
|
269
|
+
kind: "message",
|
|
270
|
+
data: await exchange(request.data)
|
|
271
|
+
};
|
|
272
|
+
} };
|
|
273
|
+
}
|
|
274
|
+
// src/hardware/index.ts
|
|
275
|
+
/**
|
|
276
|
+
* The hardware module of @qntx/wallet: `hardware(wallet)` returns the external-signer API. Every
|
|
277
|
+
* call drives one kernel device operation — `hardware.begin`, then `hardware.step` for each
|
|
278
|
+
* exchange the kernel asks for, until `done`. The host only transports frames; the kernel validates
|
|
279
|
+
* every request, decodes every answer and verifies every signature, and this module re-checks a
|
|
280
|
+
* sign result the same way `chains().sign` does. An operation is never left running: any abort or
|
|
281
|
+
* transport failure cancels it best-effort before the promise settles.
|
|
282
|
+
*
|
|
283
|
+
* `qrParts`/`qrReader` are the pure UR plumbing for air-gapped (QR) transports: parts are the
|
|
284
|
+
* uppercase fountain strings a device scans, the reader folds scanned strings back into the payload
|
|
285
|
+
* and only accepts the UR types the operation advertised.
|
|
286
|
+
*/
|
|
287
|
+
const cancelledError = () => new WalletError("cancelled", "the device operation was aborted");
|
|
288
|
+
function run(internals, op, options) {
|
|
289
|
+
const { io, verify } = options;
|
|
290
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
291
|
+
/** The most recent step reported — a late observe starts from it. */
|
|
292
|
+
let current;
|
|
293
|
+
let opId;
|
|
294
|
+
/** `cancel` raced `hardware.begin` — fire `hardware.cancel` the moment the opId lands. */
|
|
295
|
+
let cancelRequested = false;
|
|
296
|
+
/** A live read — a plain property access lets TS and the linter treat the flag as constant. */
|
|
297
|
+
const isCancelled = () => cancelRequested;
|
|
298
|
+
let ackCancel;
|
|
299
|
+
let cancelAck;
|
|
300
|
+
let done = false;
|
|
301
|
+
let resolveResult;
|
|
302
|
+
let rejectResult;
|
|
303
|
+
const result = new Promise((resolve, reject) => {
|
|
304
|
+
resolveResult = resolve;
|
|
305
|
+
rejectResult = reject;
|
|
306
|
+
});
|
|
307
|
+
(async () => {
|
|
308
|
+
try {
|
|
309
|
+
await result;
|
|
310
|
+
} catch {}
|
|
311
|
+
})();
|
|
312
|
+
const emit = (step) => {
|
|
313
|
+
current = step;
|
|
314
|
+
for (const listener of listeners) listener(step);
|
|
315
|
+
};
|
|
316
|
+
const cancel = async () => {
|
|
317
|
+
if (done) return;
|
|
318
|
+
cancelRequested = true;
|
|
319
|
+
if (opId === void 0) {
|
|
320
|
+
cancelAck ??= new Promise((resolve) => {
|
|
321
|
+
ackCancel = resolve;
|
|
322
|
+
});
|
|
323
|
+
await cancelAck;
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
await internals.call("hardware.cancel", { opId }).catch(() => void 0);
|
|
327
|
+
};
|
|
328
|
+
(async () => {
|
|
329
|
+
try {
|
|
330
|
+
const beginCall = async () => internals.secretCall("hardware.begin", async (wire) => ({
|
|
331
|
+
op,
|
|
332
|
+
...verify === void 0 ? {} : { verify: await internals.resolveVerifyFactor(verify, wire) }
|
|
333
|
+
}));
|
|
334
|
+
const begin = verify === void 0 ? await beginCall() : await internals.withVerifying(beginCall);
|
|
335
|
+
({opId} = begin);
|
|
336
|
+
if (cancelRequested) {
|
|
337
|
+
await internals.call("hardware.cancel", { opId }).catch(() => void 0);
|
|
338
|
+
emit(begin.step);
|
|
339
|
+
done = true;
|
|
340
|
+
rejectResult(cancelledError());
|
|
341
|
+
ackCancel?.();
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
let { step } = begin;
|
|
345
|
+
while (step.kind === "exchange" && !isCancelled()) {
|
|
346
|
+
emit(step);
|
|
347
|
+
const response = await io.exchange(step.request, {
|
|
348
|
+
device: step.device,
|
|
349
|
+
...step.display === void 0 ? {} : { display: step.display }
|
|
350
|
+
});
|
|
351
|
+
if (isCancelled()) throw cancelledError();
|
|
352
|
+
step = await internals.call("hardware.step", {
|
|
353
|
+
opId,
|
|
354
|
+
response
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
if (isCancelled()) throw cancelledError();
|
|
358
|
+
if (step.kind !== "done") throw integrity$2("hardware.step answered a step kind the wire does not define");
|
|
359
|
+
const outcome = step.result;
|
|
360
|
+
if (outcome.kind !== op.kind) throw integrity$2("operation result does not match the operation");
|
|
361
|
+
if (outcome.kind === "sign" && op.kind === "sign") await checkSignResult(internals, op.request, outcome.result);
|
|
362
|
+
emit(step);
|
|
363
|
+
done = true;
|
|
364
|
+
resolveResult(outcome);
|
|
365
|
+
} catch (error) {
|
|
366
|
+
done = true;
|
|
367
|
+
ackCancel?.();
|
|
368
|
+
if (opId !== void 0) await internals.call("hardware.cancel", { opId }).catch(() => void 0);
|
|
369
|
+
if (cancelRequested) rejectResult(cancelledError());
|
|
370
|
+
else rejectResult(error);
|
|
371
|
+
}
|
|
372
|
+
})();
|
|
373
|
+
return {
|
|
374
|
+
observe: (listener) => {
|
|
375
|
+
listeners.add(listener);
|
|
376
|
+
if (current !== void 0) listener(current);
|
|
377
|
+
return () => {
|
|
378
|
+
listeners.delete(listener);
|
|
379
|
+
};
|
|
380
|
+
},
|
|
381
|
+
cancel,
|
|
382
|
+
result
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
function createHardwareApi(internals) {
|
|
386
|
+
/** The running task, if any — a second `start` cancels it (the kernel does the same). */
|
|
387
|
+
let active;
|
|
388
|
+
return { start: (op, options) => {
|
|
389
|
+
active?.cancel();
|
|
390
|
+
active = run(internals, op, options);
|
|
391
|
+
return active;
|
|
392
|
+
} };
|
|
393
|
+
}
|
|
394
|
+
const apis = /* @__PURE__ */ new WeakMap();
|
|
395
|
+
function hardware(wallet) {
|
|
396
|
+
const internals = internalsOf(wallet);
|
|
397
|
+
let api = apis.get(wallet);
|
|
398
|
+
if (api === void 0) {
|
|
399
|
+
api = createHardwareApi(internals);
|
|
400
|
+
apis.set(wallet, api);
|
|
401
|
+
}
|
|
402
|
+
return api;
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Firmware 3.2.2 `FRAGMENT_MAX_LENGTH_DEFAULT` (rust_c/src/common/ur.rs) — the fragment size the
|
|
406
|
+
* device's own encoder uses and its decoder is guaranteed to keep up with.
|
|
407
|
+
*/
|
|
408
|
+
const DEFAULT_FRAGMENT_LENGTH = 200;
|
|
409
|
+
/**
|
|
410
|
+
* Endless, cyclic fountain parts for one QR payload: each call returns the next uppercase UR string
|
|
411
|
+
* (`UR:<type>/…`), ready for an animated QR. For single-part payloads the same frame repeats — the
|
|
412
|
+
* loop is safe to drive on a timer.
|
|
413
|
+
*/
|
|
414
|
+
const qrParts = (payload, options) => {
|
|
415
|
+
if (!isUrType(payload.type)) throw new WalletError("invalid-input", `not a UR type: ${payload.type}`);
|
|
416
|
+
const encoder = new UrEncoder(payload.type, payload.cbor, { maxFragmentLength: options?.maxFragmentLength ?? DEFAULT_FRAGMENT_LENGTH });
|
|
417
|
+
return () => {
|
|
418
|
+
const next = encoder.next();
|
|
419
|
+
if (typeof next.value !== "string") throw integrity$2("fountain encoder ended");
|
|
420
|
+
return toQrString(next.value);
|
|
421
|
+
};
|
|
422
|
+
};
|
|
423
|
+
/** An incremental reader for the frames a device shows back; only `scan` types are admitted. */
|
|
424
|
+
const qrReader = (scan) => {
|
|
425
|
+
const accept = scan.map((type) => {
|
|
426
|
+
if (!isUrType(type)) throw new WalletError("invalid-input", `not a UR type: ${type}`);
|
|
427
|
+
return type;
|
|
428
|
+
});
|
|
429
|
+
const decoder = new UrDecoder({ accept });
|
|
430
|
+
return { receive: (part) => {
|
|
431
|
+
const outcome = decoder.receive(part);
|
|
432
|
+
if (outcome.status === "fatal") throw new WalletError("invalid-input", outcome.error.message);
|
|
433
|
+
const { state } = decoder;
|
|
434
|
+
if (state.phase === "complete") return {
|
|
435
|
+
progress: 1,
|
|
436
|
+
payload: {
|
|
437
|
+
type: state.value.type,
|
|
438
|
+
cbor: state.value.message
|
|
439
|
+
}
|
|
440
|
+
};
|
|
441
|
+
return { progress: decoder.progress.ratio };
|
|
442
|
+
} };
|
|
443
|
+
};
|
|
444
|
+
export { hardware, ledgerBleExchange, ledgerHidExchange, ledgerIo, oneKeyBleExchange, oneKeyHidExchange, oneKeyIo, qrParts, qrReader };
|
|
445
|
+
|
|
446
|
+
//# sourceMappingURL=hardware.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hardware.mjs","names":["integrity","input","integrity"],"sources":["../src/hardware/ledger.ts","../src/hardware/onekey.ts","../src/hardware/index.ts"],"sourcesContent":["/**\n * The host half of the Ledger transport: APDU framing and the `DeviceIo` adapter. The kernel driver\n * exchanges raw APDUs — one `{ kind: \"message\", data }` request per APDU — and all wire framing\n * happens here, where the transport lives.\n *\n * HID and BLE framing is ported from the vendor's implementation (Apache-2.0,\n * refs/ledgerjs-npm/devices-8.4.4/src/hid-framing.ts and ble/{sendAPDU,receiveAPDU}.ts).\n *\n * HID: fixed 64-byte reports `channel(2, BE) ‖ tag 0x05 ‖ seq(2, BE) ‖ [len(2, BE) on frame 0] ‖\n * data`, last frame zero padded. BLE: same layout without the channel, no padding, frames ≤ MTU;\n * the MTU is negotiated once with `08 00 00 00 00`, the reply carries the size at byte 5\n * (ledgerjs-npm/device-transport-kit-web-ble WebBleApduSender._handleMtuNegotiationFrame).\n *\n * Reassembly is a small state machine: channel/tag/sequence checked in order, the announced length\n * must be ≥ 2 (a response always carries a status word), data beyond the announced length is a\n * violation, and any frame after completion is a violation — all `integrity`. Bad host arguments\n * (an out-of-range channel, MTU or APDU size) are `invalid-input`.\n */\nimport type { DeviceIo, DeviceRequest, DeviceResponse } from \"../protocol/hardware.ts\";\nimport { WalletError } from \"../types.ts\";\nimport type { BlePort, HidPort } from \"./ports.ts\";\n\nexport const HID_REPORT_SIZE = 64;\n\nconst APDU_TAG = 0x05;\nconst MTU_TAG = 0x08;\n\nconst integrity = (message: string): WalletError => new WalletError(\"integrity\", message);\nconst input = (message: string): WalletError => new WalletError(\"invalid-input\", message);\n\n/** `push` returns the complete response once; a push after completion is `integrity`. */\nexport type Assembler = {\n push: (frame: Uint8Array) => Uint8Array | undefined;\n};\n\nconst checkApdu = (apdu: Uint8Array): void => {\n // 5 header bytes + up to 255 data bytes.\n if (apdu.length < 5 || apdu.length > 260) {\n throw input(\"APDU is not 5..260 bytes\");\n }\n};\n\n/** `channel(2) ‖ 05 ‖ seq(2) ‖ [len(2) on frame 0] ‖ data`, zero padded to 64. */\nexport function hidFrames(apdu: Uint8Array, channel: number): Uint8Array[] {\n checkApdu(apdu);\n if (!Number.isSafeInteger(channel) || channel < 0 || channel > 0xffff) {\n throw input(\"HID channel is not a u16\");\n }\n const data = new Uint8Array(2 + apdu.length);\n new DataView(data.buffer).setUint16(0, apdu.length);\n data.set(apdu, 2);\n\n const blockSize = HID_REPORT_SIZE - 5;\n const frames: Uint8Array[] = [];\n for (let seq = 0; seq * blockSize < data.length; seq += 1) {\n const frame = new Uint8Array(HID_REPORT_SIZE);\n const head = new DataView(frame.buffer);\n head.setUint16(0, channel);\n head.setUint8(2, APDU_TAG);\n head.setUint16(3, seq);\n frame.set(data.subarray(seq * blockSize, (seq + 1) * blockSize), 5);\n frames.push(frame);\n }\n return frames;\n}\n\n/** Reassembles one HID response; every violation is `integrity`. */\nexport function hidAssembler(channel: number): Assembler {\n let sequence = 0;\n let announced = 0;\n let received = 0;\n let data = new Uint8Array(0);\n let done = false;\n return {\n push(frame: Uint8Array): Uint8Array | undefined {\n if (done) {\n throw integrity(\"frame received after the response completed\");\n }\n if (frame.length !== HID_REPORT_SIZE) {\n throw integrity(\"HID frame is not 64 bytes\");\n }\n const view = new DataView(frame.buffer, frame.byteOffset, frame.byteLength);\n if (view.getUint16(0) !== channel) {\n throw integrity(\"HID frame on the wrong channel\");\n }\n if (view.getUint8(2) !== APDU_TAG) {\n throw integrity(\"HID frame carries a foreign tag\");\n }\n if (view.getUint16(3) !== sequence) {\n throw integrity(\"HID frame out of sequence\");\n }\n if (sequence === 0) {\n announced = view.getUint16(5);\n if (announced < 2) {\n throw integrity(\"announced response length is shorter than a status word\");\n }\n data = new Uint8Array(announced);\n received = Math.min(announced, frame.length - 7);\n data.set(frame.subarray(7, 7 + received));\n } else {\n const take = Math.min(announced - received, frame.length - 5);\n data.set(frame.subarray(5, 5 + take), received);\n received += take;\n }\n sequence += 1;\n if (received === announced) {\n done = true;\n return data;\n }\n return undefined;\n },\n };\n}\n\n/** The BLE MTU negotiation request (device replies with the frame size at byte 5). */\nexport const BLE_MTU_REQUEST: Uint8Array = Uint8Array.of(0x08, 0x00, 0x00, 0x00, 0x00);\n\nexport function bleMtu(frame: Uint8Array): number {\n if (frame.length < 6 || frame[0] !== MTU_TAG) {\n throw integrity(\"not an MTU negotiation frame\");\n }\n const { 5: mtu } = frame;\n if (mtu === undefined || mtu < 6) {\n throw integrity(\"negotiated MTU is not usable\");\n }\n return mtu;\n}\n\n/** `05 ‖ seq(2) ‖ [len(2) on frame 0] ‖ data`, frames ≤ mtu, no padding. */\nexport function bleFrames(apdu: Uint8Array, mtu: number): Uint8Array[] {\n checkApdu(apdu);\n if (!Number.isSafeInteger(mtu) || mtu < 6 || mtu > 0xff) {\n throw input(\"BLE MTU is not 6..255\");\n }\n const frames: Uint8Array[] = [];\n for (let seq = 0, offset = 0; offset < apdu.length; seq += 1) {\n const head = seq === 0 ? 5 : 3;\n const take = Math.min(apdu.length - offset, mtu - head);\n const frame = new Uint8Array(head + take);\n const view = new DataView(frame.buffer);\n view.setUint8(0, APDU_TAG);\n view.setUint16(1, seq);\n if (seq === 0) {\n view.setUint16(3, apdu.length);\n }\n frame.set(apdu.subarray(offset, offset + take), head);\n frames.push(frame);\n offset += take;\n }\n return frames;\n}\n\n/** Reassembles one BLE response; every violation is `integrity`. */\nexport function bleAssembler(mtu: number): Assembler {\n if (!Number.isSafeInteger(mtu) || mtu < 6 || mtu > 0xff) {\n throw input(\"BLE MTU is not 6..255\");\n }\n let sequence = 0;\n let announced = 0;\n let received = 0;\n let chunks: Uint8Array[] = [];\n let done = false;\n return {\n push(frame: Uint8Array): Uint8Array | undefined {\n if (done) {\n throw integrity(\"frame received after the response completed\");\n }\n if (frame.length > mtu) {\n throw integrity(\"BLE frame exceeds the negotiated MTU\");\n }\n if (frame[0] !== APDU_TAG) {\n throw integrity(\"BLE frame carries a foreign tag\");\n }\n if (frame.length < 3) {\n throw integrity(\"BLE frame is too short for the sequence header\");\n }\n const view = new DataView(frame.buffer, frame.byteOffset, frame.byteLength);\n if (view.getUint16(1) !== sequence) {\n throw integrity(\"BLE frame out of sequence\");\n }\n let chunk = frame.subarray(3);\n if (sequence === 0) {\n if (chunk.length < 2) {\n throw integrity(\"first BLE frame is too short for the announced length\");\n }\n announced = view.getUint16(3);\n chunk = chunk.subarray(2);\n }\n sequence += 1;\n if (received + chunk.length > announced) {\n throw integrity(\"BLE data exceeds the announced response length\");\n }\n chunks.push(chunk);\n received += chunk.length;\n if (received === announced) {\n done = true;\n const out = new Uint8Array(announced);\n let offset = 0;\n for (const part of chunks) {\n out.set(part, offset);\n offset += part.length;\n }\n chunks = [];\n return out;\n }\n return undefined;\n },\n };\n}\n\n/**\n * One APDU exchange over HID: frames the request, reassembles the response. One call at a time — an\n * interleaved call while a previous one is in flight is `invalid-input`.\n */\nexport function ledgerHidExchange(\n port: HidPort,\n channel: number,\n): (apdu: Uint8Array) => Promise<Uint8Array> {\n if (!Number.isSafeInteger(channel) || channel < 0 || channel > 0xffff) {\n throw input(\"HID channel is not a u16\");\n }\n let inFlight = false;\n return async (apdu) => {\n if (inFlight) {\n throw input(\"exchange is already in flight on this link\");\n }\n inFlight = true;\n try {\n for (const frame of hidFrames(apdu, channel)) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- frames are ordered on one link\n await port.write(frame);\n }\n const assemble = hidAssembler(channel);\n for (;;) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- response frames are ordered\n const complete = assemble.push(await port.read());\n if (complete !== undefined) {\n return complete;\n }\n }\n } finally {\n inFlight = false;\n }\n };\n}\n\n/** Negotiates the BLE MTU once, then returns the framed exchange. */\nexport async function ledgerBleExchange(\n port: BlePort,\n): Promise<(apdu: Uint8Array) => Promise<Uint8Array>> {\n await port.write(BLE_MTU_REQUEST);\n const mtu = bleMtu(await port.read());\n let inFlight = false;\n return async (apdu) => {\n if (inFlight) {\n throw input(\"exchange is already in flight on this link\");\n }\n inFlight = true;\n try {\n for (const frame of bleFrames(apdu, mtu)) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- frames are ordered on one link\n await port.write(frame);\n }\n const assemble = bleAssembler(mtu);\n for (;;) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- response frames are ordered\n const complete = assemble.push(await port.read());\n if (complete !== undefined) {\n return complete;\n }\n }\n } finally {\n inFlight = false;\n }\n };\n}\n\n/**\n * A `DeviceIo` backed by a raw APDU exchange: `message` requests are answered with `apdu`, any\n * other request kind is `unsupported` — a Ledger device cannot take a QR or compare exchange.\n */\nexport function ledgerIo(apdu: (apdu: Uint8Array) => Promise<Uint8Array>): DeviceIo {\n return {\n exchange: async (request: DeviceRequest): Promise<DeviceResponse> => {\n if (request.kind !== \"message\") {\n throw new WalletError(\"unsupported\", \"the ledger transport only carries APDU messages\");\n }\n return { kind: \"message\", data: await apdu(request.data) };\n },\n };\n}\n","/**\n * OneKey Protocol-V1 transport — the host contract for `device: \"onekey\"` operations. Every\n * `message` exchange carries one framed command in `request.data` and the device answers one framed\n * message back; the kernel owns the protobuf layer, the host only moves bytes.\n *\n * USB: both directions travel in 64-byte HID reports. The first report carries a 9-byte header —\n * `3f 23 23`, BE u16 message type, BE u32 payload length — and 55 payload bytes; every continuation\n * report starts with `3f` and carries 63. Write `request.data` report by report; to read an answer,\n * collect reports until `oneKeyAnswerLength(firstReport, \"usb\")` bytes have arrived and hand the\n * whole sequence back. The firmware may leave stale bytes in the final report's padding — only the\n * declared payload is meaningful, and the kernel reads only that.\n *\n * BLE: GATT service `00000001-0000-1000-8000-00805f9b34fb`, write characteristic\n * `00000002-0000-1000-8000-00805f9b34fb`, notify characteristic\n * `00000003-0000-1000-8000-00805f9b34fb`. Write `request.data` — the same 64-byte report sequence;\n * the BLE chip counts reports, not write calls — split into writes at or below the negotiated MTU.\n * The answer arrives as notifications of up to MTU bytes forming one stream: `3f 23 23` + type +\n * length + exactly `length` payload bytes (the chip strips the USB continuation markers), so\n * concatenate notifications until `oneKeyAnswerLength(first, \"ble\")`.\n *\n * `oneKeyAnswerLength` returns the total byte count to collect for one device answer from its first\n * chunk — USB report count times 64, or the BLE header-plus-payload size — and throws on a chunk\n * that is not a OneKey frame.\n */\nimport type { DeviceIo, DeviceRequest, DeviceResponse } from \"../protocol/hardware.ts\";\nimport { WalletError } from \"../types.ts\";\nimport type { BlePort, HidPort } from \"./ports.ts\";\n\nconst REPORT_SIZE = 64;\n\nconst input = (message: string): WalletError => new WalletError(\"invalid-input\", message);\nconst integrity = (message: string): WalletError => new WalletError(\"integrity\", message);\n\nexport const oneKeyAnswerLength = (firstChunk: Uint8Array, transport: \"usb\" | \"ble\"): number => {\n if (\n firstChunk.length < 9 ||\n firstChunk[0] !== 0x3f ||\n firstChunk[1] !== 0x23 ||\n firstChunk[2] !== 0x23\n ) {\n throw input(\"the device answer does not start with the OneKey header\");\n }\n const length = new DataView(\n firstChunk.buffer,\n firstChunk.byteOffset,\n firstChunk.length,\n ).getUint32(5);\n return transport === \"usb\" ? 64 * Math.max(1, Math.ceil((8 + length) / 63)) : 9 + length;\n};\n\n/**\n * Reads `port` until `answerLength(first chunk)` bytes have arrived; returns the whole sequence.\n * Over USB every report is exactly 64 bytes; over BLE a notification may be any size, but the\n * stream must stop exactly at the announced length — a short or long transport read is `integrity`,\n * like the Ledger assembler's violations.\n */\nconst collect = async (port: HidPort | BlePort, transport: \"usb\" | \"ble\"): Promise<Uint8Array> => {\n const first = await port.read();\n if (transport === \"usb\" && first.length !== REPORT_SIZE) {\n throw integrity(\"a HID answer report is not 64 bytes\");\n }\n const total = oneKeyAnswerLength(first, transport);\n const chunks = [first];\n let collected = first.length;\n while (collected < total) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- one chunk per transport read\n const chunk = await port.read();\n if (chunk.length === 0) {\n throw integrity(\"the device answer stalled on an empty read\");\n }\n if (transport === \"usb\" && chunk.length !== REPORT_SIZE) {\n throw integrity(\"a HID answer report is not 64 bytes\");\n }\n chunks.push(chunk);\n collected += chunk.length;\n }\n if (collected !== total) {\n throw integrity(\"the device answer overshot its announced length\");\n }\n const data = new Uint8Array(collected);\n let at = 0;\n for (const chunk of chunks) {\n data.set(chunk, at);\n at += chunk.length;\n }\n return data;\n};\n\n/**\n * One framed command exchange over USB HID: writes `data` report by report, then collects the whole\n * report sequence of the answer. One call at a time — an interleaved call while a previous one is\n * in flight is `invalid-input`.\n */\nexport function oneKeyHidExchange(port: HidPort): (data: Uint8Array) => Promise<Uint8Array> {\n let inFlight = false;\n return async (data) => {\n if (inFlight) {\n throw input(\"exchange is already in flight on this link\");\n }\n if (data.length === 0 || data.length % REPORT_SIZE !== 0) {\n throw input(\"the request is not a whole number of 64-byte HID reports\");\n }\n inFlight = true;\n try {\n for (let at = 0; at < data.length; at += REPORT_SIZE) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- reports are ordered on one link\n await port.write(data.subarray(at, at + REPORT_SIZE));\n }\n return await collect(port, \"usb\");\n } finally {\n inFlight = false;\n }\n };\n}\n\n/**\n * The same exchange over BLE: `data` — the same 64-byte report sequence — is split into writes of\n * at most `mtu` bytes (the chip counts reports, not write calls), and the answer is the\n * concatenated notification stream. One call at a time — interleaving is `invalid-input`.\n */\nexport function oneKeyBleExchange(\n port: BlePort,\n mtu: number,\n): (data: Uint8Array) => Promise<Uint8Array> {\n if (!Number.isSafeInteger(mtu) || mtu < 1) {\n throw input(\"BLE MTU is not a positive integer\");\n }\n let inFlight = false;\n return async (data) => {\n if (inFlight) {\n throw input(\"exchange is already in flight on this link\");\n }\n if (data.length === 0) {\n throw input(\"the request is empty\");\n }\n inFlight = true;\n try {\n for (let at = 0; at < data.length; at += mtu) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- writes are ordered on one link\n await port.write(data.subarray(at, at + mtu));\n }\n return await collect(port, \"ble\");\n } finally {\n inFlight = false;\n }\n };\n}\n\n/**\n * A `DeviceIo` backed by a framed exchange: `message` requests are written verbatim, any other\n * request kind is `unsupported` — a OneKey device cannot take a QR or compare exchange.\n */\nexport function oneKeyIo(exchange: (data: Uint8Array) => Promise<Uint8Array>): DeviceIo {\n return {\n exchange: async (request: DeviceRequest): Promise<DeviceResponse> => {\n if (request.kind !== \"message\") {\n throw new WalletError(\"unsupported\", \"the onekey transport only carries framed messages\");\n }\n return { kind: \"message\", data: await exchange(request.data) };\n },\n };\n}\n","/**\n * The hardware module of @qntx/wallet: `hardware(wallet)` returns the external-signer API. Every\n * call drives one kernel device operation — `hardware.begin`, then `hardware.step` for each\n * exchange the kernel asks for, until `done`. The host only transports frames; the kernel validates\n * every request, decodes every answer and verifies every signature, and this module re-checks a\n * sign result the same way `chains().sign` does. An operation is never left running: any abort or\n * transport failure cancels it best-effort before the promise settles.\n *\n * `qrParts`/`qrReader` are the pure UR plumbing for air-gapped (QR) transports: parts are the\n * uppercase fountain strings a device scans, the reader folds scanned strings back into the payload\n * and only accepts the UR types the operation advertised.\n */\nimport { isUrType, toQrString, UrDecoder, UrEncoder } from \"@qntx/ur\";\n\nimport { checkSignResult } from \"../chains/check.ts\";\nimport { integrity } from \"../channel.ts\";\nimport { internalsOf } from \"../internal.ts\";\nimport type { WalletInternals } from \"../internal.ts\";\nimport type {\n DeviceIo,\n HardwareOperation,\n HardwareResult,\n HardwareStep,\n QrPayload,\n} from \"../protocol/hardware.ts\";\nimport type { ResultOf } from \"../protocol/index.ts\";\nimport { WalletError } from \"../types.ts\";\nimport type { SignerTask, VerifyFactor, Wallet } from \"../types.ts\";\n\nexport type {\n DeviceDisplay,\n DeviceIo,\n DeviceRequest,\n DeviceResponse,\n HardwareDevice,\n HardwareOperation,\n HardwareResult,\n HardwareStep,\n QrPayload,\n} from \"../protocol/hardware.ts\";\n\nexport { ledgerBleExchange, ledgerHidExchange, ledgerIo } from \"./ledger.ts\";\nexport { oneKeyBleExchange, oneKeyHidExchange, oneKeyIo } from \"./onekey.ts\";\nexport type { BlePort, HidPort } from \"./ports.ts\";\n\n/** One running device operation: observe every exchange (and the verified `done`), cancel ends it. */\nexport type HardwareTask = SignerTask<HardwareStep, HardwareResult>;\n\nexport type HardwareApi = {\n /**\n * Runs one device operation — pair, accounts, sign or verify-address — begin, then fold each\n * `exchange` step through `options.io.exchange` until `done`. A second `start` cancels the\n * running task. A `sign` result is verified (`chains().sign` rules) before `done` is emitted; a\n * rejected exchange or a kernel error cancels the operation best-effort and rejects `result`;\n * `cancel` answers `cancelled`.\n */\n readonly start: (\n op: HardwareOperation,\n options: { readonly io: DeviceIo; readonly verify?: VerifyFactor },\n ) => HardwareTask;\n};\n\nconst cancelledError = (): WalletError =>\n new WalletError(\"cancelled\", \"the device operation was aborted\");\n\nfunction run(\n internals: WalletInternals,\n op: HardwareOperation,\n options: { readonly io: DeviceIo; readonly verify?: VerifyFactor },\n): HardwareTask {\n const { io, verify } = options;\n const listeners = new Set<(step: HardwareStep) => void>();\n /** The most recent step reported — a late observe starts from it. */\n let current: HardwareStep | undefined;\n let opId: string | undefined;\n /** `cancel` raced `hardware.begin` — fire `hardware.cancel` the moment the opId lands. */\n let cancelRequested = false;\n /** A live read — a plain property access lets TS and the linter treat the flag as constant. */\n const isCancelled = (): boolean => cancelRequested;\n let ackCancel: (() => void) | undefined;\n let cancelAck: Promise<void> | undefined;\n let done = false;\n let resolveResult!: (result: HardwareResult) => void;\n let rejectResult!: (error: unknown) => void;\n const result = new Promise<HardwareResult>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n // The task owns `result`'s rejection — it must never surface as unhandled.\n void (async (): Promise<void> => {\n try {\n await result;\n } catch {\n // `result` itself surfaces the WalletError to whoever awaited it.\n }\n })();\n\n const emit = (step: HardwareStep): void => {\n current = step;\n for (const listener of listeners) {\n listener(step);\n }\n };\n\n const cancel = async (): Promise<void> => {\n if (done) {\n return;\n }\n cancelRequested = true;\n if (opId === undefined) {\n // `hardware.begin` has not answered: remember and resolve once the deferred cancel lands.\n cancelAck ??= new Promise<void>((resolve) => {\n ackCancel = resolve;\n });\n await cancelAck;\n return;\n }\n await internals.call(\"hardware.cancel\", { opId }).catch(() => undefined);\n };\n\n void (async (): Promise<void> => {\n try {\n const beginCall = async (): Promise<ResultOf<\"hardware.begin\">> =>\n internals.secretCall(\"hardware.begin\", async (wire) => ({\n op,\n ...(verify === undefined\n ? {}\n : { verify: await internals.resolveVerifyFactor(verify, wire) }),\n }));\n // The user verification lives inside begin; the exchanges that follow are not part of it.\n const begin =\n verify === undefined ? await beginCall() : await internals.withVerifying(beginCall);\n ({ opId } = begin);\n if (cancelRequested) {\n await internals.call(\"hardware.cancel\", { opId }).catch(() => undefined);\n emit(begin.step);\n done = true;\n rejectResult(cancelledError());\n ackCancel?.();\n return;\n }\n let { step } = begin;\n while (step.kind === \"exchange\" && !isCancelled()) {\n emit(step);\n // oxlint-disable-next-line eslint/no-await-in-loop -- one exchange at a time by design.\n const response = await io.exchange(step.request, {\n device: step.device,\n ...(step.display === undefined ? {} : { display: step.display }),\n });\n if (isCancelled()) {\n throw cancelledError();\n }\n // oxlint-disable-next-line eslint/no-await-in-loop -- one exchange at a time by design.\n step = await internals.call(\"hardware.step\", { opId, response });\n }\n if (isCancelled()) {\n throw cancelledError();\n }\n if (step.kind !== \"done\") {\n throw integrity(\"hardware.step answered a step kind the wire does not define\");\n }\n const outcome = step.result;\n if (outcome.kind !== op.kind) {\n throw integrity(\"operation result does not match the operation\");\n }\n if (outcome.kind === \"sign\" && op.kind === \"sign\") {\n // The `done` step goes out only once the signature verifies — an observer never sees a\n // forged signature reported as done.\n await checkSignResult(internals, op.request, outcome.result);\n }\n emit(step);\n done = true;\n resolveResult(outcome);\n } catch (error) {\n done = true;\n ackCancel?.();\n if (opId !== undefined) {\n await internals.call(\"hardware.cancel\", { opId }).catch(() => undefined);\n }\n if (cancelRequested) {\n rejectResult(cancelledError());\n } else {\n // A host transport failure or a kernel error propagates as itself; only the channel's own\n // validation failures are WalletErrors already.\n rejectResult(error);\n }\n }\n })();\n\n return {\n observe: (listener) => {\n listeners.add(listener);\n if (current !== undefined) {\n listener(current);\n }\n return () => {\n listeners.delete(listener);\n };\n },\n cancel,\n result,\n };\n}\n\nfunction createHardwareApi(internals: WalletInternals): HardwareApi {\n /** The running task, if any — a second `start` cancels it (the kernel does the same). */\n let active: HardwareTask | undefined;\n return {\n start: (op, options) => {\n void active?.cancel();\n active = run(internals, op, options);\n return active;\n },\n };\n}\n\nconst apis = new WeakMap<Wallet, HardwareApi>();\n\nexport function hardware(wallet: Wallet): HardwareApi {\n const internals = internalsOf(wallet);\n let api = apis.get(wallet);\n if (api === undefined) {\n api = createHardwareApi(internals);\n apis.set(wallet, api);\n }\n return api;\n}\n\n/**\n * Firmware 3.2.2 `FRAGMENT_MAX_LENGTH_DEFAULT` (rust_c/src/common/ur.rs) — the fragment size the\n * device's own encoder uses and its decoder is guaranteed to keep up with.\n */\nconst DEFAULT_FRAGMENT_LENGTH = 200;\n\n/**\n * Endless, cyclic fountain parts for one QR payload: each call returns the next uppercase UR string\n * (`UR:<type>/…`), ready for an animated QR. For single-part payloads the same frame repeats — the\n * loop is safe to drive on a timer.\n */\nexport const qrParts = (\n payload: QrPayload,\n options?: { readonly maxFragmentLength?: number },\n): (() => string) => {\n if (!isUrType(payload.type)) {\n throw new WalletError(\"invalid-input\", `not a UR type: ${payload.type}`);\n }\n const encoder = new UrEncoder(payload.type, payload.cbor, {\n maxFragmentLength: options?.maxFragmentLength ?? DEFAULT_FRAGMENT_LENGTH,\n });\n return () => {\n const next = encoder.next();\n if (typeof next.value !== \"string\") {\n throw integrity(\"fountain encoder ended\");\n }\n return toQrString(next.value);\n };\n};\n\nexport type QrReader = {\n /**\n * Feeds one scanned string. `progress` is the fountain decode ratio in [0, 1]; `payload` appears\n * once complete. Frames of a type outside `scan`, duplicates and out-of-order parts leave the\n * session unchanged; a fatal decoder failure throws `invalid-input`.\n */\n readonly receive: (part: string) => { readonly progress: number; readonly payload?: QrPayload };\n};\n\n/** An incremental reader for the frames a device shows back; only `scan` types are admitted. */\nexport const qrReader = (scan: ReadonlyArray<string>): QrReader => {\n const accept = scan.map((type) => {\n if (!isUrType(type)) {\n throw new WalletError(\"invalid-input\", `not a UR type: ${type}`);\n }\n return type;\n });\n const decoder = new UrDecoder({ accept });\n return {\n receive: (part) => {\n const outcome = decoder.receive(part);\n if (outcome.status === \"fatal\") {\n throw new WalletError(\"invalid-input\", outcome.error.message);\n }\n const { state } = decoder;\n if (state.phase === \"complete\") {\n return { progress: 1, payload: { type: state.value.type, cbor: state.value.message } };\n }\n return { progress: decoder.progress.ratio };\n },\n };\n};\n"],"mappings":";;;;;AAwBA,MAAM,WAAW;AACjB,MAAM,UAAU;AAEhB,MAAMA,eAAa,YAAiC,IAAI,YAAY,aAAa,OAAO;AACxF,MAAMC,WAAS,YAAiC,IAAI,YAAY,iBAAiB,OAAO;AAOxF,MAAM,aAAa,SAA2B;CAE5C,IAAI,KAAK,SAAS,KAAK,KAAK,SAAS,KACnC,MAAMA,QAAM,0BAA0B;AAE1C;;AAGA,S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GACxB,MAAM,IAAI,YAAY,iBAAiB,kBAAkB,QAAQ,MAAM;CAEzE,MAAM,UAAU,IAAI,UAAU,QAAQ,MAAM,QAAQ,MAAM,EACxD,mBAAmB,SAAS,qBAAqB,wBACnD,CAAC;CACD,aAAa;EACX,MAAM,OAAO,QAAQ,KAAK;EAC1B,IAAI,OAAO,KAAK,UAAU,UACxB,MAAMA,YAAU,wBAAwB;EAE1C,OAAO,WAAW,KAAK,KAAK;CAC9B;AACF;;AAYA,MAAa,YAAY,SAA0C;CACjE,MAAM,SAAS,KAAK,KAAK,SAAS;EAChC,IAAI,CAAC,SAAS,IAAI,GAChB,MAAM,IAAI,YAAY,iBAAiB,kBAAkB,MAAM;EAEjE,OAAO;CACT,CAAC;CACD,MAAM,UAAU,IAAI,UAAU,EAAE,OAAO,CAAC;CACxC,OAAO,EACL,UAAU,SAAS;EACjB,MAAM,UAAU,QAAQ,QAAQ,IAAI;EACpC,IAAI,QAAQ,WAAW,SACrB,MAAM,IAAI,YAAY,iBAAiB,QAAQ,MAAM,OAAO;EAE9D,MAAM,EAAE,UAAU;EAClB,IAAI,MAAM,UAAU,YAClB,OAAO;GAAE,UAAU;GAAG,SAAS;IAAE,MAAM,MAAM,MAAM;IAAM,MAAM,MAAM,MAAM;GAAQ;EAAE;EAEvF,OAAO,EAAE,UAAU,QAAQ,SAAS,MAAM;CAC5C,EACF;AACF"}
|
package/dist/host.d.mts
CHANGED
|
@@ -1,19 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
* Why the kernel port ended: a fault in the enclave/transport, or a deliberate host-side lock
|
|
5
|
-
* triggered by the platform (native background expiry — W7).
|
|
6
|
-
*/
|
|
7
|
-
type PortExit = "crashed" | "background";
|
|
8
|
-
/** The host packages' side of the kernel channel (worker, JSI runtime, in-process test port). */
|
|
9
|
-
type MainPort = {
|
|
10
|
-
readonly post: (message: ProtocolValue, transfer: ArrayBuffer[]) => void;
|
|
11
|
-
readonly listen: (handler: (message: unknown) => void) => () => void;
|
|
12
|
-
readonly onExit: (handler: (reason: PortExit) => void) => () => void;
|
|
13
|
-
readonly terminate: () => void;
|
|
14
|
-
};
|
|
15
|
-
/** Schedules `fn` after `delayMs` and returns a cancel function — injected by the host package. */
|
|
16
|
-
type SetTimer = (delayMs: number, fn: () => void) => () => void;
|
|
1
|
+
import { C as PasskeyConfig, j as Wallet } from "./types-CRnacSqJ.mjs";
|
|
2
|
+
import { C as ProtocolValue } from "./chains-u1M0CWkT.mjs";
|
|
3
|
+
import { ft as SignedEvent } from "./index-UclKfprm.mjs";
|
|
17
4
|
type PrfSalts = {
|
|
18
5
|
readonly first: Uint8Array;
|
|
19
6
|
readonly second?: Uint8Array;
|
|
@@ -47,11 +34,32 @@ type PasskeyCeremony = {
|
|
|
47
34
|
}) => Promise<PrfResult>;
|
|
48
35
|
};
|
|
49
36
|
/**
|
|
50
|
-
* Which vault factors a host offers: `hardware` (React Native — the platform keystore
|
|
51
|
-
*
|
|
52
|
-
* enforces the same rule; resolving here keeps a doomed request
|
|
37
|
+
* Which vault factors a host offers: `hardware` (React Native — the platform keystore factors,
|
|
38
|
+
* device and hardware, and omitted factors mean the silent device one) or `software` (web/node —
|
|
39
|
+
* passkey and password). The kernel enforces the same rule; resolving here keeps a doomed request
|
|
40
|
+
* from firing a ceremony.
|
|
53
41
|
*/
|
|
54
42
|
type FactorMode = "hardware" | "software";
|
|
43
|
+
/**
|
|
44
|
+
* Why the kernel port ended: a fault in the enclave/transport, or a deliberate host-side lock
|
|
45
|
+
* triggered by the platform (native background expiry — W7).
|
|
46
|
+
*/
|
|
47
|
+
type PortExit = "crashed" | "background";
|
|
48
|
+
/** The host packages' side of the kernel channel (worker, JSI runtime, in-process test port). */
|
|
49
|
+
type MainPort = {
|
|
50
|
+
readonly post: (message: ProtocolValue, transfer: ArrayBuffer[]) => void;
|
|
51
|
+
readonly listen: (handler: (message: unknown) => void) => () => void;
|
|
52
|
+
readonly onExit: (handler: (reason: PortExit) => void) => () => void;
|
|
53
|
+
readonly terminate: () => void;
|
|
54
|
+
};
|
|
55
|
+
/** Schedules `fn` after `delayMs` and returns a cancel function — injected by the host package. */
|
|
56
|
+
type SetTimer = (delayMs: number, fn: () => void) => () => void;
|
|
57
|
+
/**
|
|
58
|
+
* Posted-but-unanswered requests. Kept well below the native runtime's inbound cap of 64
|
|
59
|
+
* (KernelRuntime's kMaxInboundFrames, past which it fails closed) so a busy kernel delays requests
|
|
60
|
+
* instead of killing the session; Web/Node get the same bound so all hosts behave alike.
|
|
61
|
+
*/
|
|
62
|
+
export declare const MAX_IN_FLIGHT = 32;
|
|
55
63
|
type ConnectOptions = {
|
|
56
64
|
readonly spawn: () => MainPort;
|
|
57
65
|
/** Fixed by the host entry: `hardware` on React Native, `software` on web and node. */
|