@onekeyfe/hwk-keystone-adapter 1.2.8-alpha.54 → 1.2.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +47 -9
- package/dist/index.d.ts +47 -9
- package/dist/index.js +453 -96
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +459 -96
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
// src/urEngine/KeystoneUrEngine.ts
|
|
2
2
|
import { generateAddressFromXpub } from "@keystonehq/bc-ur-registry-eth";
|
|
3
|
+
import {
|
|
4
|
+
CryptoAccount,
|
|
5
|
+
CryptoHDKey,
|
|
6
|
+
CryptoMultiAccounts,
|
|
7
|
+
ScriptExpressions,
|
|
8
|
+
extend as extend3
|
|
9
|
+
} from "@keystonehq/bc-ur-registry";
|
|
10
|
+
import { ScriptExpression } from "@keystonehq/bc-ur-registry/dist/ScriptExpression.js";
|
|
3
11
|
import { Curve, KeystoneSDK, QRHardwareCallVersion, UR } from "@keystonehq/keystone-sdk";
|
|
4
12
|
import bs58check from "bs58check";
|
|
5
13
|
import * as bitcoin from "bitcoinjs-lib";
|
|
@@ -179,6 +187,35 @@ function toParsedAccount(key) {
|
|
|
179
187
|
};
|
|
180
188
|
}
|
|
181
189
|
var BIP32_HARDENED_OFFSET = 2147483648;
|
|
190
|
+
function isExportedAccountPath(path) {
|
|
191
|
+
return /^m(?:\/\d+')+(?:\/\d+)*$/.test(path) && path.slice(2).split("/").every(
|
|
192
|
+
(segment) => Number(segment.endsWith("'") ? segment.slice(0, -1) : segment) < BIP32_HARDENED_OFFSET
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
function checkExportedKey(key, account, masterFingerprint, unsupportedDescriptor) {
|
|
196
|
+
if (unsupportedDescriptor || key.isMaster() || key.isPrivateKey()) {
|
|
197
|
+
return { rejected: "unusable-key" };
|
|
198
|
+
}
|
|
199
|
+
const source = key.getOrigin()?.getSourceFingerprint();
|
|
200
|
+
if (source && source.toString("hex") !== masterFingerprint) {
|
|
201
|
+
return { rejected: "different-wallet" };
|
|
202
|
+
}
|
|
203
|
+
if (!account.extendedPublicKey) {
|
|
204
|
+
return /^[0-9a-f]{64}$/i.test(account.publicKey) ? { identity: account.publicKey } : { rejected: "unusable-key" };
|
|
205
|
+
}
|
|
206
|
+
try {
|
|
207
|
+
const node = HDKey.fromExtendedKey(account.extendedPublicKey);
|
|
208
|
+
if (node.privateKey || !node.publicKey || !node.chainCode || node.publicKey.toString("hex") !== account.publicKey.toLowerCase()) {
|
|
209
|
+
return { rejected: "unusable-key" };
|
|
210
|
+
}
|
|
211
|
+
return { identity: `${account.publicKey}:${node.chainCode.toString("hex")}` };
|
|
212
|
+
} catch {
|
|
213
|
+
return { rejected: "unusable-key" };
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
function unexpectedQrCodeError(message, code = HardwareErrorCode.InvalidParams) {
|
|
217
|
+
return createHwkError({ code, message, params: { reason: "unexpected-qr-code" } });
|
|
218
|
+
}
|
|
182
219
|
function relativeHdPath(relativeDerivePath) {
|
|
183
220
|
const segments = relativeDerivePath.replace(/^m\//i, "").split("/");
|
|
184
221
|
const valid = segments.every(
|
|
@@ -192,7 +229,7 @@ function relativeHdPath(relativeDerivePath) {
|
|
|
192
229
|
}
|
|
193
230
|
return `m/${segments.join("/")}`;
|
|
194
231
|
}
|
|
195
|
-
var FIRMWARE_VERSION = /^\d{1,4}(\.\d{1,4}){1,3}(-[0-9A-Za-z
|
|
232
|
+
var FIRMWARE_VERSION = /^\d{1,4}(\.\d{1,4}){1,3}(-[0-9A-Za-z.-]{1,20})?$/;
|
|
196
233
|
var DEVICE_TEXT = /^[^\p{Cc}\p{Cf}]{1,64}$/u;
|
|
197
234
|
function deviceText(value, pattern) {
|
|
198
235
|
return typeof value === "string" && pattern.test(value) ? value : void 0;
|
|
@@ -223,7 +260,8 @@ var KeystoneUrEngine = class {
|
|
|
223
260
|
const ur = this.sdk.generateKeyDerivationCall({
|
|
224
261
|
schemas: input.schemas.map((schema) => ({
|
|
225
262
|
path: schema.path,
|
|
226
|
-
curve: DERIVATION_CURVE[schema.curve ?? "secp256k1"]
|
|
263
|
+
curve: DERIVATION_CURVE[schema.curve ?? "secp256k1"],
|
|
264
|
+
chainType: schema.chainType
|
|
227
265
|
})),
|
|
228
266
|
origin: input.origin,
|
|
229
267
|
version: QRHardwareCallVersion.V1
|
|
@@ -247,6 +285,90 @@ var KeystoneUrEngine = class {
|
|
|
247
285
|
}
|
|
248
286
|
return this.parseMultiAccounts(ur);
|
|
249
287
|
}
|
|
288
|
+
/**
|
|
289
|
+
* Device exports are opt-in: request responses retain their existing format/path checks. An
|
|
290
|
+
* export carries whatever the device syncs to other wallets, so each key is checked on its own: a
|
|
291
|
+
* key that fails lands in `rejectedPaths` instead of discarding the whole export.
|
|
292
|
+
*/
|
|
293
|
+
parseAccountExport(ur) {
|
|
294
|
+
let parsed;
|
|
295
|
+
let keys;
|
|
296
|
+
const unsupportedDescriptors = /* @__PURE__ */ new Set();
|
|
297
|
+
try {
|
|
298
|
+
const { cbor } = toSdkUr(ur);
|
|
299
|
+
if (ur.urType === "crypto-account") {
|
|
300
|
+
if (!Object.values(ScriptExpressions).some((script) => script.getTag() === 409)) {
|
|
301
|
+
Object.assign(ScriptExpressions, { TAPROOT: new ScriptExpression(409, "tr") });
|
|
302
|
+
}
|
|
303
|
+
extend3.cbor.patchTags([409]);
|
|
304
|
+
const account = CryptoAccount.fromCBOR(cbor);
|
|
305
|
+
keys = account.getOutputDescriptors().map((output, index) => {
|
|
306
|
+
const key = output.getHDKey();
|
|
307
|
+
const path = key?.getOrigin()?.getPath();
|
|
308
|
+
const script = output.getScriptExpressions().map((item) => item.getExpression()).join("/");
|
|
309
|
+
const validScript = path?.startsWith("44'/0'/") && script === "pkh" || path?.startsWith("49'/0'/") && script === "sh/wpkh" || path?.startsWith("84'/0'/") && script === "wpkh" || path?.startsWith("86'/0'/") && script === "tr";
|
|
310
|
+
const children = key?.getChildren();
|
|
311
|
+
if (!key) throw new Error("Unsupported account descriptor");
|
|
312
|
+
if (!validScript || children && children.getPath() !== "0/*") {
|
|
313
|
+
unsupportedDescriptors.add(index);
|
|
314
|
+
}
|
|
315
|
+
return key;
|
|
316
|
+
});
|
|
317
|
+
const result = this.sdk.parseAccount(toSdkUr(ur));
|
|
318
|
+
parsed = {
|
|
319
|
+
masterFingerprint: requireBip32MasterFingerprint(result.masterFingerprint),
|
|
320
|
+
accounts: result.keys.map(toParsedAccount)
|
|
321
|
+
};
|
|
322
|
+
} else if (ur.urType === "crypto-multi-accounts") {
|
|
323
|
+
keys = CryptoMultiAccounts.fromCBOR(cbor).getKeys();
|
|
324
|
+
parsed = this.parseMultiAccounts(ur);
|
|
325
|
+
} else if (ur.urType === "crypto-hdkey") {
|
|
326
|
+
keys = [CryptoHDKey.fromCBOR(cbor)];
|
|
327
|
+
parsed = this.parseAccountResponse(ur);
|
|
328
|
+
} else {
|
|
329
|
+
throw new Error("Unsupported account export type");
|
|
330
|
+
}
|
|
331
|
+
if (!keys.length || keys.length !== parsed.accounts.length) {
|
|
332
|
+
throw new Error("Empty account export");
|
|
333
|
+
}
|
|
334
|
+
} catch {
|
|
335
|
+
throw unexpectedQrCodeError(
|
|
336
|
+
"Unable to read account export; scan a supported Keystone account export code"
|
|
337
|
+
);
|
|
338
|
+
}
|
|
339
|
+
const byPath = /* @__PURE__ */ new Map();
|
|
340
|
+
parsed.accounts.forEach((account, index) => {
|
|
341
|
+
if (!isExportedAccountPath(account.path)) return;
|
|
342
|
+
const entry = byPath.get(account.path) ?? {};
|
|
343
|
+
byPath.set(account.path, entry);
|
|
344
|
+
const check = checkExportedKey(
|
|
345
|
+
keys[index],
|
|
346
|
+
account,
|
|
347
|
+
parsed.masterFingerprint,
|
|
348
|
+
unsupportedDescriptors.has(index)
|
|
349
|
+
);
|
|
350
|
+
if (check.rejected === "different-wallet") {
|
|
351
|
+
entry.rejected = check.rejected;
|
|
352
|
+
} else if (check.identity === void 0) {
|
|
353
|
+
entry.rejected ?? (entry.rejected = check.rejected);
|
|
354
|
+
} else if (entry.identity === void 0) {
|
|
355
|
+
entry.account = account;
|
|
356
|
+
entry.identity = check.identity;
|
|
357
|
+
} else if (entry.identity !== check.identity && entry.rejected !== "different-wallet") {
|
|
358
|
+
entry.rejected = "conflicting-keys";
|
|
359
|
+
}
|
|
360
|
+
});
|
|
361
|
+
const accounts = [];
|
|
362
|
+
const rejectedPaths = [];
|
|
363
|
+
byPath.forEach((entry, path) => {
|
|
364
|
+
if (entry.account && entry.rejected !== "different-wallet" && entry.rejected !== "conflicting-keys") {
|
|
365
|
+
accounts.push(entry.account);
|
|
366
|
+
} else if (entry.rejected) {
|
|
367
|
+
rejectedPaths.push({ path, reason: entry.rejected });
|
|
368
|
+
}
|
|
369
|
+
});
|
|
370
|
+
return { ...parsed, accounts, rejectedPaths };
|
|
371
|
+
}
|
|
250
372
|
// --- EVM ---
|
|
251
373
|
buildEthSignRequest(input) {
|
|
252
374
|
const ur = this.sdk.eth.generateSignRequest({
|
|
@@ -331,10 +453,10 @@ var KeystoneUrEngine = class {
|
|
|
331
453
|
sameTransaction = false;
|
|
332
454
|
}
|
|
333
455
|
if (!sameTransaction) {
|
|
334
|
-
throw
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
456
|
+
throw unexpectedQrCodeError(
|
|
457
|
+
"Keystone returned a PSBT for another transaction than the one requested",
|
|
458
|
+
HardwareErrorCode.DeviceMismatch
|
|
459
|
+
);
|
|
338
460
|
}
|
|
339
461
|
return signedPsbtHex;
|
|
340
462
|
}
|
|
@@ -537,12 +659,15 @@ function accountKey(hwkChain, path) {
|
|
|
537
659
|
function createDeviceRecord(masterFingerprint) {
|
|
538
660
|
return {
|
|
539
661
|
masterFingerprint,
|
|
540
|
-
connectId: walletConnectId(masterFingerprint)
|
|
541
|
-
importedAt: Date.now()
|
|
662
|
+
connectId: walletConnectId(masterFingerprint)
|
|
542
663
|
};
|
|
543
664
|
}
|
|
544
665
|
var CAPABILITIES = { persistentDeviceIdentity: true };
|
|
545
666
|
function toDeviceInfo(record) {
|
|
667
|
+
return toDeviceInfoForConnection(record, record.usbSessionId ? "usb" : "qr");
|
|
668
|
+
}
|
|
669
|
+
function toDeviceInfoForConnection(record, connectionType) {
|
|
670
|
+
const firmwareVersion = connectionType === "usb" ? record.usbFirmwareVersion : record.deviceVersion;
|
|
546
671
|
let availableChannels = ["qr"];
|
|
547
672
|
if (record.usbSessionId) {
|
|
548
673
|
availableChannels = record.qrSynced ? ["qr", "usb"] : ["usb"];
|
|
@@ -551,11 +676,13 @@ function toDeviceInfo(record) {
|
|
|
551
676
|
vendor: "keystone",
|
|
552
677
|
model: record.model ?? "unknown",
|
|
553
678
|
modelName: record.model,
|
|
554
|
-
firmwareVersion:
|
|
679
|
+
firmwareVersion: firmwareVersion ?? "0.0.0",
|
|
555
680
|
deviceId: record.masterFingerprint,
|
|
556
681
|
connectId: record.connectId,
|
|
557
|
-
connectionType
|
|
558
|
-
capabilities:
|
|
682
|
+
connectionType,
|
|
683
|
+
capabilities: {
|
|
684
|
+
...CAPABILITIES
|
|
685
|
+
},
|
|
559
686
|
raw: {
|
|
560
687
|
availableChannels,
|
|
561
688
|
masterFingerprint: record.masterFingerprint,
|
|
@@ -575,6 +702,31 @@ function placeholderDeviceInfo() {
|
|
|
575
702
|
};
|
|
576
703
|
}
|
|
577
704
|
|
|
705
|
+
// src/adapter/firmwareCapabilities.ts
|
|
706
|
+
var MULTI_COIN = {
|
|
707
|
+
variant: "multi-coin",
|
|
708
|
+
supportedChains: ["btc", "evm", "sol", "tron"]
|
|
709
|
+
};
|
|
710
|
+
var BITCOIN_ONLY = {
|
|
711
|
+
variant: "bitcoin-only",
|
|
712
|
+
supportedChains: ["btc"]
|
|
713
|
+
};
|
|
714
|
+
var CYPHERPUNK = {
|
|
715
|
+
variant: "cypherpunk",
|
|
716
|
+
// Firmware support alone is insufficient: this adapter has no Zcash/Monero methods yet.
|
|
717
|
+
supportedChains: ["btc"]
|
|
718
|
+
};
|
|
719
|
+
function getKeystoneFirmwareProfile(firmwareVersion) {
|
|
720
|
+
if (!firmwareVersion || firmwareVersion === "0.0.0") return void 0;
|
|
721
|
+
const version = /^\d{1,4}(?:\.\d{1,4}){1,3}(?:-([a-z0-9.-]{1,40}))?$/i.exec(firmwareVersion);
|
|
722
|
+
if (!version) return void 0;
|
|
723
|
+
const suffix = version[1]?.toUpperCase();
|
|
724
|
+
if (!suffix) return MULTI_COIN;
|
|
725
|
+
if (suffix === "C" || suffix === "CYPHERPUNK" || suffix === "CYPHERPUNK-B") return CYPHERPUNK;
|
|
726
|
+
if (suffix === "B" || suffix === "BTC" || suffix === "BTC-ONLY") return BITCOIN_ONLY;
|
|
727
|
+
return void 0;
|
|
728
|
+
}
|
|
729
|
+
|
|
578
730
|
// src/utils/queueKey.ts
|
|
579
731
|
import { isHardwareOperationId, parseWalletMasterFingerprint as parseWalletMasterFingerprint2 } from "@onekeyfe/hwk-adapter-core";
|
|
580
732
|
var KEYSTONE_COLD_START_JOB_LABEL = "keystone-cold-start";
|
|
@@ -614,10 +766,36 @@ function keystoneBtcParamsFailure(params) {
|
|
|
614
766
|
}
|
|
615
767
|
return void 0;
|
|
616
768
|
}
|
|
769
|
+
var USB_ATTACH_FAILURE_REASONS = {
|
|
770
|
+
[HardwareErrorCode2.DeviceMismatch]: "wallet-mismatch",
|
|
771
|
+
[HardwareErrorCode2.DeviceNotInitialized]: "wallet-mismatch",
|
|
772
|
+
[HardwareErrorCode2.DeviceLocked]: "device-locked"
|
|
773
|
+
};
|
|
774
|
+
var KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS = 24;
|
|
617
775
|
var KEYSTONE_USB_REATTACH_PROBE_ATTEMPTS = 4;
|
|
618
776
|
var KEYSTONE_USB_REATTACH_PROBE_INTERVAL_MS = 500;
|
|
777
|
+
var CHAIN_TYPE_BY_CHAIN = {
|
|
778
|
+
evm: "ETH",
|
|
779
|
+
sol: "SOL",
|
|
780
|
+
tron: "TRX"
|
|
781
|
+
};
|
|
782
|
+
var BTC_CHAIN_TYPE_BY_PURPOSE = {
|
|
783
|
+
44: "BTC_LEGACY",
|
|
784
|
+
49: "BTC",
|
|
785
|
+
84: "BTC_NATIVE_SEGWIT",
|
|
786
|
+
86: "BTC_TAPROOT"
|
|
787
|
+
};
|
|
788
|
+
function hardwareCallChainType(chain, path) {
|
|
789
|
+
if (chain !== "btc") return CHAIN_TYPE_BY_CHAIN[chain];
|
|
790
|
+
const purpose = normalizePath(path).match(/^m\/(\d+)'/)?.[1];
|
|
791
|
+
return purpose ? BTC_CHAIN_TYPE_BY_PURPOSE[Number(purpose)] : void 0;
|
|
792
|
+
}
|
|
619
793
|
function keySchema(chain, path) {
|
|
620
|
-
return {
|
|
794
|
+
return {
|
|
795
|
+
path,
|
|
796
|
+
curve: chain === "sol" ? "ed25519" : "secp256k1",
|
|
797
|
+
chainType: hardwareCallChainType(chain, path)
|
|
798
|
+
};
|
|
621
799
|
}
|
|
622
800
|
function waitForKeystoneUsbReattachProbe() {
|
|
623
801
|
return new Promise((resolve) => {
|
|
@@ -641,12 +819,42 @@ function exactHex(value) {
|
|
|
641
819
|
function invalidHexFailure(field) {
|
|
642
820
|
return failure(HardwareErrorCode2.InvalidParams, `${field} must be an even-length hex string`);
|
|
643
821
|
}
|
|
644
|
-
function
|
|
645
|
-
const
|
|
822
|
+
function exportedAccountAt(parsed, path) {
|
|
823
|
+
const rejected = parsed.rejectedPaths?.find((entry) => normalizePath(entry.path) === path);
|
|
824
|
+
switch (rejected?.reason) {
|
|
825
|
+
case "different-wallet":
|
|
826
|
+
throw createHwkError2({
|
|
827
|
+
code: HardwareErrorCode2.DeviceMismatch,
|
|
828
|
+
message: "Account export contains a different wallet fingerprint"
|
|
829
|
+
});
|
|
830
|
+
case "conflicting-keys":
|
|
831
|
+
throw createHwkError2({
|
|
832
|
+
code: HardwareErrorCode2.DeviceMismatch,
|
|
833
|
+
message: "Account export contains conflicting keys for the same path"
|
|
834
|
+
});
|
|
835
|
+
case "unusable-key":
|
|
836
|
+
throw unexpectedQrCodeError(`Account export key at ${path} is not usable`);
|
|
837
|
+
default:
|
|
838
|
+
return parsed.accounts.find((returned) => normalizePath(returned.path) === path);
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
function parseScannedAnswer(parse) {
|
|
842
|
+
try {
|
|
843
|
+
return parse();
|
|
844
|
+
} catch (error) {
|
|
845
|
+
if (typeof error?.code === "number") throw error;
|
|
846
|
+
throw unexpectedQrCodeError(
|
|
847
|
+
`Scanned code is not this request's answer: ${error instanceof Error ? error.message : ""}`
|
|
848
|
+
);
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
function requireExportedPath(parsed, path, accountExport = false) {
|
|
852
|
+
const account = exportedAccountAt(parsed, path);
|
|
646
853
|
if (!account) {
|
|
647
854
|
throw createHwkError2({
|
|
648
|
-
code: HardwareErrorCode2.DeviceMismatch,
|
|
649
|
-
message: `Keystone did not return the requested derivation path (${path})
|
|
855
|
+
code: accountExport ? HardwareErrorCode2.DevicePathForbidden : HardwareErrorCode2.DeviceMismatch,
|
|
856
|
+
message: `Keystone did not return the requested derivation path (${path})`,
|
|
857
|
+
...accountExport ? { params: { reason: "account-not-exported" } } : {}
|
|
650
858
|
});
|
|
651
859
|
}
|
|
652
860
|
return account;
|
|
@@ -660,7 +868,9 @@ function coinTypeFailure(chain, path) {
|
|
|
660
868
|
}
|
|
661
869
|
function btcAccountFailure(accountPath) {
|
|
662
870
|
if (isKeystoneSignableBtcAccountPath(accountPath)) return void 0;
|
|
663
|
-
return failure(HardwareErrorCode2.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE
|
|
871
|
+
return failure(HardwareErrorCode2.DevicePathForbidden, KEYSTONE_BTC_ACCOUNT_FORBIDDEN_MESSAGE, {
|
|
872
|
+
reason: "btc-account-limit"
|
|
873
|
+
});
|
|
664
874
|
}
|
|
665
875
|
function missingParamFailure(method, param) {
|
|
666
876
|
return failure(HardwareErrorCode2.InvalidParams, `${method} requires ${param}`);
|
|
@@ -672,6 +882,10 @@ function evmMessageSignature(sig) {
|
|
|
672
882
|
return { signature: ensure0x(sig.r + sig.s + sig.v) };
|
|
673
883
|
}
|
|
674
884
|
var KeystoneAdapter = class _KeystoneAdapter {
|
|
885
|
+
/**
|
|
886
|
+
* `qrKeyRequestLimit` caps the account paths one QR key request may ask for, below the firmware's
|
|
887
|
+
* own limit: a host with no USB to fall back on can refuse a large request before the device does.
|
|
888
|
+
*/
|
|
675
889
|
constructor(options) {
|
|
676
890
|
this.vendor = "keystone";
|
|
677
891
|
// No protocol-level cancel exists over Keystone USB, and QR has no transport
|
|
@@ -692,11 +906,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
692
906
|
params: { operationId: operation.operationId, reason }
|
|
693
907
|
});
|
|
694
908
|
const queueKey = keystoneQueueKey(operation.operationId);
|
|
695
|
-
const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
|
|
696
909
|
this._jobQueue.cancelActiveAndPending(queueKey, ended);
|
|
697
|
-
|
|
698
|
-
this._uiRegistry.cancel(void 0, void 0, operation.operationId);
|
|
699
|
-
}
|
|
910
|
+
this._uiRegistry.cancel(void 0, void 0, operation.operationId);
|
|
700
911
|
}
|
|
701
912
|
}
|
|
702
913
|
this.emitter.emit(SDK.OPERATION_ENDED, {
|
|
@@ -723,6 +934,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
723
934
|
if (!record) return;
|
|
724
935
|
this._operations.endByConnectionKey(connectId, "disconnect");
|
|
725
936
|
record.usbSessionId = void 0;
|
|
937
|
+
record.usbFirmwareVersion = void 0;
|
|
726
938
|
const info = toDeviceInfo(record);
|
|
727
939
|
if (record.qrSynced) {
|
|
728
940
|
this.emitter.emit(DEVICE.CHANGED, { type: DEVICE.CHANGED, payload: info });
|
|
@@ -732,7 +944,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
732
944
|
}
|
|
733
945
|
};
|
|
734
946
|
this._handleUsbUiEvent = (event) => {
|
|
735
|
-
this.
|
|
947
|
+
const operationId = this._activeOperationId();
|
|
948
|
+
this.emitter.emit("ui-event", operationId ? { ...event, operationId } : event);
|
|
736
949
|
};
|
|
737
950
|
// ---------------------------------------------------------------------------
|
|
738
951
|
// All-network bundle, dispatched to the per-chain methods below.
|
|
@@ -805,6 +1018,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
805
1018
|
success: true,
|
|
806
1019
|
payload: {
|
|
807
1020
|
...context.payload,
|
|
1021
|
+
...access?.channel === "qr" && access.accountExport ? { accountExport: true } : {},
|
|
808
1022
|
rootFingerprint: record ? Number.parseInt(record.masterFingerprint, 16) : void 0,
|
|
809
1023
|
deviceIdentity: record ? {
|
|
810
1024
|
vendor: "keystone",
|
|
@@ -830,6 +1044,8 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
830
1044
|
};
|
|
831
1045
|
this._origin = options?.origin ?? "OneKey";
|
|
832
1046
|
this._qrTimeoutMs = options?.qrTimeoutMs;
|
|
1047
|
+
const limit = options?.qrKeyRequestLimit;
|
|
1048
|
+
this._qrKeyRequestLimit = limit !== void 0 && Number.isInteger(limit) && limit > 0 ? Math.min(limit, KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS) : KEYSTONE_MAX_KEY_DERIVATION_SCHEMAS;
|
|
833
1049
|
this.urEngine = new KeystoneUrEngine(this._origin);
|
|
834
1050
|
this._jobQueue = new DeviceJobQueue();
|
|
835
1051
|
this._usbConnector = options?.usbConnector;
|
|
@@ -1054,23 +1270,24 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
1054
1270
|
}
|
|
1055
1271
|
getDeviceInfo(connectIdOrOperationId, deviceId) {
|
|
1056
1272
|
try {
|
|
1057
|
-
const
|
|
1273
|
+
const operation = isHardwareOperationId2(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId) : void 0;
|
|
1274
|
+
const connectId = operation?.connectId ?? connectIdOrOperationId;
|
|
1058
1275
|
const { record } = this._resolveTarget(connectId, deviceId);
|
|
1059
1276
|
if (!record) {
|
|
1060
1277
|
return Promise.resolve(
|
|
1061
1278
|
failure(HardwareErrorCode2.DeviceNotFound, "Unknown Keystone device")
|
|
1062
1279
|
);
|
|
1063
1280
|
}
|
|
1064
|
-
|
|
1281
|
+
const info = operation ? toDeviceInfoForConnection(record, operation.connectionType === "qr" ? "qr" : "usb") : toDeviceInfo(record);
|
|
1282
|
+
return Promise.resolve(success(info));
|
|
1065
1283
|
} catch (err) {
|
|
1066
1284
|
return Promise.resolve(this._errorToFailure(err));
|
|
1067
1285
|
}
|
|
1068
1286
|
}
|
|
1069
1287
|
cancel(connectId) {
|
|
1070
|
-
let namedOperationConnectId;
|
|
1071
1288
|
if (isHardwareOperationId2(connectId)) {
|
|
1072
1289
|
try {
|
|
1073
|
-
|
|
1290
|
+
this._operations.resolve(connectId);
|
|
1074
1291
|
} catch {
|
|
1075
1292
|
return;
|
|
1076
1293
|
}
|
|
@@ -1080,15 +1297,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
1080
1297
|
message: "User aborted operation"
|
|
1081
1298
|
});
|
|
1082
1299
|
if (connectId) {
|
|
1300
|
+
const scopedOperationId = isHardwareOperationId2(connectId) ? connectId : this._operationRouteForIdentifier(connectId)?.operationId;
|
|
1083
1301
|
const queueKeys = keystoneCancelQueueKeys([
|
|
1084
1302
|
connectId,
|
|
1085
|
-
this._operationRoutes.get(connectId)?.operationId
|
|
1086
|
-
namedOperationConnectId
|
|
1303
|
+
this._operationRoutes.get(connectId)?.operationId
|
|
1087
1304
|
]);
|
|
1088
1305
|
for (const key of queueKeys) {
|
|
1089
1306
|
this._jobQueue.cancelActiveAndPending(key, reason);
|
|
1090
1307
|
}
|
|
1091
|
-
const scopedOperationId = isHardwareOperationId2(connectId) ? connectId : this._operationRouteForIdentifier(connectId)?.operationId;
|
|
1092
1308
|
if (scopedOperationId) {
|
|
1093
1309
|
this._uiRegistry.cancel(void 0, void 0, scopedOperationId);
|
|
1094
1310
|
}
|
|
@@ -1150,13 +1366,13 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
1150
1366
|
});
|
|
1151
1367
|
responseUr = await this._requestQrAndAwaitResponse(
|
|
1152
1368
|
displayDevice,
|
|
1153
|
-
{ ...requestUr, animated: false },
|
|
1369
|
+
{ ...requestUr, animated: false, allowAccountExport: true },
|
|
1154
1370
|
signal
|
|
1155
1371
|
);
|
|
1156
1372
|
}
|
|
1157
1373
|
_KeystoneAdapter._throwIfAborted(signal);
|
|
1158
|
-
const parsed = this.urEngine.parseAccountResponse(responseUr);
|
|
1159
|
-
if (
|
|
1374
|
+
const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
|
|
1375
|
+
if (!responseUr.accountExport) requireExportedPath(parsed, KEYSTONE_COLD_START_PATH);
|
|
1160
1376
|
const record = this._upsertDeviceRecord(parsed);
|
|
1161
1377
|
return success(toDeviceInfo(record));
|
|
1162
1378
|
});
|
|
@@ -1356,7 +1572,9 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
1356
1572
|
"btcSignPsbt"
|
|
1357
1573
|
);
|
|
1358
1574
|
_KeystoneAdapter._throwIfAborted(signal);
|
|
1359
|
-
const signedPsbt =
|
|
1575
|
+
const signedPsbt = parseScannedAnswer(
|
|
1576
|
+
() => this.urEngine.parseBtcPsbt(responseUr, requestPsbtHex)
|
|
1577
|
+
);
|
|
1360
1578
|
return success({ signedPsbt });
|
|
1361
1579
|
});
|
|
1362
1580
|
}
|
|
@@ -1703,7 +1921,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
1703
1921
|
args.operationName
|
|
1704
1922
|
);
|
|
1705
1923
|
_KeystoneAdapter._throwIfAborted(signal);
|
|
1706
|
-
const signature = args.parseResponse(responseUr);
|
|
1924
|
+
const signature = parseScannedAnswer(() => args.parseResponse(responseUr));
|
|
1707
1925
|
_KeystoneAdapter._assertRequestIdMatches(requestId, signature.requestId);
|
|
1708
1926
|
return success(args.toPayload(signature));
|
|
1709
1927
|
});
|
|
@@ -1753,7 +1971,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
1753
1971
|
}
|
|
1754
1972
|
if (this._forcedTransport !== "qr" && !routedToQr && record?.usbSessionId) {
|
|
1755
1973
|
return {
|
|
1756
|
-
access: { channel: "usb", usbSessionId: record.usbSessionId },
|
|
1974
|
+
access: { channel: "usb", usbSessionId: record.usbSessionId, qrFallback: {} },
|
|
1757
1975
|
masterFingerprint: record.masterFingerprint
|
|
1758
1976
|
};
|
|
1759
1977
|
}
|
|
@@ -1764,26 +1982,67 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
1764
1982
|
});
|
|
1765
1983
|
}
|
|
1766
1984
|
const schemas = Array.from(requestedByKey.values());
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1985
|
+
if (schemas.length > this._qrKeyRequestLimit) {
|
|
1986
|
+
throw createHwkError2({
|
|
1987
|
+
code: HardwareErrorCode2.QrRequestTooLarge,
|
|
1988
|
+
message: `Keystone QR requests take at most ${this._qrKeyRequestLimit} account paths here; this one needs ${schemas.length}`,
|
|
1989
|
+
params: { limit: this._qrKeyRequestLimit, requested: schemas.length }
|
|
1990
|
+
});
|
|
1991
|
+
}
|
|
1992
|
+
const request = {
|
|
1993
|
+
...this.urEngine.buildKeyDerivationRequest({
|
|
1994
|
+
schemas: schemas.map((schema) => keySchema(schema.hwkChain, schema.path)),
|
|
1995
|
+
origin: this._origin
|
|
1996
|
+
}),
|
|
1997
|
+
animated: false,
|
|
1998
|
+
allowAccountExport: true
|
|
1999
|
+
};
|
|
1771
2000
|
const responseUr = await this._requestQrAndAwaitResponse(
|
|
1772
2001
|
record ? toDeviceInfo(record) : placeholderDeviceInfo(),
|
|
1773
|
-
|
|
2002
|
+
request,
|
|
1774
2003
|
signal
|
|
1775
2004
|
);
|
|
1776
2005
|
_KeystoneAdapter._throwIfAborted(signal);
|
|
1777
|
-
const parsed = this.urEngine.parseAccountResponse(responseUr);
|
|
2006
|
+
const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
|
|
1778
2007
|
this._assertParsedIdentity(parsed, target);
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
2008
|
+
const firmware = getKeystoneFirmwareProfile(parsed.deviceVersion);
|
|
2009
|
+
const usableSchemas = schemas.filter(
|
|
2010
|
+
(schema) => !firmware || firmware.supportedChains.includes(schema.hwkChain)
|
|
2011
|
+
);
|
|
2012
|
+
const isColdStart = !target.expectedMasterFingerprint;
|
|
2013
|
+
if (firmware && isColdStart && !responseUr.accountExport && !usableSchemas.length) {
|
|
2014
|
+
throw createHwkError2({
|
|
2015
|
+
code: HardwareErrorCode2.ChainNotSupported,
|
|
2016
|
+
message: `Keystone ${firmware.variant} firmware cannot use any requested chain`,
|
|
2017
|
+
params: { firmwareVariant: firmware.variant }
|
|
2018
|
+
});
|
|
2019
|
+
}
|
|
2020
|
+
for (const schema of usableSchemas) {
|
|
2021
|
+
const exported = responseUr.accountExport ? exportedAccountAt(parsed, schema.path) : requireExportedPath(parsed, schema.path);
|
|
2022
|
+
if (exported) {
|
|
2023
|
+
scanned.set(accountKey(schema.hwkChain, schema.path), {
|
|
2024
|
+
...exported,
|
|
2025
|
+
hwkChain: schema.hwkChain
|
|
2026
|
+
});
|
|
2027
|
+
}
|
|
2028
|
+
}
|
|
2029
|
+
if (responseUr.accountExport && !scanned.size) {
|
|
2030
|
+
throw createHwkError2({
|
|
2031
|
+
code: HardwareErrorCode2.DevicePathForbidden,
|
|
2032
|
+
message: "Account export contains none of the requested supported account paths",
|
|
2033
|
+
params: { reason: "account-not-exported" }
|
|
1783
2034
|
});
|
|
1784
2035
|
}
|
|
1785
2036
|
record = this._upsertDeviceRecord(parsed);
|
|
1786
|
-
return {
|
|
2037
|
+
return {
|
|
2038
|
+
access: {
|
|
2039
|
+
channel: "qr",
|
|
2040
|
+
scanned,
|
|
2041
|
+
firmwareVersion: parsed.deviceVersion,
|
|
2042
|
+
...responseUr.accountExport ? { accountExport: true } : {}
|
|
2043
|
+
},
|
|
2044
|
+
masterFingerprint: record.masterFingerprint
|
|
2045
|
+
};
|
|
1787
2046
|
});
|
|
1788
2047
|
}
|
|
1789
2048
|
/**
|
|
@@ -1857,11 +2116,17 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
1857
2116
|
record = createDeviceRecord(masterFingerprint);
|
|
1858
2117
|
this._devices.set(masterFingerprint, record);
|
|
1859
2118
|
}
|
|
1860
|
-
record.model = parsed.device
|
|
1861
|
-
record.
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
2119
|
+
record.model = parsed.device;
|
|
2120
|
+
record.hardwareDeviceId = parsed.deviceId;
|
|
2121
|
+
if (options?.usbSessionId) {
|
|
2122
|
+
record.usbSessionId = options.usbSessionId;
|
|
2123
|
+
record.usbFirmwareVersion = options.usbFirmwareVersion;
|
|
2124
|
+
record.hadUsbSession = true;
|
|
2125
|
+
}
|
|
2126
|
+
if (!options?.viaUsb) {
|
|
2127
|
+
record.deviceVersion = parsed.deviceVersion;
|
|
2128
|
+
record.qrSynced = true;
|
|
2129
|
+
}
|
|
1865
2130
|
const info = toDeviceInfo(record);
|
|
1866
2131
|
const eventType = isNew ? DEVICE.CONNECT : DEVICE.CHANGED;
|
|
1867
2132
|
this.emitter.emit(eventType, { type: eventType, payload: info });
|
|
@@ -1945,16 +2210,18 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
1945
2210
|
}
|
|
1946
2211
|
_KeystoneAdapter._throwIfAborted(signal);
|
|
1947
2212
|
const record = this._upsertDeviceRecord(
|
|
1948
|
-
{
|
|
2213
|
+
{
|
|
2214
|
+
masterFingerprint,
|
|
2215
|
+
accounts: [],
|
|
2216
|
+
device: session.deviceInfo.modelName ?? session.deviceInfo.model
|
|
2217
|
+
},
|
|
1949
2218
|
{
|
|
1950
2219
|
viaUsb: true,
|
|
1951
|
-
usbSessionId: session.sessionId
|
|
2220
|
+
usbSessionId: session.sessionId,
|
|
2221
|
+
usbFirmwareVersion: session.deviceInfo.firmwareVersion
|
|
1952
2222
|
}
|
|
1953
2223
|
);
|
|
1954
2224
|
_KeystoneAdapter._throwIfAborted(signal);
|
|
1955
|
-
record.hadUsbSession = true;
|
|
1956
|
-
record.model = session.deviceInfo.modelName ?? session.deviceInfo.model ?? record.model;
|
|
1957
|
-
record.deviceVersion = session.deviceInfo.firmwareVersion ?? record.deviceVersion;
|
|
1958
2225
|
return success(toDeviceInfo(record));
|
|
1959
2226
|
} catch (err) {
|
|
1960
2227
|
if (sessionId) {
|
|
@@ -1968,7 +2235,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
1968
2235
|
}
|
|
1969
2236
|
/**
|
|
1970
2237
|
* Probes already-authorized USB devices without a permission picker, then attaches and verifies
|
|
1971
|
-
* the requested wallet if present.
|
|
2238
|
+
* the requested wallet if present. Undefined means use QR: no device, or the user chose QR.
|
|
1972
2239
|
*/
|
|
1973
2240
|
async _tryUsbAttach(signal, expectedMasterFingerprint, options) {
|
|
1974
2241
|
_KeystoneAdapter._throwIfAborted(signal);
|
|
@@ -2012,19 +2279,33 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
2012
2279
|
signal
|
|
2013
2280
|
);
|
|
2014
2281
|
_KeystoneAdapter._throwIfAborted(signal);
|
|
2015
|
-
if (
|
|
2282
|
+
if (attached.success) return this._devices.get(expectedMasterFingerprint);
|
|
2283
|
+
const { code } = attached.payload;
|
|
2284
|
+
if (code === HardwareErrorCode2.DeviceBusyInternal || code === HardwareErrorCode2.DeviceOneDeviceOnly) {
|
|
2016
2285
|
throw createHwkError2({
|
|
2017
2286
|
...attached.payload,
|
|
2018
2287
|
message: attached.payload.error
|
|
2019
2288
|
});
|
|
2020
2289
|
}
|
|
2021
|
-
|
|
2290
|
+
if (code === HardwareErrorCode2.DeviceNotFound || this._forcedTransport) return void 0;
|
|
2291
|
+
const answer = await this._askQrFallback(
|
|
2292
|
+
signal,
|
|
2293
|
+
USB_ATTACH_FAILURE_REASONS[code] ?? "usb-unavailable"
|
|
2294
|
+
);
|
|
2295
|
+
if (answer === "retry") return this._tryUsbAttach(signal, expectedMasterFingerprint);
|
|
2296
|
+
if (answer === "cancel") {
|
|
2297
|
+
throw createHwkError2({
|
|
2298
|
+
code: HardwareErrorCode2.UserAborted,
|
|
2299
|
+
message: "User declined to continue by QR while the connected Keystone was unusable"
|
|
2300
|
+
});
|
|
2301
|
+
}
|
|
2302
|
+
return void 0;
|
|
2022
2303
|
}
|
|
2023
2304
|
/**
|
|
2024
2305
|
* Decides QR vs USB for one UR round trip. A pinned 'usb' with no live session reattaches once
|
|
2025
2306
|
* and fails closed if that fails; otherwise a failed USB reattach leaves the call on QR.
|
|
2026
2307
|
*/
|
|
2027
|
-
async _resolveUr(record, requestUr, animated, operationId, signal, operationName) {
|
|
2308
|
+
async _resolveUr(record, requestUr, animated, operationId, signal, operationName, qrFallback) {
|
|
2028
2309
|
const releaseOperationRetention = isHardwareOperationId2(operationId) ? this._operations.retain(operationId) : void 0;
|
|
2029
2310
|
try {
|
|
2030
2311
|
return await this._resolveUrWithRoute(
|
|
@@ -2033,13 +2314,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
2033
2314
|
animated,
|
|
2034
2315
|
operationId,
|
|
2035
2316
|
signal,
|
|
2036
|
-
operationName
|
|
2317
|
+
operationName,
|
|
2318
|
+
qrFallback
|
|
2037
2319
|
);
|
|
2038
2320
|
} finally {
|
|
2039
2321
|
releaseOperationRetention?.();
|
|
2040
2322
|
}
|
|
2041
2323
|
}
|
|
2042
|
-
async _resolveUrWithRoute(callerRecord, requestUr, animated, operationId, signal, operationName) {
|
|
2324
|
+
async _resolveUrWithRoute(callerRecord, requestUr, animated, operationId, signal, operationName, qrFallback) {
|
|
2043
2325
|
let record = callerRecord;
|
|
2044
2326
|
let interactionRoute;
|
|
2045
2327
|
if (isHardwareOperationId2(operationId)) {
|
|
@@ -2078,13 +2360,31 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
2078
2360
|
requestUr,
|
|
2079
2361
|
signal
|
|
2080
2362
|
);
|
|
2081
|
-
if (result.success)
|
|
2363
|
+
if (result.success) {
|
|
2364
|
+
const ur = result.payload;
|
|
2365
|
+
return { urType: ur.urType, urData: ur.urData, channel: "usb" };
|
|
2366
|
+
}
|
|
2082
2367
|
const usbError = rehydrateConnectorError(result.error);
|
|
2083
2368
|
const { origin: usbErrorOrigin, code: usbErrorCode } = usbError;
|
|
2084
2369
|
if (usbErrorCode === HardwareErrorCode2.PayloadTooLarge && usbErrorOrigin !== "device") {
|
|
2085
2370
|
if (!interactionRoute && !this._forcedTransport) {
|
|
2371
|
+
if (!await this._confirmQrFallback(signal, qrFallback)) {
|
|
2372
|
+
throw createHwkError2({
|
|
2373
|
+
code: HardwareErrorCode2.UserAborted,
|
|
2374
|
+
message: "User declined to show the request too large for USB as a QR code"
|
|
2375
|
+
});
|
|
2376
|
+
}
|
|
2086
2377
|
const displayDevice2 = toDeviceInfo(record);
|
|
2087
|
-
|
|
2378
|
+
const responseUr = await this._requestQrAndAwaitResponse(
|
|
2379
|
+
displayDevice2,
|
|
2380
|
+
{
|
|
2381
|
+
...requestUr,
|
|
2382
|
+
animated,
|
|
2383
|
+
...!operationName ? { allowAccountExport: true } : {}
|
|
2384
|
+
},
|
|
2385
|
+
signal
|
|
2386
|
+
);
|
|
2387
|
+
return { ...responseUr, channel: "qr" };
|
|
2088
2388
|
}
|
|
2089
2389
|
throw usbError;
|
|
2090
2390
|
}
|
|
@@ -2095,6 +2395,7 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
2095
2395
|
this._usbConnector?.disconnect(lostSessionId).catch(() => void 0);
|
|
2096
2396
|
}
|
|
2097
2397
|
record.usbSessionId = void 0;
|
|
2398
|
+
record.usbFirmwareVersion = void 0;
|
|
2098
2399
|
this.emitter.emit(DEVICE.CHANGED, { type: DEVICE.CHANGED, payload: toDeviceInfo(record) });
|
|
2099
2400
|
if (interactionRoute) {
|
|
2100
2401
|
throw this._endDisconnectedOperation(
|
|
@@ -2126,11 +2427,12 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
2126
2427
|
}
|
|
2127
2428
|
const displayDevice = record ? toDeviceInfo(record) : placeholderDeviceInfo();
|
|
2128
2429
|
try {
|
|
2129
|
-
|
|
2430
|
+
const responseUr = await this._requestQrAndAwaitResponse(
|
|
2130
2431
|
displayDevice,
|
|
2131
|
-
{ ...requestUr, animated },
|
|
2432
|
+
{ ...requestUr, animated, ...!operationName ? { allowAccountExport: true } : {} },
|
|
2132
2433
|
signal
|
|
2133
2434
|
);
|
|
2435
|
+
return { ...responseUr, channel: "qr" };
|
|
2134
2436
|
} catch (error) {
|
|
2135
2437
|
const { code, _tag: tag } = error;
|
|
2136
2438
|
if (operationName && (code === HardwareErrorCode2.OperationTimeout || tag === UI_REQUEST_TIMEOUT_TAG)) {
|
|
@@ -2164,6 +2466,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
2164
2466
|
const target = this._resolveTarget(connectId, deviceId);
|
|
2165
2467
|
if (bundle?.channel === "qr") {
|
|
2166
2468
|
const scanned = bundle.scanned.get(accountKey(hwkChain, syncPath));
|
|
2469
|
+
if (target.record && !scanned && bundle.accountExport) {
|
|
2470
|
+
throw createHwkError2({
|
|
2471
|
+
code: HardwareErrorCode2.DevicePathForbidden,
|
|
2472
|
+
message: "Scanned account export does not include this account path",
|
|
2473
|
+
params: { reason: "account-not-exported" }
|
|
2474
|
+
});
|
|
2475
|
+
}
|
|
2476
|
+
this._assertQrChainSupported(bundle.firmwareVersion, hwkChain);
|
|
2167
2477
|
if (!target.record || !scanned) {
|
|
2168
2478
|
throw createHwkError2({
|
|
2169
2479
|
code: HardwareErrorCode2.DeviceMismatch,
|
|
@@ -2178,19 +2488,27 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
2178
2488
|
message: "Keystone USB connection was lost during the bundle"
|
|
2179
2489
|
});
|
|
2180
2490
|
}
|
|
2181
|
-
const operationConnectionType = isHardwareOperationId2(connectId) ? this._operations.resolve(connectId).connectionType : void 0;
|
|
2182
2491
|
let existingRecord = target.record;
|
|
2183
2492
|
if (!existingRecord) {
|
|
2184
2493
|
existingRecord = await this._tryUsbAttach(signal, target.expectedMasterFingerprint);
|
|
2185
2494
|
_KeystoneAdapter._throwIfAborted(signal);
|
|
2186
2495
|
}
|
|
2187
|
-
const useSinglePathUsbExport = operationConnectionType ? operationConnectionType === "usb" : this._forcedTransport === "usb" || this._forcedTransport !== "qr" && Boolean(existingRecord?.usbSessionId);
|
|
2188
2496
|
const schemas = [keySchema(hwkChain, syncPath)];
|
|
2189
2497
|
const requestUr = this.urEngine.buildKeyDerivationRequest({ schemas, origin: this._origin });
|
|
2190
|
-
const responseUr = await this._resolveUr(
|
|
2498
|
+
const responseUr = await this._resolveUr(
|
|
2499
|
+
existingRecord,
|
|
2500
|
+
requestUr,
|
|
2501
|
+
false,
|
|
2502
|
+
connectId,
|
|
2503
|
+
signal,
|
|
2504
|
+
void 0,
|
|
2505
|
+
bundle?.channel === "usb" ? bundle.qrFallback : void 0
|
|
2506
|
+
);
|
|
2191
2507
|
_KeystoneAdapter._throwIfAborted(signal);
|
|
2192
|
-
const parsed = this.urEngine.parseAccountResponse(responseUr);
|
|
2193
|
-
|
|
2508
|
+
const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
|
|
2509
|
+
this._assertParsedIdentity(parsed, target);
|
|
2510
|
+
const account = requireExportedPath(parsed, syncPath, responseUr.accountExport);
|
|
2511
|
+
const useSinglePathUsbExport = !responseUr.accountExport && responseUr.channel === "usb";
|
|
2194
2512
|
let record;
|
|
2195
2513
|
if (useSinglePathUsbExport && existingRecord) {
|
|
2196
2514
|
if (parsed.masterFingerprint !== existingRecord.masterFingerprint) {
|
|
@@ -2201,23 +2519,18 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
2201
2519
|
}
|
|
2202
2520
|
record = existingRecord;
|
|
2203
2521
|
} else {
|
|
2204
|
-
this.
|
|
2205
|
-
record = this._upsertDeviceRecord(parsed
|
|
2206
|
-
viaUsb: operationConnectionType !== "qr" && Boolean(existingRecord?.usbSessionId)
|
|
2207
|
-
});
|
|
2522
|
+
this._assertQrChainSupported(parsed.deviceVersion, hwkChain);
|
|
2523
|
+
record = this._upsertDeviceRecord(parsed);
|
|
2208
2524
|
}
|
|
2209
2525
|
return { record, account: { ...account, hwkChain } };
|
|
2210
2526
|
}
|
|
2211
2527
|
/**
|
|
2212
|
-
* Resolves
|
|
2213
|
-
*
|
|
2528
|
+
* Resolves wallet identity without a per-path account. A caller-supplied fingerprint needs no
|
|
2529
|
+
* device round trip; otherwise request the account path from the device.
|
|
2214
2530
|
*/
|
|
2215
2531
|
async _ensureWalletKnown(connectId, deviceId, chain, signal) {
|
|
2216
2532
|
const target = this._resolveTarget(connectId, deviceId);
|
|
2217
2533
|
if (target.record) return { record: target.record };
|
|
2218
|
-
const attached = await this._tryUsbAttach(signal, target.expectedMasterFingerprint);
|
|
2219
|
-
_KeystoneAdapter._throwIfAborted(signal);
|
|
2220
|
-
if (attached) return { record: attached };
|
|
2221
2534
|
if (target.expectedMasterFingerprint) {
|
|
2222
2535
|
return { record: createDeviceRecord(target.expectedMasterFingerprint) };
|
|
2223
2536
|
}
|
|
@@ -2228,19 +2541,25 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
2228
2541
|
});
|
|
2229
2542
|
const responseUr = await this._resolveUr(void 0, requestUr, false, connectId, signal);
|
|
2230
2543
|
_KeystoneAdapter._throwIfAborted(signal);
|
|
2231
|
-
const parsed = this.urEngine.parseAccountResponse(responseUr);
|
|
2232
|
-
requireExportedPath(parsed, normalizePath(accountPath));
|
|
2233
|
-
|
|
2544
|
+
const parsed = responseUr.accountExport ? this.urEngine.parseAccountExport(responseUr) : this.urEngine.parseAccountResponse(responseUr);
|
|
2545
|
+
if (!responseUr.accountExport) requireExportedPath(parsed, normalizePath(accountPath));
|
|
2546
|
+
this._assertQrChainSupported(parsed.deviceVersion, chain);
|
|
2547
|
+
const record = this._upsertDeviceRecord(parsed);
|
|
2548
|
+
return { record };
|
|
2549
|
+
}
|
|
2550
|
+
_assertQrChainSupported(firmwareVersion, chain) {
|
|
2551
|
+
const firmware = getKeystoneFirmwareProfile(firmwareVersion);
|
|
2552
|
+
if (firmware && !firmware.supportedChains.includes(chain)) {
|
|
2553
|
+
throw createHwkError2({
|
|
2554
|
+
code: HardwareErrorCode2.ChainNotSupported,
|
|
2555
|
+
message: `Keystone ${firmware.variant} firmware cannot use ${chain} through this adapter`,
|
|
2556
|
+
params: { firmwareVariant: firmware.variant, chain }
|
|
2557
|
+
});
|
|
2558
|
+
}
|
|
2234
2559
|
}
|
|
2235
|
-
/**
|
|
2236
|
-
* The operation owning the running job, so a mid-call UI request can name it. Unpinned jobs map
|
|
2237
|
-
* through the operation route; a cold start returns undefined.
|
|
2238
|
-
*/
|
|
2560
|
+
/** Only an operation id supplied to the running call owns its UI prompts. */
|
|
2239
2561
|
_activeOperationId() {
|
|
2240
|
-
|
|
2241
|
-
if (!activeJobId) return void 0;
|
|
2242
|
-
if (isHardwareOperationId2(activeJobId)) return activeJobId;
|
|
2243
|
-
return this._operationRouteForIdentifier(activeJobId)?.operationId;
|
|
2562
|
+
return this._operations.findOperationIdByJobKey(this._jobQueue.getActiveJob()?.deviceId);
|
|
2244
2563
|
}
|
|
2245
2564
|
/** Routes are keyed by connectId; a job key may be the bare master fingerprint. */
|
|
2246
2565
|
_operationRouteForIdentifier(identifier) {
|
|
@@ -2273,6 +2592,43 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
2273
2592
|
signal.removeEventListener("abort", onAbort);
|
|
2274
2593
|
}
|
|
2275
2594
|
}
|
|
2595
|
+
/**
|
|
2596
|
+
* Asks whether a request too large for USB may be shown as a QR. A timeout or an unanswered
|
|
2597
|
+
* prompt reads as no; a cancelled call keeps its own error.
|
|
2598
|
+
*/
|
|
2599
|
+
async _confirmQrFallback(signal, choice) {
|
|
2600
|
+
if (choice?.confirmed !== void 0) return choice.confirmed;
|
|
2601
|
+
const confirmed = await this._askQrFallback(signal, "payload-too-large") === "qr";
|
|
2602
|
+
if (choice) choice.confirmed = confirmed;
|
|
2603
|
+
return confirmed;
|
|
2604
|
+
}
|
|
2605
|
+
/** A timeout or an unanswered prompt reads as cancel; a cancelled call keeps its own error. */
|
|
2606
|
+
async _askQrFallback(signal, reason) {
|
|
2607
|
+
const requestType = UI_REQUEST.REQUEST_QR_FALLBACK_CONFIRM;
|
|
2608
|
+
const requestId = this._uiRegistry.createRequestId();
|
|
2609
|
+
const operationId = this._activeOperationId();
|
|
2610
|
+
const release = operationId ? this._operations.retain(operationId) : void 0;
|
|
2611
|
+
try {
|
|
2612
|
+
const waitPromise = this._uiRegistry.wait(
|
|
2613
|
+
requestType,
|
|
2614
|
+
{ requestId, operationId }
|
|
2615
|
+
);
|
|
2616
|
+
this.emitter.emit(requestType, {
|
|
2617
|
+
type: requestType,
|
|
2618
|
+
payload: { vendor: "keystone", requestId, operationId, reason }
|
|
2619
|
+
});
|
|
2620
|
+
let answer;
|
|
2621
|
+
try {
|
|
2622
|
+
answer = await this._awaitQrResponse(requestType, waitPromise, signal);
|
|
2623
|
+
} catch (error) {
|
|
2624
|
+
if (signal.aborted) throw error;
|
|
2625
|
+
}
|
|
2626
|
+
if (answer?.retry && reason !== "payload-too-large") return "retry";
|
|
2627
|
+
return answer?.confirmed ? "qr" : "cancel";
|
|
2628
|
+
} finally {
|
|
2629
|
+
release?.();
|
|
2630
|
+
}
|
|
2631
|
+
}
|
|
2276
2632
|
/** Shows `data` for the device to scan, or with no `data` asks the host to scan the device. */
|
|
2277
2633
|
async _requestQrAndAwaitResponse(device, data, signal) {
|
|
2278
2634
|
const requestType = data ? UI_REQUEST.REQUEST_QR_DISPLAY : UI_REQUEST.REQUEST_QR_SCAN;
|
|
@@ -2295,7 +2651,14 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
2295
2651
|
});
|
|
2296
2652
|
}
|
|
2297
2653
|
const response = await this._awaitQrResponse(requestType, waitPromise, signal);
|
|
2298
|
-
|
|
2654
|
+
if (response.accountExport && data && !data.allowAccountExport) {
|
|
2655
|
+
throw unexpectedQrCodeError("This request cannot be answered with an account export");
|
|
2656
|
+
}
|
|
2657
|
+
return {
|
|
2658
|
+
urType: response.urType,
|
|
2659
|
+
urData: response.urData,
|
|
2660
|
+
...!data || response.accountExport ? { accountExport: true } : {}
|
|
2661
|
+
};
|
|
2299
2662
|
} finally {
|
|
2300
2663
|
release?.();
|
|
2301
2664
|
}
|
|
@@ -2401,10 +2764,10 @@ var KeystoneAdapter = class _KeystoneAdapter {
|
|
|
2401
2764
|
/** A response without the request's id is as unrelated as one with another id. */
|
|
2402
2765
|
static _assertRequestIdMatches(expected, actual) {
|
|
2403
2766
|
if (!actual || actual.toLowerCase() !== expected.toLowerCase()) {
|
|
2404
|
-
throw
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
2767
|
+
throw unexpectedQrCodeError(
|
|
2768
|
+
actual ? "Keystone response requestId does not match the pending request \u2014 discarding a stale or unrelated scan" : "Keystone response carries no requestId \u2014 discarding a stale or unrelated scan",
|
|
2769
|
+
HardwareErrorCode2.DeviceMismatch
|
|
2770
|
+
);
|
|
2408
2771
|
}
|
|
2409
2772
|
}
|
|
2410
2773
|
_unsupported(method, reason) {
|