@qntx/wallet 0.11.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chains-Dkmqwe-8.d.mts → chains-B-FmFmuV.d.mts} +44 -4
- package/dist/chains.d.mts +2 -2
- package/dist/chains.mjs +32 -7
- package/dist/chains.mjs.map +1 -1
- package/dist/{channel-D6u0HBfy.mjs → channel-BLwce5hh.mjs} +3 -3
- package/dist/{channel-D6u0HBfy.mjs.map → channel-BLwce5hh.mjs.map} +1 -1
- package/dist/{core-DDfzuSIa.mjs → core-DaRwkTaV.mjs} +43 -2
- package/dist/core-DaRwkTaV.mjs.map +1 -0
- package/dist/host.d.mts +2 -2
- package/dist/host.mjs +53 -2
- package/dist/host.mjs.map +1 -1
- package/dist/{index-HWtJPkvq.d.mts → index-CEhrd0Pl.d.mts} +9 -3
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +2 -2
- package/dist/nostr.d.mts +1 -1
- package/dist/nostr.mjs +1 -1
- package/dist/{protocol-DqBfdhN5.mjs → protocol-fXHXJguP.mjs} +33 -10
- package/dist/protocol-fXHXJguP.mjs.map +1 -0
- package/dist/protocol.d.mts +3 -3
- package/dist/protocol.mjs +2 -2
- package/dist/spark.d.mts +2 -2
- package/dist/{types-Dub5eUl3.d.mts → types-cAQAJBLi.d.mts} +23 -2
- package/dist/types.d.mts +2 -2
- package/dist/types.mjs.map +1 -1
- package/package.json +5 -5
- package/dist/core-DDfzuSIa.mjs.map +0 -1
- package/dist/protocol-DqBfdhN5.mjs.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { C as WalletErrorCode, c as FactorInfo, w as WalletInfo } from "./types-cAQAJBLi.mjs";
|
|
2
2
|
/**
|
|
3
3
|
* Strict validator combinators for the secret-area protocol. Both sides share them: the kernel
|
|
4
4
|
* validates every request, the host validates every response. Anything that does not match is a
|
|
@@ -208,6 +208,29 @@ declare const CORE_METHODS: {
|
|
|
208
208
|
readonly "dataKeys.get": MethodSpec<{
|
|
209
209
|
readonly purpose: string;
|
|
210
210
|
}, Uint8Array>;
|
|
211
|
+
readonly "keys.import": MethodSpec<{
|
|
212
|
+
readonly family: "evm" | "solana" | "bitcoin";
|
|
213
|
+
readonly secret: Uint8Array;
|
|
214
|
+
}, {
|
|
215
|
+
readonly keyId: string;
|
|
216
|
+
readonly family: "evm" | "solana" | "bitcoin";
|
|
217
|
+
readonly address: string;
|
|
218
|
+
readonly createdAt: number;
|
|
219
|
+
}>;
|
|
220
|
+
readonly "keys.list": MethodSpec<NullValue, ReadonlyArray<{
|
|
221
|
+
readonly keyId: string;
|
|
222
|
+
readonly family: "evm" | "solana" | "bitcoin";
|
|
223
|
+
readonly address: string;
|
|
224
|
+
readonly createdAt: number;
|
|
225
|
+
}>>;
|
|
226
|
+
readonly "keys.remove": MethodSpec<{
|
|
227
|
+
readonly verify: Factor;
|
|
228
|
+
readonly keyId: string;
|
|
229
|
+
}, NullValue>;
|
|
230
|
+
readonly "keys.export": MethodSpec<{
|
|
231
|
+
readonly verify: Factor;
|
|
232
|
+
readonly keyId: string;
|
|
233
|
+
}, Uint8Array>;
|
|
211
234
|
};
|
|
212
235
|
type ChainTemplate = "evm.bip44" | "solana.bip44-change" | "btc.bip44" | "btc.bip49" | "btc.bip84" | "btc.bip86";
|
|
213
236
|
type ChainAccountsParams = {
|
|
@@ -267,6 +290,15 @@ type EvmTransactionWire = (EvmTransactionBase & {
|
|
|
267
290
|
readonly maxFeePerGas: string;
|
|
268
291
|
readonly maxPriorityFeePerGas: string;
|
|
269
292
|
readonly accessList: ReadonlyArray<EvmAccessListEntryWire>;
|
|
293
|
+
}) | (EvmTransactionBase & {
|
|
294
|
+
readonly type: "eip7702";
|
|
295
|
+
readonly to: string;
|
|
296
|
+
readonly maxFeePerGas: string;
|
|
297
|
+
readonly maxPriorityFeePerGas: string;
|
|
298
|
+
readonly accessList: ReadonlyArray<EvmAccessListEntryWire>;
|
|
299
|
+
readonly authorization: {
|
|
300
|
+
readonly address: string;
|
|
301
|
+
};
|
|
270
302
|
});
|
|
271
303
|
/** `chain.sign`'s request — the wire mirror of @qntx/wallet-chains `SignRequest`. */
|
|
272
304
|
type ChainSignRequest = {
|
|
@@ -302,9 +334,17 @@ type ChainSignRequest = {
|
|
|
302
334
|
} | {
|
|
303
335
|
readonly kind: "bitcoin.psbt";
|
|
304
336
|
readonly network: string;
|
|
305
|
-
|
|
337
|
+
/** The wallet group whose keys sign; each signed input names its template. */
|
|
338
|
+
readonly account: {
|
|
339
|
+
readonly kind: "hd";
|
|
340
|
+
readonly walletId: string;
|
|
341
|
+
readonly groupIndex: number;
|
|
342
|
+
};
|
|
306
343
|
readonly psbt: Uint8Array;
|
|
307
|
-
readonly sign: ReadonlyArray<
|
|
344
|
+
readonly sign: ReadonlyArray<{
|
|
345
|
+
readonly index: number;
|
|
346
|
+
readonly template: "btc.bip44" | "btc.bip49" | "btc.bip84" | "btc.bip86";
|
|
347
|
+
}>;
|
|
308
348
|
} | {
|
|
309
349
|
readonly kind: "bitcoin.message";
|
|
310
350
|
readonly network: string;
|
|
@@ -340,4 +380,4 @@ declare const CHAINS_METHODS: {
|
|
|
340
380
|
readonly "chain.sign": MethodSpec<ChainSignParams, ChainSignResult>;
|
|
341
381
|
};
|
|
342
382
|
export { validate as A, literal as C, record as D, opt as E, str as O, int as S, obj as T, ValidationError as _, ChainSignResult as a, bool as b, BackupUnlockFactor as c, CreatedResult as d, Factor as f, NullValue as g, walletErrorCode as h, ChainSignRequest as i, union as k, CORE_METHODS as l, RestoreWithPasskeyParams as m, ChainAccount as n, ChainTemplate as o, MethodSpec as p, ChainAccountsParams as r, BackupFactor as s, CHAINS_METHODS as t, CreateWithPasskeyParams as u, Validator as v, nullValue as w, bytes as x, arr as y };
|
|
343
|
-
//# sourceMappingURL=chains-
|
|
383
|
+
//# sourceMappingURL=chains-B-FmFmuV.d.mts.map
|
package/dist/chains.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { a as ChainSignResult, i as ChainSignRequest, n as ChainAccount, o as ChainTemplate, r as ChainAccountsParams } from "./chains-
|
|
1
|
+
import { v as UnlockFactor, x as Wallet } from "./types-cAQAJBLi.mjs";
|
|
2
|
+
import { a as ChainSignResult, i as ChainSignRequest, n as ChainAccount, o as ChainTemplate, r as ChainAccountsParams } from "./chains-B-FmFmuV.mjs";
|
|
3
3
|
export type ChainsApi = {
|
|
4
4
|
readonly account: (params: ChainAccountsParams) => Promise<ChainAccount>;
|
|
5
5
|
readonly sign: (params: {
|
package/dist/chains.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as integrity } from "./channel-
|
|
1
|
+
import { n as integrity } from "./channel-BLwce5hh.mjs";
|
|
2
2
|
import { t as internalsOf } from "./internal-CAKfHjIg.mjs";
|
|
3
3
|
import { bitcoinAddressFromXpub, verifyBitcoinMessage, verifyBitcoinPsbtSignatures } from "@qntx/wallet-chains/bitcoin";
|
|
4
4
|
import { recoverEvmSigner } from "@qntx/wallet-chains/evm";
|
|
@@ -10,14 +10,33 @@ import { verifySolanaSignature } from "@qntx/wallet-chains/solana";
|
|
|
10
10
|
* signature against the account address — a kernel that answers with someone else's signature fails
|
|
11
11
|
* closed with `integrity`.
|
|
12
12
|
*/
|
|
13
|
+
/**
|
|
14
|
+
* The PSBT check: each sign entry names its template, so the account is fetched once per distinct
|
|
15
|
+
* template and each group's signatures verify against that template's xpub.
|
|
16
|
+
*/
|
|
17
|
+
const checkPsbt = async (internals, request, result) => {
|
|
18
|
+
if (result.kind !== "bitcoin.psbt") throw integrity("result kind does not match the request");
|
|
19
|
+
const byTemplate = /* @__PURE__ */ new Map();
|
|
20
|
+
for (const { index, template } of request.sign) {
|
|
21
|
+
const group = byTemplate.get(template) ?? [];
|
|
22
|
+
group.push(index);
|
|
23
|
+
byTemplate.set(template, group);
|
|
24
|
+
}
|
|
25
|
+
for (const [template, indices] of byTemplate) {
|
|
26
|
+
const account = await internals.call("wallet.accounts", {
|
|
27
|
+
walletId: request.account.walletId,
|
|
28
|
+
groupIndex: request.account.groupIndex,
|
|
29
|
+
template,
|
|
30
|
+
network: request.network
|
|
31
|
+
});
|
|
32
|
+
if (!("xpub" in account)) throw integrity("chain account has no xpub");
|
|
33
|
+
if (!verifyBitcoinPsbtSignatures(result.signedPsbt, indices, account.xpub, template, request.network)) throw integrity("psbt signatures do not verify for the account");
|
|
34
|
+
}
|
|
35
|
+
};
|
|
13
36
|
/** Whether the kernel's signature belongs to the account it was asked to sign for. */
|
|
14
37
|
const checkSigner = (request, result, account) => {
|
|
15
|
-
if (request.kind === "bitcoin.
|
|
38
|
+
if (request.kind === "bitcoin.message") {
|
|
16
39
|
if (!("xpub" in account)) throw integrity("chain account has no xpub");
|
|
17
|
-
if (request.kind === "bitcoin.psbt" && result.kind === "bitcoin.psbt") {
|
|
18
|
-
if (!verifyBitcoinPsbtSignatures(result.signedPsbt, request.sign, account.xpub, account.template, request.network)) throw integrity("psbt signatures do not verify for the account");
|
|
19
|
-
return;
|
|
20
|
-
}
|
|
21
40
|
if (request.kind === "bitcoin.message" && result.kind === "bitcoin.message") {
|
|
22
41
|
if (bitcoinAddressFromXpub(account.xpub, account.template, request.network, request.change, request.index) !== request.address || !verifyBitcoinMessage(request.address, request.message, result.signature, request.network)) throw integrity("message signature does not verify for the account");
|
|
23
42
|
return;
|
|
@@ -41,7 +60,8 @@ function createChainsApi(internals) {
|
|
|
41
60
|
request: params.request,
|
|
42
61
|
verify
|
|
43
62
|
});
|
|
44
|
-
if (params.request.
|
|
63
|
+
if (params.request.kind === "bitcoin.psbt") await checkPsbt(internals, params.request, result);
|
|
64
|
+
else if (params.request.account.kind === "hd") {
|
|
45
65
|
const account = await internals.call("wallet.accounts", {
|
|
46
66
|
walletId: params.request.account.walletId,
|
|
47
67
|
groupIndex: params.request.account.groupIndex,
|
|
@@ -49,6 +69,11 @@ function createChainsApi(internals) {
|
|
|
49
69
|
network: params.request.network
|
|
50
70
|
});
|
|
51
71
|
checkSigner(params.request, result, account);
|
|
72
|
+
} else {
|
|
73
|
+
const { keyId } = params.request.account;
|
|
74
|
+
const key = (await internals.call("keys.list", null)).find((k) => k.keyId === keyId);
|
|
75
|
+
if (key === void 0) throw integrity("chain.sign answered for a key not in the vault");
|
|
76
|
+
checkSigner(params.request, result, { address: key.address });
|
|
52
77
|
}
|
|
53
78
|
return result;
|
|
54
79
|
})
|
package/dist/chains.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chains.mjs","names":[],"sources":["../src/chains/index.ts"],"sourcesContent":["/**\n * The chains module of @qntx/wallet: `chains(wallet)` returns the wallet's chain API. `account`\n * calls the kernel's `wallet.accounts`; `sign` calls `chain.sign` and then verifies the returned\n * signature against the account address — a kernel that answers with someone else's signature fails\n * closed with `integrity`.\n */\nimport {\n bitcoinAddressFromXpub,\n verifyBitcoinMessage,\n verifyBitcoinPsbtSignatures,\n} from \"@qntx/wallet-chains/bitcoin\";\nimport { recoverEvmSigner } from \"@qntx/wallet-chains/evm\";\nimport { verifySolanaSignature } from \"@qntx/wallet-chains/solana\";\n\nimport { integrity } from \"../channel.ts\";\nimport { internalsOf } from \"../internal.ts\";\nimport type { WalletInternals } from \"../internal.ts\";\nimport type {\n ChainAccount,\n ChainAccountsParams,\n ChainSignRequest,\n ChainSignResult,\n} from \"../protocol/chains.ts\";\nimport type { UnlockFactor, Wallet } from \"../types.ts\";\n\nexport type {\n ChainAccount,\n ChainAccountsParams,\n ChainSignRequest,\n ChainSignResult,\n ChainTemplate,\n} from \"../protocol/chains.ts\";\n\nexport type ChainsApi = {\n readonly account: (params: ChainAccountsParams) => Promise<ChainAccount>;\n readonly sign: (params: {\n readonly request: ChainSignRequest;\n readonly verify: UnlockFactor;\n }) => Promise<ChainSignResult>;\n};\n\n
|
|
1
|
+
{"version":3,"file":"chains.mjs","names":[],"sources":["../src/chains/index.ts"],"sourcesContent":["/**\n * The chains module of @qntx/wallet: `chains(wallet)` returns the wallet's chain API. `account`\n * calls the kernel's `wallet.accounts`; `sign` calls `chain.sign` and then verifies the returned\n * signature against the account address — a kernel that answers with someone else's signature fails\n * closed with `integrity`.\n */\nimport {\n bitcoinAddressFromXpub,\n verifyBitcoinMessage,\n verifyBitcoinPsbtSignatures,\n} from \"@qntx/wallet-chains/bitcoin\";\nimport { recoverEvmSigner } from \"@qntx/wallet-chains/evm\";\nimport { verifySolanaSignature } from \"@qntx/wallet-chains/solana\";\n\nimport { integrity } from \"../channel.ts\";\nimport { internalsOf } from \"../internal.ts\";\nimport type { WalletInternals } from \"../internal.ts\";\nimport type {\n ChainAccount,\n ChainAccountsParams,\n ChainSignRequest,\n ChainSignResult,\n} from \"../protocol/chains.ts\";\nimport type { UnlockFactor, Wallet } from \"../types.ts\";\n\nexport type {\n ChainAccount,\n ChainAccountsParams,\n ChainSignRequest,\n ChainSignResult,\n ChainTemplate,\n} from \"../protocol/chains.ts\";\n\nexport type ChainsApi = {\n readonly account: (params: ChainAccountsParams) => Promise<ChainAccount>;\n readonly sign: (params: {\n readonly request: ChainSignRequest;\n readonly verify: UnlockFactor;\n }) => Promise<ChainSignResult>;\n};\n\n/**\n * The PSBT check: each sign entry names its template, so the account is fetched once per distinct\n * template and each group's signatures verify against that template's xpub.\n */\nconst checkPsbt = async (\n internals: WalletInternals,\n request: Extract<ChainSignRequest, { kind: \"bitcoin.psbt\" }>,\n result: ChainSignResult,\n): Promise<void> => {\n if (result.kind !== \"bitcoin.psbt\") {\n throw integrity(\"result kind does not match the request\");\n }\n const byTemplate = new Map<\"btc.bip44\" | \"btc.bip49\" | \"btc.bip84\" | \"btc.bip86\", number[]>();\n for (const { index, template } of request.sign) {\n const group = byTemplate.get(template) ?? [];\n group.push(index);\n byTemplate.set(template, group);\n }\n for (const [template, indices] of byTemplate) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- one wallet.accounts call per template.\n const account = await internals.call(\"wallet.accounts\", {\n walletId: request.account.walletId,\n groupIndex: request.account.groupIndex,\n template,\n network: request.network,\n });\n if (!(\"xpub\" in account)) {\n throw integrity(\"chain account has no xpub\");\n }\n if (\n !verifyBitcoinPsbtSignatures(\n result.signedPsbt,\n indices,\n account.xpub,\n template,\n request.network,\n )\n ) {\n throw integrity(\"psbt signatures do not verify for the account\");\n }\n }\n};\n\n/** Whether the kernel's signature belongs to the account it was asked to sign for. */\nconst checkSigner = (\n request: ChainSignRequest,\n result: ChainSignResult,\n account: ChainAccount | { readonly address: string },\n) => {\n if (request.kind === \"bitcoin.message\") {\n if (!(\"xpub\" in account)) {\n throw integrity(\"chain account has no xpub\");\n }\n if (request.kind === \"bitcoin.message\" && result.kind === \"bitcoin.message\") {\n const derived = bitcoinAddressFromXpub(\n account.xpub,\n account.template,\n request.network,\n request.change,\n request.index,\n );\n if (\n derived !== request.address ||\n !verifyBitcoinMessage(request.address, request.message, result.signature, request.network)\n ) {\n throw integrity(\"message signature does not verify for the account\");\n }\n return;\n }\n throw integrity(\"result kind does not match the request\");\n }\n if (!(\"address\" in account)) {\n throw integrity(\"chain account has no address\");\n }\n if (request.kind.startsWith(\"evm.\")) {\n if (\n result.kind !== \"evm.transaction\" &&\n result.kind !== \"evm.personal-message\" &&\n result.kind !== \"evm.typed-data\"\n ) {\n throw integrity(\"result kind does not match the request\");\n }\n const signer = recoverEvmSigner(request, result);\n if (signer.toLowerCase() !== account.address.toLowerCase()) {\n throw integrity(\"signer does not match the account\");\n }\n return;\n }\n if (\n (request.kind === \"solana.transaction\" || request.kind === \"solana.message\") &&\n (result.kind === \"solana.transaction\" || result.kind === \"solana.message\") &&\n !verifySolanaSignature(request.message, result.signature, account.address)\n ) {\n throw integrity(\"signature does not verify for the account\");\n }\n};\n\nfunction createChainsApi(internals: WalletInternals): ChainsApi {\n return {\n account: async (params) => internals.call(\"wallet.accounts\", params),\n sign: async (params) =>\n internals.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const verify = await internals.resolveFactor(params.verify, transfer);\n const result = await internals.call(\"chain.sign\", { request: params.request, verify });\n if (params.request.kind === \"bitcoin.psbt\") {\n await checkPsbt(internals, params.request, result);\n } else if (params.request.account.kind === \"hd\") {\n const account = await internals.call(\"wallet.accounts\", {\n walletId: params.request.account.walletId,\n groupIndex: params.request.account.groupIndex,\n template: params.request.account.template,\n network: params.request.network,\n });\n checkSigner(params.request, result, account);\n } else {\n const { keyId } = params.request.account;\n const keys = await internals.call(\"keys.list\", null);\n const key = keys.find((k) => k.keyId === keyId);\n if (key === undefined) {\n throw integrity(\"chain.sign answered for a key not in the vault\");\n }\n checkSigner(params.request, result, { address: key.address });\n }\n return result;\n }),\n };\n}\n\nconst apis = new WeakMap<Wallet, ChainsApi>();\n\nexport function chains(wallet: Wallet): ChainsApi {\n const internals = internalsOf(wallet);\n let api = apis.get(wallet);\n if (api === undefined) {\n api = createChainsApi(internals);\n apis.set(wallet, api);\n }\n return api;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA6CA,MAAM,YAAY,OAChB,WACA,SACA,WACkB;CAClB,IAAI,OAAO,SAAS,gBAClB,MAAM,UAAU,wCAAwC;CAE1D,MAAM,6BAAa,IAAI,IAAqE;CAC5F,KAAK,MAAM,EAAE,OAAO,cAAc,QAAQ,MAAM;EAC9C,MAAM,QAAQ,WAAW,IAAI,QAAQ,KAAK,CAAC;EAC3C,MAAM,KAAK,KAAK;EAChB,WAAW,IAAI,UAAU,KAAK;CAChC;CACA,KAAK,MAAM,CAAC,UAAU,YAAY,YAAY;EAE5C,MAAM,UAAU,MAAM,UAAU,KAAK,mBAAmB;GACtD,UAAU,QAAQ,QAAQ;GAC1B,YAAY,QAAQ,QAAQ;GAC5B;GACA,SAAS,QAAQ;EACnB,CAAC;EACD,IAAI,EAAE,UAAU,UACd,MAAM,UAAU,2BAA2B;EAE7C,IACE,CAAC,4BACC,OAAO,YACP,SACA,QAAQ,MACR,UACA,QAAQ,OACV,GAEA,MAAM,UAAU,+CAA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,OAAO,SAAS,MAAM;QAC5C,IAAI,OAAO,QAAQ,QAAQ,SAAS,MAAM;IAC/C,MAAM,UAAU,MAAM,UAAU,KAAK,mBAAmB;KACtD,UAAU,OAAO,QAAQ,QAAQ;KACjC,YAAY,OAAO,QAAQ,QAAQ;KACnC,UAAU,OAAO,QAAQ,QAAQ;KACjC,SAAS,OAAO,QAAQ;IAC1B,CAAC;IACD,YAAY,OAAO,SAAS,QAAQ,OAAO;GAC7C,OAAO;IACL,MAAM,EAAE,UAAU,OAAO,QAAQ;IAEjC,MAAM,OAAM,MADO,UAAU,KAAK,aAAa,IAAI,EAAA,CAClC,MAAM,MAAM,EAAE,UAAU,KAAK;IAC9C,IAAI,QAAQ,KAAA,GACV,MAAM,UAAU,gDAAgD;IAElE,YAAY,OAAO,SAAS,QAAQ,EAAE,SAAS,IAAI,QAAQ,CAAC;GAC9D;GACA,OAAO;EACT,CAAC;CACL;AACF;AAEA,MAAM,uBAAO,IAAI,QAA2B;AAE5C,SAAgB,OAAO,QAA2B;CAChD,MAAM,YAAY,YAAY,MAAM;CACpC,IAAI,MAAM,KAAK,IAAI,MAAM;CACzB,IAAI,QAAQ,KAAA,GAAW;EACrB,MAAM,gBAAgB,SAAS;EAC/B,KAAK,IAAI,QAAQ,GAAG;CACtB;CACA,OAAO;AACT"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { a as isProtocolValue, c as responseError, n as METHODS, o as kernelEvent, s as requestBytes } from "./protocol-
|
|
1
|
+
import { g as ValidationError } from "./core-DaRwkTaV.mjs";
|
|
2
|
+
import { a as isProtocolValue, c as responseError, n as METHODS, o as kernelEvent, s as requestBytes } from "./protocol-fXHXJguP.mjs";
|
|
3
3
|
import { WalletError } from "./types.mjs";
|
|
4
4
|
// src/channel.ts
|
|
5
5
|
/**
|
|
@@ -317,4 +317,4 @@ var Channel = class {
|
|
|
317
317
|
};
|
|
318
318
|
export { integrity as n, Channel as t };
|
|
319
319
|
|
|
320
|
-
//# sourceMappingURL=channel-
|
|
320
|
+
//# sourceMappingURL=channel-BLwce5hh.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"channel-D6u0HBfy.mjs","names":[],"sources":["../src/channel.ts"],"sourcesContent":["/**\n * The host side of the kernel channel (design/enclave.mdx \"协议与传输\"): port lifecycle, respawn,\n * request/response correlation and wire validation. Internal to the `./host` subpath — reserved for\n * host packages (wallet-worker, wallet-native); applications must not use it.\n */\nimport {\n isProtocolValue,\n kernelEvent,\n MAX_REQUEST_BYTES,\n METHODS,\n PROTOCOL_VERSION,\n requestBytes,\n responseError,\n ValidationError,\n} from \"./protocol/index.ts\";\nimport type { MethodName, ParamsOf, ProtocolValue, ResultOf } from \"./protocol/index.ts\";\nimport { WalletError } from \"./types.ts\";\nimport type { LockReason, StatusPayload } from \"./types.ts\";\n\n/**\n * Why the kernel port ended: a fault in the enclave/transport, or a deliberate host-side lock\n * triggered by the platform (native background expiry — W7).\n */\nexport type PortExit = \"crashed\" | \"background\";\n\n/** The host packages' side of the kernel channel (worker, JSI runtime, in-process test port). */\nexport type MainPort = {\n readonly post: (message: ProtocolValue, transfer: ArrayBuffer[]) => void;\n readonly listen: (handler: (message: unknown) => void) => () => void;\n readonly onExit: (handler: (reason: PortExit) => void) => () => void;\n readonly terminate: () => void;\n};\n\nexport function integrity(message: string): WalletError {\n return new WalletError(\"integrity\", message);\n}\n\n/** Schedules `fn` after `delayMs` and returns a cancel function — injected by the host package. */\nexport type SetTimer = (delayMs: number, fn: () => void) => () => void;\n\n/**\n * A silent kernel is a wedged kernel: the request at the head of the kernel's serial queue gets\n * this long before the port is replaced. Requests still queued behind it are not timed — the kernel\n * answers in order, so only the head can wedge.\n */\nconst CALL_TIMEOUT_MS = 60_000;\n\ntype Pending = {\n readonly method: MethodName;\n readonly resolve: (value: unknown) => void;\n readonly reject: (error: WalletError) => void;\n};\n\n/**\n * State callbacks: the channel owns the port lifecycle and message ordering; the wallet owns the\n * snapshot state these events describe. `onLocked`/`onCrashed` fire before the port is replaced so\n * the wallet can stamp the lock reason.\n */\nexport type ChannelHandlers = {\n readonly onStatus: (status: StatusPayload) => void;\n readonly onLocked: (reason: LockReason) => void;\n readonly onCrashed: () => void;\n};\n\nexport class Channel {\n /** The live kernel session; attached to every request and cleared whenever it is gone. */\n session: string | undefined;\n\n private port: MainPort | undefined;\n private unlisten: (() => void) | undefined;\n private unlistenExit: (() => void) | undefined;\n private generation = 0;\n\n private readonly pending = new Map<number, Pending>();\n /** Times the earliest pending request — the one the kernel is working on. */\n private watchdog: { readonly id: number; readonly cancel: () => void } | undefined;\n private nextId = 1;\n private destroyed = false;\n /** Terminal state: the kernel peer proved untrustworthy; every later call fails with it. */\n private broken: WalletError | undefined;\n /** An unlocked status held back until the session it belongs to is installed. */\n private deferredStatus: StatusPayload | undefined;\n /** Whether the current port has delivered its first valid status event. */\n private portReady = false;\n private readyPromise: Promise<void>;\n private resolveReady: (() => void) | undefined;\n private rejectReady: ((error: WalletError) => void) | undefined;\n\n private readonly spawn: () => MainPort;\n private readonly handlers: ChannelHandlers;\n private readonly setTimer: SetTimer;\n\n constructor(spawn: () => MainPort, handlers: ChannelHandlers, setTimer: SetTimer) {\n this.spawn = spawn;\n this.handlers = handlers;\n this.setTimer = setTimer;\n this.readyPromise = new Promise((resolve, reject) => {\n this.resolveReady = resolve;\n this.rejectReady = reject;\n });\n }\n\n /** Spawns the first kernel and resolves once its initial status event arrives. */\n async start(): Promise<void> {\n this.respawn();\n return this.readyPromise;\n }\n\n /** Resolves when the current port has delivered its first status event. */\n get ready(): Promise<void> {\n return this.readyPromise;\n }\n\n /**\n * Terminates the current port and spawns a fresh secret runtime, keeping the vault image (the\n * host-side store survives the worker). \"Lock destroys the enclave.\"\n */\n respawn(): void {\n if (this.destroyed || this.broken !== undefined) {\n return;\n }\n this.unlisten?.();\n this.unlistenExit?.();\n this.port?.terminate();\n this.port = undefined;\n this.session = undefined;\n this.deferredStatus = undefined;\n this.watchdog?.cancel();\n this.watchdog = undefined;\n this.portReady = false;\n\n const generation = ++this.generation;\n // Settle the previous gate: a call still awaiting it must not hang — the kernel it was\n // waiting for is gone, so \"locked\" (session destroyed) applies.\n // oxlint-disable-next-line promise/prefer-await-to-then -- marks the stale gate as handled without swallowing it for awaiters\n void this.readyPromise.catch(() => undefined);\n this.rejectReady?.(new WalletError(\"locked\", \"the kernel restarted\"));\n this.readyPromise = new Promise((resolve, reject) => {\n this.resolveReady = resolve;\n this.rejectReady = reject;\n });\n // A rejected gate with nobody awaiting it (e.g. destroy() mid-boot) must not surface as\n // an unhandled rejection; callers that do await still observe the rejection.\n // oxlint-disable-next-line promise/prefer-await-to-then -- marks the gate as handled without swallowing it for awaiters\n void this.readyPromise.catch(() => undefined);\n try {\n const port = this.spawn();\n this.unlisten = port.listen((message) => {\n this.onMessage(message, generation);\n });\n this.unlistenExit = port.onExit((reason) => {\n this.onExit(reason, generation);\n });\n this.port = port;\n } catch (error) {\n // A host that cannot spawn has no kernel to talk to — fail closed like a dead peer.\n const spawnError = integrity(\"could not spawn the kernel port\");\n spawnError.cause = error;\n this.breakChannel(spawnError);\n }\n }\n\n private onExit(reason: PortExit, generation: number): void {\n if (generation !== this.generation || this.destroyed || this.broken !== undefined) {\n return;\n }\n this.session = undefined;\n this.deferredStatus = undefined;\n if (!this.portReady) {\n // Death before the first valid status means the runtime never ran honestly (worker\n // blocked by CSP, a script that fails to load, protocol skew): no respawn — a fresh\n // spawn would face the same broken peer. Initial connect rejects with integrity;\n // a respawned port dying this way breaks the wallet.\n this.breakChannel(integrity(\"the kernel port died before its first status\"));\n return;\n }\n if (reason === \"background\") {\n // The platform backgrounded the app past autoLock.backgroundSeconds and locked the\n // enclave: not a crash — take the lock path so the user sees the real reason.\n this.lockWith(\"background\");\n return;\n }\n // A proven port dying is a crash: fail everything in flight, mark it, respawn.\n this.failPending(new WalletError(\"crashed\", \"the kernel port exited\"));\n this.handlers.onCrashed();\n this.respawn();\n }\n\n /**\n * Immediate host-side lock: no kernel round trip. Fails everything in flight with `locked`, drops\n * the session, reports the user lock, and replaces the port — the old worker can never answer\n * again. Safe mid-commit: IndexedDB transactions are atomic.\n */\n lockNow(): void {\n this.lockWith(\"user\");\n }\n\n private lockWith(reason: \"user\" | \"background\"): void {\n if (this.destroyed || this.broken !== undefined) {\n return;\n }\n this.session = undefined;\n this.deferredStatus = undefined;\n this.failPending(new WalletError(\"locked\", \"the vault locked\"));\n this.handlers.onLocked(reason);\n this.respawn();\n }\n\n private onCallTimeout(): void {\n if (this.destroyed || this.broken !== undefined) {\n return;\n }\n this.failPending(new WalletError(\"crashed\", \"the kernel did not answer in time\"));\n this.handlers.onCrashed();\n this.respawn();\n }\n\n private failPending(error: WalletError): void {\n this.watchdog?.cancel();\n this.watchdog = undefined;\n for (const [, pending] of this.pending) {\n pending.reject(error);\n }\n this.pending.clear();\n }\n\n /** (Re)arms the watchdog on `pending`'s insertion-ordered head, or clears it when empty. */\n private armWatchdog(): void {\n this.watchdog?.cancel();\n const head = this.pending.keys().next().value;\n this.watchdog =\n head === undefined\n ? undefined\n : {\n id: head,\n cancel: this.setTimer(CALL_TIMEOUT_MS, () => {\n this.onCallTimeout();\n }),\n };\n }\n\n /** Removes the pending entry, re-timing the watchdog when the head settled, then runs `fn`. */\n private settle(id: number, fn: (pending: Pending) => void): void {\n const pending = this.pending.get(id);\n if (pending !== undefined) {\n this.pending.delete(id);\n if (this.watchdog?.id === id) {\n this.armWatchdog();\n }\n fn(pending);\n }\n }\n\n /**\n * Terminal failure: terminate the port, fail everything in flight, and latch `broken` so every\n * later call rejects with the same error. The snapshot is left untouched.\n */\n private breakChannel(error: WalletError): void {\n this.broken = error;\n this.session = undefined;\n this.deferredStatus = undefined;\n this.failPending(error);\n this.rejectReady?.(error);\n this.unlisten?.();\n this.unlistenExit?.();\n this.port?.terminate();\n this.port = undefined;\n this.generation++; // anything the dead port still emits is stale\n }\n\n /** A malformed protocol peer cannot be trusted — it fails closed, never respawns. */\n private poison(reason: string): void {\n this.breakChannel(integrity(reason));\n }\n\n private onMessage(raw: unknown, generation: number): void {\n if (generation !== this.generation) {\n return; // a dead port must not steer the wallet\n }\n if (\n !isProtocolValue(raw) ||\n typeof raw !== \"object\" ||\n raw === null ||\n raw instanceof Uint8Array ||\n Array.isArray(raw)\n ) {\n this.poison(\"malformed kernel message\");\n return;\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- narrowed to a plain record above\n const message = raw as Readonly<Record<string, ProtocolValue>>;\n if (\"id\" in message) {\n this.onResponse(message);\n return;\n }\n if (\"event\" in message) {\n let event;\n try {\n event = kernelEvent(message);\n } catch (error) {\n if (!(error instanceof ValidationError)) {\n throw error;\n }\n this.poison(\"malformed kernel event\");\n return;\n }\n if (event.event === \"status\") {\n if (event.status.vault !== \"unlocked\") {\n this.session = undefined;\n this.deferredStatus = undefined;\n this.handlers.onStatus(event.status);\n } else if (this.session === undefined) {\n // The unlock/create response has not delivered the session yet — subscribers must\n // never see \"unlocked\" while requests would go out sessionless.\n this.deferredStatus = event.status;\n } else {\n this.handlers.onStatus(event.status);\n }\n this.portReady = true;\n this.resolveReady?.();\n } else {\n // A locked event destroys the enclave: drop the session, tear down the port, respawn.\n this.session = undefined;\n this.deferredStatus = undefined;\n this.handlers.onLocked(event.reason);\n this.failPending(new WalletError(\"locked\", \"the vault locked\"));\n this.respawn();\n }\n return;\n }\n this.poison(\"unrecognised kernel message\");\n }\n\n private onResponse(message: Readonly<Record<string, ProtocolValue>>): void {\n const { id } = message;\n if (typeof id !== \"number\" || !Number.isSafeInteger(id) || message[\"v\"] !== PROTOCOL_VERSION) {\n this.poison(\"malformed response envelope\");\n return;\n }\n const pending = this.pending.get(id);\n if (pending === undefined) {\n // Includes UNATTRIBUTED_ID 0 — never a live request.\n this.poison(\"response for an unknown request\");\n return;\n }\n const hasOk = \"ok\" in message;\n const hasErr = \"err\" in message;\n if (hasOk === hasErr) {\n // Keep the entry so poison's failPending rejects this caller too.\n this.poison(\"malformed response body\");\n return;\n }\n if (hasErr) {\n try {\n const err = responseError(message[\"err\"]);\n this.settle(id, (p) => {\n p.reject(\n new WalletError(\n err.code,\n `kernel returned ${err.code}`,\n typeof err.retryAt === \"number\" ? err.retryAt : undefined,\n err.detail,\n ),\n );\n });\n } catch (error) {\n if (!(error instanceof ValidationError)) {\n throw error;\n }\n this.poison(\"malformed error payload\");\n }\n return;\n }\n try {\n const result = METHODS[pending.method].result(message[\"ok\"]);\n this.settle(id, (p) => {\n p.resolve(result);\n });\n } catch (error) {\n if (!(error instanceof ValidationError)) {\n throw error;\n }\n this.poison(\"invalid result from the kernel\");\n }\n }\n\n /**\n * Sends one request and resolves with the validated result. The kernel answers with status →\n * response → locked, so the snapshot is already current when this promise settles.\n */\n async call<M extends MethodName>(\n method: M,\n params: ParamsOf<M>,\n transfer: ArrayBuffer[] = [],\n ): Promise<ResultOf<M>> {\n await this.readyPromise;\n if (this.broken !== undefined) {\n throw this.broken;\n }\n const { port } = this;\n if (this.destroyed || port === undefined) {\n throw new WalletError(\"locked\", \"wallet is destroyed\");\n }\n const id = this.nextId++;\n const message: Record<string, ProtocolValue> = { v: PROTOCOL_VERSION, id, method, params };\n // Attach the session whenever we hold one: the create/import methods are session:false\n // in the table because the rule is dynamic (required exactly when the vault is initialized).\n if (this.session !== undefined) {\n message[\"session\"] = this.session;\n }\n // The whole envelope counts against the cap — an oversized request never reaches the port.\n if (requestBytes(message) > MAX_REQUEST_BYTES) {\n throw new WalletError(\"invalid-input\", \"request exceeds the size limit\");\n }\n const result = await new Promise<unknown>((resolve, reject) => {\n this.pending.set(id, { method, resolve, reject });\n if (this.watchdog === undefined) {\n // Pending went empty → non-empty: this request is the head the kernel works on next.\n this.armWatchdog();\n }\n try {\n port.post(message, transfer);\n } catch {\n this.pending.delete(id);\n if (this.watchdog?.id === id) {\n this.armWatchdog();\n }\n reject(integrity(\"the kernel port refused the message\"));\n }\n });\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- validated by METHODS[method].result\n return result as ResultOf<M>;\n }\n\n /** Fires the deferred unlocked status, if any, once the session is installed. */\n flushStatus(): void {\n const status = this.deferredStatus;\n if (status !== undefined && this.session !== undefined) {\n this.deferredStatus = undefined;\n this.handlers.onStatus(status);\n }\n }\n\n /** Terminates the port without respawn; later calls fail \"locked\". */\n destroy(): void {\n if (this.destroyed) {\n return;\n }\n this.destroyed = true;\n this.unlisten?.();\n this.unlistenExit?.();\n this.port?.terminate();\n this.port = undefined;\n this.session = undefined;\n this.deferredStatus = undefined;\n this.rejectReady?.(new WalletError(\"locked\", \"wallet is destroyed\"));\n this.failPending(new WalletError(\"locked\", \"wallet is destroyed\"));\n }\n}\n"],"mappings":";;;;;;;;;AAiCA,SAAgB,UAAU,SAA8B;CACtD,OAAO,IAAI,YAAY,aAAa,OAAO;AAC7C;;;;;;AAUA,MAAM,kBAAkB;AAmBxB,IAAa,UAAb,MAAqB;;CAEnB;CAEA;CACA;CACA;CACA,aAAqB;CAErB,0BAA2B,IAAI,IAAqB;;CAEpD;CACA,SAAiB;CACjB,YAAoB;;CAEpB;;CAEA;;CAEA,YAAoB;CACpB;CACA;CACA;CAEA;CACA;CACA;CAEA,YAAY,OAAuB,UAA2B,UAAoB;EAChF,KAAK,QAAQ;EACb,KAAK,WAAW;EAChB,KAAK,WAAW;EAChB,KAAK,eAAe,IAAI,SAAS,SAAS,WAAW;GACnD,KAAK,eAAe;GACpB,KAAK,cAAc;EACrB,CAAC;CACH;;CAGA,MAAM,QAAuB;EAC3B,KAAK,QAAQ;EACb,OAAO,KAAK;CACd;;CAGA,IAAI,QAAuB;EACzB,OAAO,KAAK;CACd;;;;;CAMA,UAAgB;EACd,IAAI,KAAK,aAAa,KAAK,WAAW,KAAA,GACpC;EAEF,KAAK,WAAW;EAChB,KAAK,eAAe;EACpB,KAAK,MAAM,UAAU;EACrB,KAAK,OAAO,KAAA;EACZ,KAAK,UAAU,KAAA;EACf,KAAK,iBAAiB,KAAA;EACtB,KAAK,UAAU,OAA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KAAK,UAAU,OAAO,IACxB,KAAK,YAAY;IAEnB,OAAO,UAAU,qCAAqC,CAAC;GACzD;EACF,CAAC;CAGH;;CAGA,cAAoB;EAClB,MAAM,SAAS,KAAK;EACpB,IAAI,WAAW,KAAA,KAAa,KAAK,YAAY,KAAA,GAAW;GACtD,KAAK,iBAAiB,KAAA;GACtB,KAAK,SAAS,SAAS,MAAM;EAC/B;CACF;;CAGA,UAAgB;EACd,IAAI,KAAK,WACP;EAEF,KAAK,YAAY;EACjB,KAAK,WAAW;EAChB,KAAK,eAAe;EACpB,KAAK,MAAM,UAAU;EACrB,KAAK,OAAO,KAAA;EACZ,KAAK,UAAU,KAAA;EACf,KAAK,iBAAiB,KAAA;EACtB,KAAK,cAAc,IAAI,YAAY,UAAU,qBAAqB,CAAC;EACnE,KAAK,YAAY,IAAI,YAAY,UAAU,qBAAqB,CAAC;CACnE;AACF"}
|
|
1
|
+
{"version":3,"file":"channel-BLwce5hh.mjs","names":[],"sources":["../src/channel.ts"],"sourcesContent":["/**\n * The host side of the kernel channel (design/enclave.mdx \"协议与传输\"): port lifecycle, respawn,\n * request/response correlation and wire validation. Internal to the `./host` subpath — reserved for\n * host packages (wallet-worker, wallet-native); applications must not use it.\n */\nimport {\n isProtocolValue,\n kernelEvent,\n MAX_REQUEST_BYTES,\n METHODS,\n PROTOCOL_VERSION,\n requestBytes,\n responseError,\n ValidationError,\n} from \"./protocol/index.ts\";\nimport type { MethodName, ParamsOf, ProtocolValue, ResultOf } from \"./protocol/index.ts\";\nimport { WalletError } from \"./types.ts\";\nimport type { LockReason, StatusPayload } from \"./types.ts\";\n\n/**\n * Why the kernel port ended: a fault in the enclave/transport, or a deliberate host-side lock\n * triggered by the platform (native background expiry — W7).\n */\nexport type PortExit = \"crashed\" | \"background\";\n\n/** The host packages' side of the kernel channel (worker, JSI runtime, in-process test port). */\nexport type MainPort = {\n readonly post: (message: ProtocolValue, transfer: ArrayBuffer[]) => void;\n readonly listen: (handler: (message: unknown) => void) => () => void;\n readonly onExit: (handler: (reason: PortExit) => void) => () => void;\n readonly terminate: () => void;\n};\n\nexport function integrity(message: string): WalletError {\n return new WalletError(\"integrity\", message);\n}\n\n/** Schedules `fn` after `delayMs` and returns a cancel function — injected by the host package. */\nexport type SetTimer = (delayMs: number, fn: () => void) => () => void;\n\n/**\n * A silent kernel is a wedged kernel: the request at the head of the kernel's serial queue gets\n * this long before the port is replaced. Requests still queued behind it are not timed — the kernel\n * answers in order, so only the head can wedge.\n */\nconst CALL_TIMEOUT_MS = 60_000;\n\ntype Pending = {\n readonly method: MethodName;\n readonly resolve: (value: unknown) => void;\n readonly reject: (error: WalletError) => void;\n};\n\n/**\n * State callbacks: the channel owns the port lifecycle and message ordering; the wallet owns the\n * snapshot state these events describe. `onLocked`/`onCrashed` fire before the port is replaced so\n * the wallet can stamp the lock reason.\n */\nexport type ChannelHandlers = {\n readonly onStatus: (status: StatusPayload) => void;\n readonly onLocked: (reason: LockReason) => void;\n readonly onCrashed: () => void;\n};\n\nexport class Channel {\n /** The live kernel session; attached to every request and cleared whenever it is gone. */\n session: string | undefined;\n\n private port: MainPort | undefined;\n private unlisten: (() => void) | undefined;\n private unlistenExit: (() => void) | undefined;\n private generation = 0;\n\n private readonly pending = new Map<number, Pending>();\n /** Times the earliest pending request — the one the kernel is working on. */\n private watchdog: { readonly id: number; readonly cancel: () => void } | undefined;\n private nextId = 1;\n private destroyed = false;\n /** Terminal state: the kernel peer proved untrustworthy; every later call fails with it. */\n private broken: WalletError | undefined;\n /** An unlocked status held back until the session it belongs to is installed. */\n private deferredStatus: StatusPayload | undefined;\n /** Whether the current port has delivered its first valid status event. */\n private portReady = false;\n private readyPromise: Promise<void>;\n private resolveReady: (() => void) | undefined;\n private rejectReady: ((error: WalletError) => void) | undefined;\n\n private readonly spawn: () => MainPort;\n private readonly handlers: ChannelHandlers;\n private readonly setTimer: SetTimer;\n\n constructor(spawn: () => MainPort, handlers: ChannelHandlers, setTimer: SetTimer) {\n this.spawn = spawn;\n this.handlers = handlers;\n this.setTimer = setTimer;\n this.readyPromise = new Promise((resolve, reject) => {\n this.resolveReady = resolve;\n this.rejectReady = reject;\n });\n }\n\n /** Spawns the first kernel and resolves once its initial status event arrives. */\n async start(): Promise<void> {\n this.respawn();\n return this.readyPromise;\n }\n\n /** Resolves when the current port has delivered its first status event. */\n get ready(): Promise<void> {\n return this.readyPromise;\n }\n\n /**\n * Terminates the current port and spawns a fresh secret runtime, keeping the vault image (the\n * host-side store survives the worker). \"Lock destroys the enclave.\"\n */\n respawn(): void {\n if (this.destroyed || this.broken !== undefined) {\n return;\n }\n this.unlisten?.();\n this.unlistenExit?.();\n this.port?.terminate();\n this.port = undefined;\n this.session = undefined;\n this.deferredStatus = undefined;\n this.watchdog?.cancel();\n this.watchdog = undefined;\n this.portReady = false;\n\n const generation = ++this.generation;\n // Settle the previous gate: a call still awaiting it must not hang — the kernel it was\n // waiting for is gone, so \"locked\" (session destroyed) applies.\n // oxlint-disable-next-line promise/prefer-await-to-then -- marks the stale gate as handled without swallowing it for awaiters\n void this.readyPromise.catch(() => undefined);\n this.rejectReady?.(new WalletError(\"locked\", \"the kernel restarted\"));\n this.readyPromise = new Promise((resolve, reject) => {\n this.resolveReady = resolve;\n this.rejectReady = reject;\n });\n // A rejected gate with nobody awaiting it (e.g. destroy() mid-boot) must not surface as\n // an unhandled rejection; callers that do await still observe the rejection.\n // oxlint-disable-next-line promise/prefer-await-to-then -- marks the gate as handled without swallowing it for awaiters\n void this.readyPromise.catch(() => undefined);\n try {\n const port = this.spawn();\n this.unlisten = port.listen((message) => {\n this.onMessage(message, generation);\n });\n this.unlistenExit = port.onExit((reason) => {\n this.onExit(reason, generation);\n });\n this.port = port;\n } catch (error) {\n // A host that cannot spawn has no kernel to talk to — fail closed like a dead peer.\n const spawnError = integrity(\"could not spawn the kernel port\");\n spawnError.cause = error;\n this.breakChannel(spawnError);\n }\n }\n\n private onExit(reason: PortExit, generation: number): void {\n if (generation !== this.generation || this.destroyed || this.broken !== undefined) {\n return;\n }\n this.session = undefined;\n this.deferredStatus = undefined;\n if (!this.portReady) {\n // Death before the first valid status means the runtime never ran honestly (worker\n // blocked by CSP, a script that fails to load, protocol skew): no respawn — a fresh\n // spawn would face the same broken peer. Initial connect rejects with integrity;\n // a respawned port dying this way breaks the wallet.\n this.breakChannel(integrity(\"the kernel port died before its first status\"));\n return;\n }\n if (reason === \"background\") {\n // The platform backgrounded the app past autoLock.backgroundSeconds and locked the\n // enclave: not a crash — take the lock path so the user sees the real reason.\n this.lockWith(\"background\");\n return;\n }\n // A proven port dying is a crash: fail everything in flight, mark it, respawn.\n this.failPending(new WalletError(\"crashed\", \"the kernel port exited\"));\n this.handlers.onCrashed();\n this.respawn();\n }\n\n /**\n * Immediate host-side lock: no kernel round trip. Fails everything in flight with `locked`, drops\n * the session, reports the user lock, and replaces the port — the old worker can never answer\n * again. Safe mid-commit: IndexedDB transactions are atomic.\n */\n lockNow(): void {\n this.lockWith(\"user\");\n }\n\n private lockWith(reason: \"user\" | \"background\"): void {\n if (this.destroyed || this.broken !== undefined) {\n return;\n }\n this.session = undefined;\n this.deferredStatus = undefined;\n this.failPending(new WalletError(\"locked\", \"the vault locked\"));\n this.handlers.onLocked(reason);\n this.respawn();\n }\n\n private onCallTimeout(): void {\n if (this.destroyed || this.broken !== undefined) {\n return;\n }\n this.failPending(new WalletError(\"crashed\", \"the kernel did not answer in time\"));\n this.handlers.onCrashed();\n this.respawn();\n }\n\n private failPending(error: WalletError): void {\n this.watchdog?.cancel();\n this.watchdog = undefined;\n for (const [, pending] of this.pending) {\n pending.reject(error);\n }\n this.pending.clear();\n }\n\n /** (Re)arms the watchdog on `pending`'s insertion-ordered head, or clears it when empty. */\n private armWatchdog(): void {\n this.watchdog?.cancel();\n const head = this.pending.keys().next().value;\n this.watchdog =\n head === undefined\n ? undefined\n : {\n id: head,\n cancel: this.setTimer(CALL_TIMEOUT_MS, () => {\n this.onCallTimeout();\n }),\n };\n }\n\n /** Removes the pending entry, re-timing the watchdog when the head settled, then runs `fn`. */\n private settle(id: number, fn: (pending: Pending) => void): void {\n const pending = this.pending.get(id);\n if (pending !== undefined) {\n this.pending.delete(id);\n if (this.watchdog?.id === id) {\n this.armWatchdog();\n }\n fn(pending);\n }\n }\n\n /**\n * Terminal failure: terminate the port, fail everything in flight, and latch `broken` so every\n * later call rejects with the same error. The snapshot is left untouched.\n */\n private breakChannel(error: WalletError): void {\n this.broken = error;\n this.session = undefined;\n this.deferredStatus = undefined;\n this.failPending(error);\n this.rejectReady?.(error);\n this.unlisten?.();\n this.unlistenExit?.();\n this.port?.terminate();\n this.port = undefined;\n this.generation++; // anything the dead port still emits is stale\n }\n\n /** A malformed protocol peer cannot be trusted — it fails closed, never respawns. */\n private poison(reason: string): void {\n this.breakChannel(integrity(reason));\n }\n\n private onMessage(raw: unknown, generation: number): void {\n if (generation !== this.generation) {\n return; // a dead port must not steer the wallet\n }\n if (\n !isProtocolValue(raw) ||\n typeof raw !== \"object\" ||\n raw === null ||\n raw instanceof Uint8Array ||\n Array.isArray(raw)\n ) {\n this.poison(\"malformed kernel message\");\n return;\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- narrowed to a plain record above\n const message = raw as Readonly<Record<string, ProtocolValue>>;\n if (\"id\" in message) {\n this.onResponse(message);\n return;\n }\n if (\"event\" in message) {\n let event;\n try {\n event = kernelEvent(message);\n } catch (error) {\n if (!(error instanceof ValidationError)) {\n throw error;\n }\n this.poison(\"malformed kernel event\");\n return;\n }\n if (event.event === \"status\") {\n if (event.status.vault !== \"unlocked\") {\n this.session = undefined;\n this.deferredStatus = undefined;\n this.handlers.onStatus(event.status);\n } else if (this.session === undefined) {\n // The unlock/create response has not delivered the session yet — subscribers must\n // never see \"unlocked\" while requests would go out sessionless.\n this.deferredStatus = event.status;\n } else {\n this.handlers.onStatus(event.status);\n }\n this.portReady = true;\n this.resolveReady?.();\n } else {\n // A locked event destroys the enclave: drop the session, tear down the port, respawn.\n this.session = undefined;\n this.deferredStatus = undefined;\n this.handlers.onLocked(event.reason);\n this.failPending(new WalletError(\"locked\", \"the vault locked\"));\n this.respawn();\n }\n return;\n }\n this.poison(\"unrecognised kernel message\");\n }\n\n private onResponse(message: Readonly<Record<string, ProtocolValue>>): void {\n const { id } = message;\n if (typeof id !== \"number\" || !Number.isSafeInteger(id) || message[\"v\"] !== PROTOCOL_VERSION) {\n this.poison(\"malformed response envelope\");\n return;\n }\n const pending = this.pending.get(id);\n if (pending === undefined) {\n // Includes UNATTRIBUTED_ID 0 — never a live request.\n this.poison(\"response for an unknown request\");\n return;\n }\n const hasOk = \"ok\" in message;\n const hasErr = \"err\" in message;\n if (hasOk === hasErr) {\n // Keep the entry so poison's failPending rejects this caller too.\n this.poison(\"malformed response body\");\n return;\n }\n if (hasErr) {\n try {\n const err = responseError(message[\"err\"]);\n this.settle(id, (p) => {\n p.reject(\n new WalletError(\n err.code,\n `kernel returned ${err.code}`,\n typeof err.retryAt === \"number\" ? err.retryAt : undefined,\n err.detail,\n ),\n );\n });\n } catch (error) {\n if (!(error instanceof ValidationError)) {\n throw error;\n }\n this.poison(\"malformed error payload\");\n }\n return;\n }\n try {\n const result = METHODS[pending.method].result(message[\"ok\"]);\n this.settle(id, (p) => {\n p.resolve(result);\n });\n } catch (error) {\n if (!(error instanceof ValidationError)) {\n throw error;\n }\n this.poison(\"invalid result from the kernel\");\n }\n }\n\n /**\n * Sends one request and resolves with the validated result. The kernel answers with status →\n * response → locked, so the snapshot is already current when this promise settles.\n */\n async call<M extends MethodName>(\n method: M,\n params: ParamsOf<M>,\n transfer: ArrayBuffer[] = [],\n ): Promise<ResultOf<M>> {\n await this.readyPromise;\n if (this.broken !== undefined) {\n throw this.broken;\n }\n const { port } = this;\n if (this.destroyed || port === undefined) {\n throw new WalletError(\"locked\", \"wallet is destroyed\");\n }\n const id = this.nextId++;\n const message: Record<string, ProtocolValue> = { v: PROTOCOL_VERSION, id, method, params };\n // Attach the session whenever we hold one: the create/import methods are session:false\n // in the table because the rule is dynamic (required exactly when the vault is initialized).\n if (this.session !== undefined) {\n message[\"session\"] = this.session;\n }\n // The whole envelope counts against the cap — an oversized request never reaches the port.\n if (requestBytes(message) > MAX_REQUEST_BYTES) {\n throw new WalletError(\"invalid-input\", \"request exceeds the size limit\");\n }\n const result = await new Promise<unknown>((resolve, reject) => {\n this.pending.set(id, { method, resolve, reject });\n if (this.watchdog === undefined) {\n // Pending went empty → non-empty: this request is the head the kernel works on next.\n this.armWatchdog();\n }\n try {\n port.post(message, transfer);\n } catch {\n this.pending.delete(id);\n if (this.watchdog?.id === id) {\n this.armWatchdog();\n }\n reject(integrity(\"the kernel port refused the message\"));\n }\n });\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- validated by METHODS[method].result\n return result as ResultOf<M>;\n }\n\n /** Fires the deferred unlocked status, if any, once the session is installed. */\n flushStatus(): void {\n const status = this.deferredStatus;\n if (status !== undefined && this.session !== undefined) {\n this.deferredStatus = undefined;\n this.handlers.onStatus(status);\n }\n }\n\n /** Terminates the port without respawn; later calls fail \"locked\". */\n destroy(): void {\n if (this.destroyed) {\n return;\n }\n this.destroyed = true;\n this.unlisten?.();\n this.unlistenExit?.();\n this.port?.terminate();\n this.port = undefined;\n this.session = undefined;\n this.deferredStatus = undefined;\n this.rejectReady?.(new WalletError(\"locked\", \"wallet is destroyed\"));\n this.failPending(new WalletError(\"locked\", \"wallet is destroyed\"));\n }\n}\n"],"mappings":";;;;;;;;;AAiCA,SAAgB,UAAU,SAA8B;CACtD,OAAO,IAAI,YAAY,aAAa,OAAO;AAC7C;;;;;;AAUA,MAAM,kBAAkB;AAmBxB,IAAa,UAAb,MAAqB;;CAEnB;CAEA;CACA;CACA;CACA,aAAqB;CAErB,0BAA2B,IAAI,IAAqB;;CAEpD;CACA,SAAiB;CACjB,YAAoB;;CAEpB;;CAEA;;CAEA,YAAoB;CACpB;CACA;CACA;CAEA;CACA;CACA;CAEA,YAAY,OAAuB,UAA2B,UAAoB;EAChF,KAAK,Q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AM,KAAK,KAAK;EAChB,MAAM,UAAyC;GAAE,GAAA;GAAqB;GAAI;GAAQ;EAAO;EAGzF,IAAI,KAAK,YAAY,KAAA,GACnB,QAAQ,aAAa,KAAK;EAG5B,IAAI,aAAa,OAAO,IAAA,SACtB,MAAM,IAAI,YAAY,iBAAiB,gCAAgC;EAmBzE,OAAO,MAjBc,IAAI,SAAkB,SAAS,WAAW;GAC7D,KAAK,QAAQ,IAAI,IAAI;IAAE;IAAQ;IAAS;GAAO,CAAC;GAChD,IAAI,KAAK,aAAa,KAAA,GAEpB,KAAK,YAAY;GAEnB,IAAI;IACF,KAAK,KAAK,SAAS,QAAQ;GAC7B,QAAQ;IACN,KAAK,QAAQ,OAAO,EAAE;IACtB,IAAI,KAAK,UAAU,OAAO,IACxB,KAAK,YAAY;IAEnB,OAAO,UAAU,qCAAqC,CAAC;GACzD;EACF,CAAC;CAGH;;CAGA,cAAoB;EAClB,MAAM,SAAS,KAAK;EACpB,IAAI,WAAW,KAAA,KAAa,KAAK,YAAY,KAAA,GAAW;GACtD,KAAK,iBAAiB,KAAA;GACtB,KAAK,SAAS,SAAS,MAAM;EAC/B;CACF;;CAGA,UAAgB;EACd,IAAI,KAAK,WACP;EAEF,KAAK,YAAY;EACjB,KAAK,WAAW;EAChB,KAAK,eAAe;EACpB,KAAK,MAAM,UAAU;EACrB,KAAK,OAAO,KAAA;EACZ,KAAK,UAAU,KAAA;EACf,KAAK,iBAAiB,KAAA;EACtB,KAAK,cAAc,IAAI,YAAY,UAAU,qBAAqB,CAAC;EACnE,KAAK,YAAY,IAAI,YAAY,UAAU,qBAAqB,CAAC;CACnE;AACF"}
|
|
@@ -130,10 +130,18 @@ const MAX_SNAPSHOT_ITEMS = 4096;
|
|
|
130
130
|
const sessionId = str(32, /^[0-9a-f]{32}$/);
|
|
131
131
|
const draftId = str(32, /^[0-9a-f]{32}$/);
|
|
132
132
|
const walletId = str(16, /^[0-9a-f]{16}$/);
|
|
133
|
+
const keyId = str(16, /^[0-9a-f]{16}$/);
|
|
134
|
+
const keyFamily = union(literal("evm"), literal("solana"), literal("bitcoin"));
|
|
133
135
|
const publicKey = str(64, /^[0-9a-f]{64}$/);
|
|
134
136
|
const credentialId = str(1364, /^[A-Za-z0-9_-]+$/);
|
|
135
137
|
const safeTime = int(0, Number.MAX_SAFE_INTEGER);
|
|
136
138
|
const groupIndex = int(0, 2147483647);
|
|
139
|
+
const keyInfo = obj({
|
|
140
|
+
keyId,
|
|
141
|
+
family: keyFamily,
|
|
142
|
+
address: str(90, /^.+$/),
|
|
143
|
+
createdAt: safeTime
|
|
144
|
+
});
|
|
137
145
|
/** Identity indices stop below 2^31 - 1 — the top segment derives the wallet sync key. */
|
|
138
146
|
const identityIndex = int(0, 2147483646);
|
|
139
147
|
const factor = union(obj({ kind: literal("hardware") }), obj({
|
|
@@ -372,8 +380,41 @@ const CORE_METHODS = {
|
|
|
372
380
|
presence: false,
|
|
373
381
|
params: obj({ purpose: str(32, /^[a-z0-9-]{1,32}$/) }),
|
|
374
382
|
result: bytes(32)
|
|
383
|
+
},
|
|
384
|
+
"keys.import": {
|
|
385
|
+
session: true,
|
|
386
|
+
presence: true,
|
|
387
|
+
params: obj({
|
|
388
|
+
family: keyFamily,
|
|
389
|
+
secret: bytes(32, 64)
|
|
390
|
+
}),
|
|
391
|
+
result: keyInfo
|
|
392
|
+
},
|
|
393
|
+
"keys.list": {
|
|
394
|
+
session: true,
|
|
395
|
+
presence: true,
|
|
396
|
+
params: nullValue,
|
|
397
|
+
result: arr(keyInfo, 256)
|
|
398
|
+
},
|
|
399
|
+
"keys.remove": {
|
|
400
|
+
session: true,
|
|
401
|
+
presence: true,
|
|
402
|
+
params: obj({
|
|
403
|
+
verify: factor,
|
|
404
|
+
keyId
|
|
405
|
+
}),
|
|
406
|
+
result: nullValue
|
|
407
|
+
},
|
|
408
|
+
"keys.export": {
|
|
409
|
+
session: true,
|
|
410
|
+
presence: true,
|
|
411
|
+
params: obj({
|
|
412
|
+
verify: factor,
|
|
413
|
+
keyId
|
|
414
|
+
}),
|
|
415
|
+
result: bytes(1, 256)
|
|
375
416
|
}
|
|
376
417
|
};
|
|
377
|
-
export {
|
|
418
|
+
export { obj as C, union as D, str as E, validate as O, nullValue as S, record as T, arr as _, MAX_TEXT as a, int as b, groupIndex as c, publicKey as d, safeTime as f, ValidationError as g, walletInfo as h, MAX_TAG_ITEM as i, identityIndex as l, walletId as m, MAX_SNAPSHOT_ITEMS as n, factor as o, walletErrorCode as p, MAX_TAGS as r, factorInfo as s, CORE_METHODS as t, keyInfo as u, bool as v, opt as w, literal as x, bytes as y };
|
|
378
419
|
|
|
379
|
-
//# sourceMappingURL=core-
|
|
420
|
+
//# sourceMappingURL=core-DaRwkTaV.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"core-DaRwkTaV.mjs","names":[],"sources":["../src/protocol/validate.ts","../src/protocol/core.ts"],"sourcesContent":["/**\n * Strict validator combinators for the secret-area protocol. Both sides share them: the kernel\n * validates every request, the host validates every response. Anything that does not match is a\n * `ValidationError` — never a partially-accepted value.\n */\n\nexport class ValidationError extends Error {\n override name = \"ValidationError\";\n}\n\nexport type Validator<T> = (value: unknown) => T;\n\nfunction fail(): never {\n throw new ValidationError();\n}\n\n// oxlint-disable-next-line typescript/no-restricted-types -- JSON null is a protocol value\nexport type NullValue = null;\n\nexport function literal<T extends NullValue | boolean | number | string>(\n expected: T,\n): Validator<T> {\n return (value) => {\n if (value !== expected) {\n fail();\n }\n return expected;\n };\n}\n\nexport const nullValue: Validator<NullValue> = literal(null);\nexport const bool: Validator<boolean> = (value) => {\n if (typeof value !== \"boolean\") {\n fail();\n }\n return value;\n};\n\nexport function int(min: number, max: number): Validator<number> {\n return (value) => {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < min || value > max) {\n fail();\n }\n return value;\n };\n}\n\nexport function str(max: number, pattern?: RegExp): Validator<string> {\n return (value) => {\n if (\n typeof value !== \"string\" ||\n value.length > max ||\n (pattern !== undefined && !pattern.test(value))\n ) {\n fail();\n }\n return value;\n };\n}\n\nexport function bytes(min: number, max?: number): Validator<Uint8Array> {\n const high = max ?? min;\n return (value) => {\n if (!(value instanceof Uint8Array) || value.length < min || value.length > high) {\n fail();\n }\n return value;\n };\n}\n\nexport function arr<T>(item: Validator<T>, max: number, min = 0): Validator<ReadonlyArray<T>> {\n return (value) => {\n if (!Array.isArray(value) || value.length < min || value.length > max) {\n fail();\n }\n const out: T[] = [];\n for (const element of value) {\n out.push(item(element));\n }\n return out;\n };\n}\n\nclass Opt<T> {\n readonly validator: Validator<T>;\n\n constructor(validator: Validator<T>) {\n this.validator = validator;\n }\n}\n\nexport function opt<T>(validator: Validator<T>): Opt<T> {\n return new Opt(validator);\n}\n\ntype Field = Validator<unknown> | Opt<unknown>;\ntype Shape = Record<string, Field>;\n\ntype RequiredKeys<S extends Shape> = {\n readonly [K in keyof S as S[K] extends Opt<unknown> ? never : K]: S[K] extends Validator<infer T>\n ? T\n : never;\n};\ntype OptionalKeys<S extends Shape> = {\n readonly [K in keyof S as S[K] extends Opt<unknown> ? K : never]?: S[K] extends Opt<infer T>\n ? T\n : never;\n};\ntype ShapeResult<S extends Shape> = RequiredKeys<S> & OptionalKeys<S>;\n\n/** Exact key set: required keys present, optional keys allowed, nothing else. */\nexport function obj<S extends Shape>(shape: S): Validator<ShapeResult<S>> {\n const keys = Object.keys(shape);\n return (value) => {\n if (\n typeof value !== \"object\" ||\n value === null ||\n Array.isArray(value) ||\n value instanceof Uint8Array\n ) {\n fail();\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- narrowed to a plain object above\n const record = value as Record<string, unknown>;\n for (const key of Object.keys(record)) {\n if (!Object.hasOwn(shape, key)) {\n fail();\n }\n }\n const out: Record<string, unknown> = {};\n for (const key of keys) {\n const field = shape[key];\n if (field === undefined) {\n fail();\n }\n const raw = record[key];\n if (field instanceof Opt) {\n if (raw !== undefined) {\n out[key] = field.validator(raw);\n }\n } else {\n if (!Object.hasOwn(record, key)) {\n fail();\n }\n out[key] = field(raw);\n }\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the shape guarantees the keys\n return out as ShapeResult<S>;\n };\n}\n\nconst FORBIDDEN_RECORD_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/**\n * A `Record<K, V>` wire value: plain objects only, every key checked by `key`, every value by\n * `value`, at most `max` entries. Prototype-polluting keys are rejected outright — a validated\n * record must be safe to copy key-by-key.\n */\nexport function record<K extends string, V>(\n key: Validator<K>,\n value: Validator<V>,\n max: number,\n): Validator<Record<K, V>> {\n return (input) => {\n if (\n typeof input !== \"object\" ||\n input === null ||\n Array.isArray(input) ||\n input instanceof Uint8Array ||\n Object.getPrototypeOf(input) !== Object.prototype\n ) {\n fail();\n }\n const out: Record<string, V> = {};\n const entries = Object.entries(input);\n if (entries.length > max) {\n fail();\n }\n for (const [name, item] of entries) {\n if (FORBIDDEN_RECORD_KEYS.has(name)) {\n fail();\n }\n out[key(name)] = value(item);\n }\n return out;\n };\n}\n\n/** Tries each branch in order; the first match wins. */\nexport function union<Vs extends ReadonlyArray<Validator<unknown>>>(\n ...branches: Vs\n): Validator<ReturnType<Vs[number]>> {\n return (value) => {\n for (const branch of branches) {\n try {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- ReturnType of the branch union\n return branch(value) as ReturnType<Vs[number]>;\n } catch (error) {\n if (!(error instanceof ValidationError)) {\n throw error;\n }\n }\n }\n return fail();\n };\n}\n\n/** Validates a value and returns it, or undefined on a shape mismatch. */\nexport function validate<T>(validator: Validator<T>, value: unknown): T | undefined {\n try {\n return validator(value);\n } catch (error) {\n if (error instanceof ValidationError) {\n return undefined;\n }\n throw error;\n }\n}\n","/**\n * The core method table: vault, wallet and data-key commands — nothing protocol-specific. \"Create\n * or import\" commands (createWithPasskey/restoreWithPasskey/createMnemonic/importMnemonic) are\n * `session: false` here because the rule is dynamic: with an uninitialized vault they carry\n * `factor` and establish the vault in one commit; with an established vault `factor` must be absent\n * and a valid session is required.\n *\n * The shared wire validators (factor, wallet info, ids) live here too so the nostr module's table\n * can reuse them — `protocol/nostr.ts` imports only from this file.\n */\nimport type { FactorInfo, WalletErrorCode, WalletInfo } from \"../types.ts\";\nimport type { NullValue, Validator } from \"./validate.ts\";\nimport { arr, bool, bytes, int, literal, nullValue, obj, opt, str, union } from \"./validate.ts\";\n\nexport type MethodSpec<P, R> = {\n readonly session: boolean;\n /** Whether a successful call refreshes the idle timer — presence-bearing methods only. */\n readonly presence: boolean;\n readonly params: Validator<P>;\n readonly result: Validator<R>;\n};\n\n// Size caps (UTF-16 units for strings, bytes for Uint8Array). These bound individual fields; the\n// whole-request cap MAX_REQUEST_BYTES (protocol/index.ts) is enforced by host and kernel.\nexport const MAX_TEXT = 262_144;\nexport const MAX_TAGS = 1024;\nexport const MAX_TAG_ITEMS = 64;\nexport const MAX_TAG_ITEM = 4096;\nexport const MAX_BATCH = 64;\nexport const MAX_SNAPSHOT_ITEMS = 4096;\n\nexport const sessionId: Validator<string> = str(32, /^[0-9a-f]{32}$/);\nexport const draftId: Validator<string> = str(32, /^[0-9a-f]{32}$/);\nexport const walletId: Validator<string> = str(16, /^[0-9a-f]{16}$/);\nexport const keyId: Validator<string> = str(16, /^[0-9a-f]{16}$/);\nexport const keyFamily: Validator<\"evm\" | \"solana\" | \"bitcoin\"> = union(\n literal(\"evm\"),\n literal(\"solana\"),\n literal(\"bitcoin\"),\n);\n\nexport const publicKey: Validator<string> = str(64, /^[0-9a-f]{64}$/);\nexport const credentialId: Validator<string> = str(1364, /^[A-Za-z0-9_-]+$/);\nexport const safeTime: Validator<number> = int(0, Number.MAX_SAFE_INTEGER);\nexport const groupIndex: Validator<number> = int(0, 0x7fffffff);\nexport const keyInfo: Validator<{\n readonly keyId: string;\n readonly family: \"evm\" | \"solana\" | \"bitcoin\";\n readonly address: string;\n readonly createdAt: number;\n}> = obj({ keyId, family: keyFamily, address: str(90, /^.+$/), createdAt: safeTime });\n/** Identity indices stop below 2^31 - 1 — the top segment derives the wallet sync key. */\nexport const identityIndex: Validator<number> = int(0, 0x7ffffffe);\n\n/**\n * Vault factor material on the wire. `hardware` carries nothing: the kernel runs the platform\n * keystore ceremony itself, so the main runtime never touches the KEK.\n */\nexport type Factor =\n | { readonly kind: \"hardware\" }\n | { readonly kind: \"password\"; readonly password: Uint8Array }\n | { readonly kind: \"passkey\"; readonly credentialId: Uint8Array; readonly prf: Uint8Array };\n\nexport const factor: Validator<Factor> = union(\n obj({ kind: literal(\"hardware\") }),\n obj({ kind: literal(\"password\"), password: bytes(1, 1024) }),\n obj({ kind: literal(\"passkey\"), credentialId: bytes(1, 1023), prf: bytes(32) }),\n);\n\n/** A host-run backup passkey ceremony's evidence: the PRF over `backupSalt` (web). */\ntype HostBackupPasskey = {\n readonly kind: \"passkey\";\n readonly ceremony: \"host\";\n readonly credentialId: Uint8Array;\n readonly prfBackup: Uint8Array;\n};\n\n/**\n * A factor that seals a new backup key. On React Native the kernel registers a protection\n * credential (`kernel`) itself and names it; on the web the host hands over its ceremony's\n * evidence.\n */\nexport type BackupFactor =\n | { readonly kind: \"password\"; readonly password: Uint8Array }\n | HostBackupPasskey\n | {\n readonly kind: \"passkey\";\n readonly ceremony: \"kernel\";\n readonly rpId: string;\n readonly rpName: string;\n readonly backupSalt: string;\n };\n\n/**\n * A factor that opens a backup envelope. The `kernel` passkey arm asserts one of the envelope's own\n * credentials.\n */\nexport type BackupUnlockFactor =\n | { readonly kind: \"password\"; readonly password: Uint8Array }\n | HostBackupPasskey\n | {\n readonly kind: \"passkey\";\n readonly ceremony: \"kernel\";\n readonly rpId: string;\n readonly backupSalt: string;\n };\n\nexport const factorInfo: Validator<FactorInfo> = union(\n obj({ kind: literal(\"hardware\"), id: sessionId, createdAt: safeTime }),\n obj({\n kind: literal(\"passkey\"),\n id: sessionId,\n credentialId,\n createdAt: safeTime,\n }),\n obj({ kind: literal(\"password\"), id: sessionId, createdAt: safeTime }),\n);\n\n/**\n * Passkey wallet creation. `host`: the host ran the WebAuthn ceremony and hands over the PRF\n * evidence (web). `kernel`: the kernel runs the platform ceremony itself and nothing secret crosses\n * the channel (React Native). The kernel accepts exactly the shape its platform supports.\n */\nexport type CreateWithPasskeyParams =\n | {\n readonly ceremony: \"host\";\n readonly credentialId: Uint8Array;\n readonly prfWallet: Uint8Array;\n readonly synced: boolean;\n readonly factor?: Factor;\n }\n | {\n readonly ceremony: \"kernel\";\n readonly rpId: string;\n readonly rpName: string;\n readonly name: string;\n readonly walletSalt: string;\n readonly factor?: Factor;\n };\n\nexport type RestoreWithPasskeyParams =\n | {\n readonly ceremony: \"host\";\n readonly credentialId: Uint8Array;\n readonly prfWallet: Uint8Array;\n readonly synced: boolean;\n readonly factor?: Factor;\n }\n | {\n readonly ceremony: \"kernel\";\n readonly rpId: string;\n readonly walletSalt: string;\n readonly factor?: Factor;\n };\n\n// An RP id is a lowercase DNS name; the platform rejects anything its associated domains do not\n// list, so this only bounds the shape.\nconst RP_ID =\n /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/;\nconst label = (max: number): Validator<string> => str(max, /^\\S(?:.*\\S)?$/su);\n\nconst hostEvidence = {\n ceremony: literal(\"host\"),\n credentialId: bytes(1, 1023),\n prfWallet: bytes(32),\n synced: bool,\n factor: opt(factor),\n};\n\nconst createWithPasskeyParams: Validator<CreateWithPasskeyParams> = union(\n obj(hostEvidence),\n obj({\n ceremony: literal(\"kernel\"),\n rpId: str(253, RP_ID),\n rpName: label(64),\n name: label(64),\n walletSalt: label(64),\n factor: opt(factor),\n }),\n);\n\nconst restoreWithPasskeyParams: Validator<RestoreWithPasskeyParams> = union(\n obj(hostEvidence),\n obj({\n ceremony: literal(\"kernel\"),\n rpId: str(253, RP_ID),\n walletSalt: label(64),\n factor: opt(factor),\n }),\n);\n\nconst hostBackupPasskey = obj({\n kind: literal(\"passkey\"),\n ceremony: literal(\"host\"),\n credentialId: bytes(1, 1023),\n prfBackup: bytes(32),\n});\nconst backupPassword = obj({ kind: literal(\"password\"), password: bytes(1, 1024) });\n\nexport const backupFactor: Validator<BackupFactor> = union(\n backupPassword,\n hostBackupPasskey,\n obj({\n kind: literal(\"passkey\"),\n ceremony: literal(\"kernel\"),\n rpId: str(253, RP_ID),\n rpName: label(64),\n backupSalt: label(64),\n }),\n);\n\nexport const backupUnlockFactor: Validator<BackupUnlockFactor> = union(\n backupPassword,\n hostBackupPasskey,\n obj({\n kind: literal(\"passkey\"),\n ceremony: literal(\"kernel\"),\n rpId: str(253, RP_ID),\n backupSalt: label(64),\n }),\n);\n\nexport const walletInfo: Validator<WalletInfo> = obj({\n walletId,\n origin: union(literal(\"passkey\"), literal(\"mnemonic\")),\n words: union(literal(12), literal(15), literal(18), literal(21), literal(24)),\n backup: union(literal(\"none\"), literal(\"passkey\"), literal(\"mnemonic\")),\n passphrase: bool,\n createdAt: safeTime,\n});\n\n/** A BIP-39 passphrase on the wire: raw UTF-8 bytes, never empty (the host omits \"none\"). */\nconst passphraseBytes: Validator<Uint8Array> = bytes(1, 1024);\n\nexport const walletErrorCode: Validator<WalletErrorCode> = union(\n literal(\"locked\"),\n literal(\"cancelled\"),\n literal(\"factor-invalidated\"),\n literal(\"no-device-credential\"),\n literal(\"passkey-not-configured\"),\n literal(\"passkey-prf-unsupported\"),\n literal(\"wrong-password\"),\n literal(\"wrong-passkey\"),\n literal(\"rate-limited\"),\n literal(\"invalid-input\"),\n literal(\"not-found\"),\n literal(\"already-exists\"),\n literal(\"conflict\"),\n literal(\"unsupported\"),\n literal(\"unavailable\"),\n literal(\"integrity\"),\n literal(\"approval-required\"),\n literal(\"crashed\"),\n);\n\n/**\n * The result of every \"create or import\" wallet command: the new wallet's public info plus the\n * session it opened. Creating a wallet derives no protocol keys — modules add keys separately.\n */\nexport type CreatedResult = {\n readonly wallet: WalletInfo;\n readonly session: string;\n};\n\nconst createdResult: Validator<CreatedResult> = obj({ wallet: walletInfo, session: sessionId });\n\n// `status` itself is a core method, but its result validator composes every module's status\n// section — it is wired in protocol/index.ts, not here.\nexport const CORE_METHODS: {\n readonly \"vault.unlock\": MethodSpec<{ readonly factor: Factor }, { readonly session: string }>;\n readonly \"vault.reset\": MethodSpec<NullValue, NullValue>;\n readonly \"vault.addFactor\": MethodSpec<\n { readonly verify: Factor; readonly factor: Factor },\n FactorInfo\n >;\n readonly \"vault.removeFactor\": MethodSpec<\n { readonly verify: Factor; readonly id: string },\n NullValue\n >;\n readonly \"session.touch\": MethodSpec<NullValue, NullValue>;\n readonly \"wallet.createWithPasskey\": MethodSpec<CreateWithPasskeyParams, CreatedResult>;\n readonly \"wallet.restoreWithPasskey\": MethodSpec<RestoreWithPasskeyParams, CreatedResult>;\n readonly \"wallet.createMnemonic\": MethodSpec<\n { readonly words: 12 | 24; readonly factor?: Factor },\n { readonly draft: string; readonly words: Uint8Array; readonly quiz: ReadonlyArray<number> }\n >;\n readonly \"wallet.confirmMnemonic\": MethodSpec<\n {\n readonly draft: string;\n readonly answers: ReadonlyArray<Uint8Array>;\n readonly passphrase?: Uint8Array;\n },\n CreatedResult\n >;\n readonly \"wallet.discardMnemonic\": MethodSpec<{ readonly draft: string }, NullValue>;\n readonly \"backup.enable\": MethodSpec<\n {\n readonly verify: Factor;\n readonly factors: ReadonlyArray<BackupFactor>;\n },\n NullValue\n >;\n readonly \"backup.update\": MethodSpec<NullValue, { readonly envelope: string }>;\n readonly \"backup.disable\": MethodSpec<NullValue, NullValue>;\n readonly \"backup.restore\": MethodSpec<\n {\n readonly envelope: string;\n readonly backupFactor: BackupUnlockFactor;\n readonly passphrases?: ReadonlyArray<{\n readonly walletId: string;\n readonly passphrase: Uint8Array;\n }>;\n readonly factor?: Factor;\n },\n {\n readonly wallets: ReadonlyArray<WalletInfo>;\n readonly passphraseRequired: ReadonlyArray<string>;\n readonly session: string;\n }\n >;\n readonly \"wallet.importMnemonic\": MethodSpec<\n { readonly mnemonic: Uint8Array; readonly passphrase?: Uint8Array; readonly factor?: Factor },\n CreatedResult\n >;\n readonly \"wallet.exportMnemonic\": MethodSpec<\n { readonly verify: Factor; readonly walletId: string },\n { readonly mnemonic: Uint8Array; readonly passphrase?: Uint8Array }\n >;\n readonly \"wallet.delete\": MethodSpec<\n { readonly verify: Factor; readonly walletId: string },\n NullValue\n >;\n readonly \"dataKeys.get\": MethodSpec<{ readonly purpose: string }, Uint8Array>;\n readonly \"keys.import\": MethodSpec<\n { readonly family: \"evm\" | \"solana\" | \"bitcoin\"; readonly secret: Uint8Array },\n {\n readonly keyId: string;\n readonly family: \"evm\" | \"solana\" | \"bitcoin\";\n readonly address: string;\n readonly createdAt: number;\n }\n >;\n readonly \"keys.list\": MethodSpec<\n NullValue,\n ReadonlyArray<{\n readonly keyId: string;\n readonly family: \"evm\" | \"solana\" | \"bitcoin\";\n readonly address: string;\n readonly createdAt: number;\n }>\n >;\n readonly \"keys.remove\": MethodSpec<\n { readonly verify: Factor; readonly keyId: string },\n NullValue\n >;\n readonly \"keys.export\": MethodSpec<\n { readonly verify: Factor; readonly keyId: string },\n Uint8Array\n >;\n} = {\n \"session.touch\": {\n session: true,\n presence: true,\n params: nullValue,\n result: nullValue,\n },\n \"vault.unlock\": {\n session: false,\n presence: true,\n params: obj({ factor }),\n result: obj({ session: sessionId }),\n },\n \"vault.reset\": { session: false, presence: false, params: nullValue, result: nullValue },\n \"vault.addFactor\": {\n session: true,\n presence: true,\n params: obj({ verify: factor, factor }),\n result: factorInfo,\n },\n \"vault.removeFactor\": {\n session: true,\n presence: true,\n params: obj({ verify: factor, id: sessionId }),\n result: nullValue,\n },\n \"wallet.createWithPasskey\": {\n session: false,\n presence: true,\n params: createWithPasskeyParams,\n result: createdResult,\n },\n \"wallet.restoreWithPasskey\": {\n session: false,\n presence: true,\n params: restoreWithPasskeyParams,\n result: createdResult,\n },\n \"wallet.createMnemonic\": {\n session: false,\n presence: true,\n params: obj({ words: union(literal(12), literal(24)), factor: opt(factor) }),\n result: obj({\n draft: draftId,\n words: bytes(16, 1024),\n quiz: arr(int(0, 23), 3, 3),\n }),\n },\n \"wallet.confirmMnemonic\": {\n session: false,\n presence: true,\n params: obj({\n draft: draftId,\n answers: arr(bytes(1, 64), 3, 3),\n passphrase: opt(passphraseBytes),\n }),\n result: createdResult,\n },\n \"wallet.discardMnemonic\": {\n session: false,\n presence: false,\n params: obj({ draft: draftId }),\n result: nullValue,\n },\n \"backup.enable\": {\n session: true,\n presence: true,\n params: obj({ verify: factor, factors: arr(backupFactor, 5, 1) }),\n result: nullValue,\n },\n \"backup.update\": {\n session: true,\n presence: false,\n params: nullValue,\n result: obj({ envelope: str(4_000_000) }),\n },\n \"backup.disable\": {\n session: true,\n presence: true,\n params: nullValue,\n result: nullValue,\n },\n \"backup.restore\": {\n session: false,\n presence: true,\n params: obj({\n envelope: str(4_000_000),\n backupFactor: backupUnlockFactor,\n passphrases: opt(arr(obj({ walletId, passphrase: passphraseBytes }), 1000)),\n factor: opt(factor),\n }),\n result: obj({\n wallets: arr(walletInfo, 1000),\n passphraseRequired: arr(str(128), 1000),\n session: sessionId,\n }),\n },\n \"wallet.importMnemonic\": {\n session: false,\n presence: true,\n params: obj({\n mnemonic: bytes(1, 1024),\n passphrase: opt(passphraseBytes),\n factor: opt(factor),\n }),\n result: createdResult,\n },\n \"wallet.exportMnemonic\": {\n session: true,\n presence: true,\n params: obj({ verify: factor, walletId }),\n result: obj({ mnemonic: bytes(16, 1024), passphrase: opt(passphraseBytes) }),\n },\n \"wallet.delete\": {\n session: true,\n presence: true,\n params: obj({ verify: factor, walletId }),\n result: nullValue,\n },\n \"dataKeys.get\": {\n session: true,\n presence: false,\n params: obj({ purpose: str(32, /^[a-z0-9-]{1,32}$/) }),\n result: bytes(32),\n },\n \"keys.import\": {\n session: true,\n presence: true,\n params: obj({ family: keyFamily, secret: bytes(32, 64) }),\n result: keyInfo,\n },\n \"keys.list\": {\n session: true,\n presence: true,\n params: nullValue,\n result: arr(keyInfo, 256),\n },\n \"keys.remove\": {\n session: true,\n presence: true,\n params: obj({ verify: factor, keyId }),\n result: nullValue,\n },\n \"keys.export\": {\n session: true,\n presence: true,\n params: obj({ verify: factor, keyId }),\n result: bytes(1, 256),\n },\n};\n"],"mappings":";;;;;;AAMA,IAAa,kBAAb,cAAqC,MAAM;CACzC,OAAgB;AAClB;AAIA,SAAS,OAAc;CACrB,MAAM,IAAI,gBAAgB;AAC5B;AAKA,SAAgB,QACd,UACc;CACd,QAAQ,UAAU;EAChB,IAAI,UAAU,UACZ,KAAK;EAEP,OAAO;CACT;AACF;AAEA,MAAa,YAAkC,QAAQ,IAAI;AAC3D,MAAa,QAA4B,UAAU;CACjD,IAAI,OAAO,UAAU,WACnB,KAAK;CAEP,OAAO;AACT;AAEA,SAAgB,IAAI,KAAa,KAAgC;CAC/D,QAAQ,UAAU;EAChB,IAAI,OAAO,UAAU,YAAY,CAAC,OAAO,cAAc,KAAK,KAAK,QAAQ,OAAO,QAAQ,KACtF,KAAK;EAEP,OAAO;CACT;AACF;AAEA,SAAgB,IAAI,KAAa,SAAqC;CACpE,QAAQ,UAAU;EAChB,IACE,OAAO,UAAU,YACjB,MAAM,SAAS,OACd,YAAY,KAAA,KAAa,CAAC,QAAQ,KAAK,KAAK,GAE7C,KAAK;EAEP,OAAO;CACT;AACF;AAEA,SAAgB,MAAM,KAAa,KAAqC;CACtE,MAAM,OAAO,OAAO;CACpB,QAAQ,UAAU;EAChB,IAAI,EAAE,iBAAiB,eAAe,MAAM,SAAS,OAAO,MAAM,SAAS,MACzE,KAAK;EAEP,OAAO;CACT;AACF;AAEA,SAAgB,IAAO,MAAoB,KAAa,MAAM,GAAgC;CAC5F,QAAQ,UAAU;EAChB,IAAI,CAAC,MAAM,QAAQ,KAAK,KAAK,MAAM,SAAS,OAAO,MAAM,SAAS,KAChE,KAAK;EAEP,MAAM,MAAW,CAAC;EAClB,KAAK,MAAM,WAAW,OACpB,IAAI,KAAK,KAAK,OAA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b,SAAS;EACT,UAAU;EACV,QAAQ,IAAI;GAAE,QAAQ;GAAQ;EAAM,CAAC;EACrC,QAAQ;CACV;CACA,eAAe;EACb,SAAS;EACT,UAAU;EACV,QAAQ,IAAI;GAAE,QAAQ;GAAQ;EAAM,CAAC;EACrC,QAAQ,MAAM,GAAG,GAAG;CACtB;AACF"}
|
package/dist/host.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { et as SignedEvent, l as ProtocolValue } from "./index-
|
|
1
|
+
import { g as PasskeyConfig, x as Wallet } from "./types-cAQAJBLi.mjs";
|
|
2
|
+
import { et as SignedEvent, l as ProtocolValue } from "./index-CEhrd0Pl.mjs";
|
|
3
3
|
/**
|
|
4
4
|
* Why the kernel port ended: a fault in the enclave/transport, or a deliberate host-side lock
|
|
5
5
|
* triggered by the platform (native background expiry — W7).
|
package/dist/host.mjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { WalletError } from "./types.mjs";
|
|
2
|
-
import { t as Channel } from "./channel-
|
|
2
|
+
import { t as Channel } from "./channel-BLwce5hh.mjs";
|
|
3
3
|
import { n as registerInternals } from "./internal-CAKfHjIg.mjs";
|
|
4
4
|
import { a as passkeyName, c as resolveBackupUnlockFactor, d as vaultSaltBytes, f as walletSaltBytes, h as wireSecretText, i as defaultUnlockFactor, l as resolveFactor, m as wirePassphrase, n as PASSKEY_PURPOSE_VAULT, o as requireCeremony, p as wireBytes, r as PASSKEY_PURPOSE_WALLET, s as resolveBackupFactor, t as SingleUseSecret, u as resolveInitialFactor } from "./secret-CcjyF8D3.mjs";
|
|
5
|
+
import { base58, hex } from "@scure/base";
|
|
5
6
|
// src/wallet.ts
|
|
6
7
|
/**
|
|
7
8
|
* The host-facing `Wallet` (design/entry.mdx "API"): snapshot state, the core API groups, and the
|
|
@@ -50,6 +51,7 @@ var KernelWallet = class KernelWallet {
|
|
|
50
51
|
factors: [],
|
|
51
52
|
wallets: [],
|
|
52
53
|
nostr: { keys: [] },
|
|
54
|
+
importedKeys: [],
|
|
53
55
|
backup: null
|
|
54
56
|
};
|
|
55
57
|
this.channel = new Channel(options.spawn, {
|
|
@@ -147,10 +149,11 @@ var KernelWallet = class KernelWallet {
|
|
|
147
149
|
factors: status === void 0 ? [] : status.factors,
|
|
148
150
|
wallets: status === void 0 ? [] : status.wallets,
|
|
149
151
|
nostr: { keys: status === void 0 ? [] : status.nostr.keys },
|
|
152
|
+
importedKeys: status === void 0 ? [] : status.importedKeys,
|
|
150
153
|
backup: status === void 0 ? null : status.backup
|
|
151
154
|
};
|
|
152
155
|
const current = this.snapshotValue;
|
|
153
|
-
if (current.vault === next.vault && current.lockReason === next.lockReason && current.verifying === next.verifying && deepEqual(current.factors, next.factors) && deepEqual(current.wallets, next.wallets) && deepEqual(current.nostr, next.nostr) && deepEqual(current.backup, next.backup)) return;
|
|
156
|
+
if (current.vault === next.vault && current.lockReason === next.lockReason && current.verifying === next.verifying && deepEqual(current.factors, next.factors) && deepEqual(current.wallets, next.wallets) && deepEqual(current.nostr, next.nostr) && deepEqual(current.importedKeys, next.importedKeys) && deepEqual(current.backup, next.backup)) return;
|
|
154
157
|
this.snapshotValue = next;
|
|
155
158
|
for (const listener of this.listeners) listener();
|
|
156
159
|
}
|
|
@@ -228,6 +231,37 @@ var KernelWallet = class KernelWallet {
|
|
|
228
231
|
await this.channel.call("vault.reset", null);
|
|
229
232
|
}
|
|
230
233
|
};
|
|
234
|
+
keys = {
|
|
235
|
+
import: async (family, secret) => this.withVerifying(async () => {
|
|
236
|
+
const transfer = [];
|
|
237
|
+
const decoded = decodeKeySecret(family, secret);
|
|
238
|
+
try {
|
|
239
|
+
return await this.channel.call("keys.import", {
|
|
240
|
+
family,
|
|
241
|
+
secret: wireBytes(decoded, transfer)
|
|
242
|
+
}, transfer);
|
|
243
|
+
} finally {
|
|
244
|
+
if (decoded !== secret) decoded.fill(0);
|
|
245
|
+
}
|
|
246
|
+
}),
|
|
247
|
+
list: async () => this.channel.call("keys.list", null, []),
|
|
248
|
+
remove: async (keyId, verify) => this.withVerifying(async () => {
|
|
249
|
+
const transfer = [];
|
|
250
|
+
const wireVerify = await resolveFactor(this.factorSource, verify, transfer);
|
|
251
|
+
await this.channel.call("keys.remove", {
|
|
252
|
+
verify: wireVerify,
|
|
253
|
+
keyId
|
|
254
|
+
}, transfer);
|
|
255
|
+
}),
|
|
256
|
+
export: async (keyId, verify) => this.withVerifying(async () => {
|
|
257
|
+
const transfer = [];
|
|
258
|
+
const wireVerify = await resolveFactor(this.factorSource, verify, transfer);
|
|
259
|
+
return this.channel.call("keys.export", {
|
|
260
|
+
verify: wireVerify,
|
|
261
|
+
keyId
|
|
262
|
+
}, transfer);
|
|
263
|
+
})
|
|
264
|
+
};
|
|
231
265
|
wallets = {
|
|
232
266
|
createWithPasskey: async (options) => this.withVerifying(async () => {
|
|
233
267
|
const name = passkeyName(options.name);
|
|
@@ -399,6 +433,23 @@ var KernelWallet = class KernelWallet {
|
|
|
399
433
|
}
|
|
400
434
|
};
|
|
401
435
|
/**
|
|
436
|
+
* `keys.import`'s `secret` in bytes: a string is the family's canonical text encoding — `0x` hex
|
|
437
|
+
* for EVM, base58 for Solana — while a Uint8Array passes straight through to the kernel's checks.
|
|
438
|
+
*/
|
|
439
|
+
function decodeKeySecret(family, secret) {
|
|
440
|
+
if (secret instanceof Uint8Array) return secret;
|
|
441
|
+
if (family === "evm") {
|
|
442
|
+
if (!/^0x[0-9a-fA-F]{64}$/.test(secret)) throw new WalletError("invalid-input", "an EVM private key is 0x-prefixed 64-hex");
|
|
443
|
+
return hex.decode(secret.slice(2));
|
|
444
|
+
}
|
|
445
|
+
if (family === "solana") try {
|
|
446
|
+
return base58.decode(secret);
|
|
447
|
+
} catch {
|
|
448
|
+
throw new WalletError("invalid-input", "a Solana private key is base58");
|
|
449
|
+
}
|
|
450
|
+
throw new WalletError("invalid-input", `keys are not supported on ${family}`);
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
402
453
|
* Validates the passkey configuration: the RP identity and both PRF salts are permanent
|
|
403
454
|
* identifiers, so an empty or colliding value is rejected here rather than producing unrecoverable
|
|
404
455
|
* credentials later.
|