@qntx/wallet 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +2 -0
  2. package/dist/chains-BdcH4YnJ.d.mts +333 -0
  3. package/dist/chains.d.mts +2 -4
  4. package/dist/chains.mjs +3 -4
  5. package/dist/{channel-ChYtMklb.mjs → channel-Iiz28m-e.mjs} +6 -7
  6. package/dist/{channel-ChYtMklb.mjs.map → channel-Iiz28m-e.mjs.map} +1 -1
  7. package/dist/{core-Dmz5SbyJ.mjs → core-Cq5h9X0X.mjs} +11 -6
  8. package/dist/core-Cq5h9X0X.mjs.map +1 -0
  9. package/dist/host.d.mts +3 -8
  10. package/dist/host.mjs +19 -23
  11. package/dist/host.mjs.map +1 -1
  12. package/dist/{chains-D_jfwTPT.d.mts → index-BXnQtz55.d.mts} +42 -402
  13. package/dist/index.d.mts +14 -6
  14. package/dist/index.mjs +3 -6
  15. package/dist/index.mjs.map +1 -1
  16. package/dist/{internal-LBHal13j.mjs → internal-CAKfHjIg.mjs} +2 -3
  17. package/dist/internal-CAKfHjIg.mjs.map +1 -0
  18. package/dist/nostr.d.mts +19 -22
  19. package/dist/nostr.mjs +61 -53
  20. package/dist/nostr.mjs.map +1 -1
  21. package/dist/{protocol-DvzlUKB8.mjs → protocol-DbpLncEB.mjs} +81 -117
  22. package/dist/protocol-DbpLncEB.mjs.map +1 -0
  23. package/dist/protocol.d.mts +4 -3
  24. package/dist/protocol.mjs +2 -2
  25. package/dist/{secret-BiyX0Hus.mjs → secret-Dz_ItVt6.mjs} +3 -5
  26. package/dist/{secret-BiyX0Hus.mjs.map → secret-Dz_ItVt6.mjs.map} +1 -1
  27. package/dist/spark.d.mts +2 -6
  28. package/dist/spark.mjs +4 -7
  29. package/dist/spark.mjs.map +1 -1
  30. package/dist/{types-BD9fuAUj.d.mts → types-CIYT5uFj.d.mts} +6 -24
  31. package/dist/types.d.mts +2 -2
  32. package/dist/types.mjs +1 -2
  33. package/dist/types.mjs.map +1 -1
  34. package/package.json +7 -7
  35. package/dist/core-Dmz5SbyJ.mjs.map +0 -1
  36. package/dist/internal-LBHal13j.mjs.map +0 -1
  37. package/dist/protocol-DvzlUKB8.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol-DbpLncEB.mjs","names":[],"sources":["../src/protocol/backup.ts","../src/protocol/chains.ts","../src/protocol/nostr.ts","../src/protocol/spark.ts","../src/protocol/index.ts"],"sourcesContent":["/**\n * Backup-envelope wire validators (design/backup.mdx): the strict structural shape the kernel and\n * the host-side `parseBackupHeader` share — version 1, bounded fields, `obj` rejects unknown keys.\n * Cryptographic checks (the payload tag, factor unwrap) stay in the kernel; these rules only shape\n * the JSON.\n */\nimport { safeTime } from \"./core.ts\";\nimport type { Validator } from \"./validate.ts\";\nimport { arr, int, literal, obj, str, union } from \"./validate.ts\";\n\nconst MAX_FACTOR_CHARS = 512;\nconst MAX_STRING_BYTES = 64_000;\nconst MAX_PAYLOAD_CHARS = 1_400_000; // ~1 MiB of sealed bytes in base64url\nconst MAX_ENVELOPE_CHARS = 4_000_000;\n\nexport type BackupEnvelopeFactor =\n | { readonly kind: \"passkey\"; readonly credentialId: string; readonly sealedBek: string }\n | {\n readonly kind: \"password\";\n readonly iterations: 600_000;\n readonly salt: string;\n readonly sealedBek: string;\n };\n\nexport type BackupEnvelopeWire = {\n readonly version: 1;\n readonly createdAt: number;\n /** Raw JSON text — authenticated by the payload tag before it is parsed. */\n readonly header: string;\n readonly factors: ReadonlyArray<BackupEnvelopeFactor>;\n readonly payload: string;\n};\n\n/** One public factor entry — shared by the envelope and the retained `backup-key` header. */\nexport const backupEnvelopeFactor: Validator<BackupEnvelopeFactor> = union(\n obj({\n kind: literal(\"passkey\"),\n credentialId: str(MAX_FACTOR_CHARS),\n sealedBek: str(MAX_FACTOR_CHARS),\n }),\n obj({\n kind: literal(\"password\"),\n iterations: literal(600_000),\n salt: str(128),\n sealedBek: str(MAX_FACTOR_CHARS),\n }),\n);\n\nexport const backupEnvelope: Validator<BackupEnvelopeWire> = obj({\n version: literal(1),\n createdAt: int(0, Number.MAX_SAFE_INTEGER),\n header: str(MAX_STRING_BYTES),\n factors: arr(backupEnvelopeFactor, 5, 1),\n payload: str(MAX_PAYLOAD_CHARS),\n});\n\nexport type BackupHeaderWallet = {\n readonly walletId: string;\n readonly origin: \"mnemonic\" | \"passkey\";\n readonly words: 12 | 15 | 18 | 21 | 24;\n};\n\nexport type BackupHeaderWire = {\n readonly wallets: ReadonlyArray<BackupHeaderWallet>;\n};\n\nexport const backupHeader: Validator<BackupHeaderWire> = obj({\n wallets: arr(\n obj({\n walletId: str(128),\n origin: union(literal(\"mnemonic\"), literal(\"passkey\")),\n words: union(literal(12), literal(15), literal(18), literal(21), literal(24)),\n }),\n 1000,\n ),\n});\n\n/** The whole-envelope text bound — `backup.update` results and `backup.restore` params use it. */\nexport const backupEnvelopeText: Validator<string> = str(MAX_ENVELOPE_CHARS);\n\n/** The status/snapshot summary of a retained backup key — public data only. */\nexport type BackupInfo = {\n readonly id: string; // 32 lowercase hex, HKDF over the BEK\n readonly factors: ReadonlyArray<\"passkey\" | \"password\">;\n readonly createdAt: number;\n};\n\nexport const backupInfo: Validator<BackupInfo> = obj({\n id: str(32, /^[0-9a-f]{32}$/),\n factors: arr(union(literal(\"passkey\"), literal(\"password\")), 5, 1),\n createdAt: safeTime,\n});\n","/**\n * The chains module's method table and wire validators. `wallet.accounts` derives the public\n * account for a template at the wallet's group index — the EVM/Solana arm returns the address; the\n * Bitcoin arm returns the account-level extended public key plus the master fingerprint and account\n * path (both needed to build the PSBT `bip32Derivation` entries later). The protocol is free of\n *\n * @qntx/wallet-chains imports; template names and path shapes are declared here.\n */\nimport type { Factor, MethodSpec } from \"./core.ts\";\nimport { factor, groupIndex, walletId } from \"./core.ts\";\nimport type { Validator } from \"./validate.ts\";\nimport { arr, bytes, int, literal, obj, opt, str, union } from \"./validate.ts\";\n\nexport type ChainTemplate =\n | \"evm.bip44\"\n | \"solana.bip44-change\"\n | \"btc.bip44\"\n | \"btc.bip49\"\n | \"btc.bip84\"\n | \"btc.bip86\";\n\nexport type ChainAccountsParams = {\n readonly walletId: string;\n readonly groupIndex: number;\n readonly template: ChainTemplate;\n readonly network: string;\n};\n\nexport type ChainAccount =\n | {\n readonly template: \"evm.bip44\";\n readonly network: string;\n readonly address: string;\n }\n | {\n readonly template: \"solana.bip44-change\";\n readonly network: string;\n readonly address: string;\n }\n | {\n readonly template: \"btc.bip44\" | \"btc.bip49\" | \"btc.bip84\" | \"btc.bip86\";\n readonly network: string;\n readonly xpub: string;\n /** Master-key fingerprint as 8 lowercase hex chars (PSBT bip32Derivation). */\n readonly fingerprint: string;\n /** Account derivation path, e.g. \"m/84'/0'/0'\". */\n readonly path: string;\n };\n\nconst template: Validator<ChainTemplate> = union(\n literal(\"evm.bip44\"),\n literal(\"solana.bip44-change\"),\n union(literal(\"btc.bip44\"), literal(\"btc.bip49\"), literal(\"btc.bip84\")),\n literal(\"btc.bip86\"),\n);\n\nconst caip2: Validator<string> = str(200, /^[a-z0-9-]{3,64}:[0-9a-zA-Z-]{1,128}$/);\nconst addressResult = (t: \"evm.bip44\" | \"solana.bip44-change\"): Validator<ChainAccount> =>\n obj({\n template: literal(t),\n network: caip2,\n address: str(128, /^[0-9a-zA-Z-]{20,128}$/),\n });\n\nexport type AccountRef =\n | {\n readonly kind: \"hd\";\n readonly walletId: string;\n readonly groupIndex: number;\n readonly template: ChainTemplate;\n }\n | {\n readonly kind: \"imported\";\n readonly keyId: string;\n readonly family: \"evm\" | \"solana\" | \"bitcoin\";\n };\n\nexport type EvmAccessListEntryWire = {\n readonly address: string;\n readonly storageKeys: ReadonlyArray<string>;\n};\n\ntype EvmTransactionBase = {\n readonly chainId: number;\n readonly nonce: number;\n readonly gas: string;\n readonly value: string;\n readonly data: string;\n readonly to?: string;\n};\n\nexport type EvmTransactionWire =\n | (EvmTransactionBase & { readonly type: \"legacy\"; readonly gasPrice: string })\n | (EvmTransactionBase & {\n readonly type: \"eip2930\";\n readonly gasPrice: string;\n readonly accessList: ReadonlyArray<EvmAccessListEntryWire>;\n })\n | (EvmTransactionBase & {\n readonly type: \"eip1559\";\n readonly maxFeePerGas: string;\n readonly maxPriorityFeePerGas: string;\n readonly accessList: ReadonlyArray<EvmAccessListEntryWire>;\n });\n\n/** `chain.sign`'s request — the wire mirror of @qntx/wallet-chains `SignRequest`. */\nexport type ChainSignRequest =\n | {\n readonly kind: \"evm.transaction\";\n readonly network: string;\n readonly account: AccountRef;\n readonly tx: EvmTransactionWire;\n }\n | {\n readonly kind: \"evm.personal-message\";\n readonly network: string;\n readonly account: AccountRef;\n readonly message: Uint8Array;\n }\n | {\n readonly kind: \"evm.typed-data\";\n readonly network: string;\n readonly account: AccountRef;\n readonly typedData: string;\n }\n | {\n readonly kind: \"solana.transaction\";\n readonly network: string;\n readonly account: AccountRef;\n readonly message: Uint8Array;\n readonly lookupTables?: ReadonlyArray<{\n readonly address: string;\n readonly addresses: ReadonlyArray<string>;\n }>;\n }\n | {\n readonly kind: \"solana.message\";\n readonly network: string;\n readonly account: AccountRef;\n readonly message: Uint8Array;\n readonly format: \"raw\";\n }\n | {\n readonly kind: \"bitcoin.psbt\";\n readonly network: string;\n readonly account: AccountRef;\n readonly psbt: Uint8Array;\n readonly sign: ReadonlyArray<number>;\n }\n | {\n readonly kind: \"bitcoin.message\";\n readonly network: string;\n readonly account: AccountRef;\n readonly address: string;\n readonly message: string;\n readonly format: \"bip322-simple\" | \"legacy\";\n readonly change: 0 | 1;\n readonly index: number;\n };\n\nexport type ChainSignResult =\n | { readonly kind: \"evm.transaction\"; readonly signedTransaction: Uint8Array }\n | { readonly kind: \"evm.personal-message\" | \"evm.typed-data\"; readonly signature: Uint8Array }\n | { readonly kind: \"solana.transaction\" | \"solana.message\"; readonly signature: Uint8Array }\n | { readonly kind: \"bitcoin.psbt\"; readonly signedPsbt: Uint8Array }\n | { readonly kind: \"bitcoin.message\"; readonly signature: string };\n\nexport type ChainSignParams = { readonly request: ChainSignRequest; readonly verify: Factor };\n\nconst accountRef: Validator<AccountRef> = union(\n obj({ kind: literal(\"hd\"), walletId, groupIndex, template }),\n obj({\n kind: literal(\"imported\"),\n keyId: str(64, /^[0-9a-f]{8,64}$/),\n family: union(literal(\"evm\"), literal(\"solana\"), literal(\"bitcoin\")),\n }),\n);\n\nconst hexQuantity = str(66, /^0x[0-9a-fA-F]+$/);\nconst hexData = str(40000, /^0x[0-9a-fA-F]*$/);\nconst evmAddress = str(42, /^0x[0-9a-fA-F]{40}$/);\nconst solanaAddress = str(44, /^[1-9A-HJ-NP-Za-km-z]{32,44}$/);\nconst bitcoinAddress = str(90, /^(bc1|tb1|bcrt1|[13mn2])[a-zA-Z0-9]{4,87}$/);\nconst safeInt = int(0, 9007199254740991);\nconst accessList = arr(\n obj({ address: evmAddress, storageKeys: arr(str(66, /^0x[0-9a-fA-F]{64}$/), 256) }),\n 256,\n);\nconst txBase = {\n chainId: safeInt,\n nonce: safeInt,\n gas: hexQuantity,\n value: hexQuantity,\n data: hexData,\n to: opt(evmAddress),\n};\nconst evmTx: Validator<EvmTransactionWire> = union(\n obj({ ...txBase, type: literal(\"legacy\"), gasPrice: hexQuantity }),\n obj({ ...txBase, type: literal(\"eip2930\"), gasPrice: hexQuantity, accessList }),\n obj({\n ...txBase,\n type: literal(\"eip1559\"),\n maxFeePerGas: hexQuantity,\n maxPriorityFeePerGas: hexQuantity,\n accessList,\n }),\n);\n\nconst signRequest: Validator<ChainSignRequest> = union(\n obj({ kind: literal(\"evm.transaction\"), network: caip2, account: accountRef, tx: evmTx }),\n obj({\n kind: literal(\"evm.personal-message\"),\n network: caip2,\n account: accountRef,\n message: bytes(0, 65536),\n }),\n obj({\n kind: literal(\"evm.typed-data\"),\n network: caip2,\n account: accountRef,\n typedData: str(1048576),\n }),\n obj({\n kind: literal(\"solana.transaction\"),\n network: caip2,\n account: accountRef,\n message: bytes(1, 1232),\n lookupTables: opt(arr(obj({ address: solanaAddress, addresses: arr(solanaAddress, 256) }), 64)),\n }),\n obj({\n kind: literal(\"solana.message\"),\n network: caip2,\n account: accountRef,\n message: bytes(1, 65536),\n format: literal(\"raw\"),\n }),\n obj({\n kind: literal(\"bitcoin.psbt\"),\n network: caip2,\n account: accountRef,\n psbt: bytes(1, 131072),\n sign: arr(int(0, 1024), 1024),\n }),\n obj({\n kind: literal(\"bitcoin.message\"),\n network: caip2,\n account: accountRef,\n address: bitcoinAddress,\n message: str(1048576),\n format: union(literal(\"bip322-simple\"), literal(\"legacy\")),\n change: union(literal(0), literal(1)),\n index: int(0, 2147483647),\n }),\n);\n\nconst signResult: Validator<ChainSignResult> = union(\n obj({ kind: literal(\"evm.transaction\"), signedTransaction: bytes(1, 65536) }),\n obj({\n kind: union(literal(\"evm.personal-message\"), literal(\"evm.typed-data\")),\n signature: bytes(65, 65),\n }),\n obj({\n kind: union(literal(\"solana.transaction\"), literal(\"solana.message\")),\n signature: bytes(64, 64),\n }),\n obj({ kind: literal(\"bitcoin.psbt\"), signedPsbt: bytes(1, 131072) }),\n obj({ kind: literal(\"bitcoin.message\"), signature: str(512) }),\n);\n\nexport const CHAINS_METHODS: {\n readonly \"wallet.accounts\": MethodSpec<ChainAccountsParams, ChainAccount>;\n readonly \"chain.sign\": MethodSpec<ChainSignParams, ChainSignResult>;\n} = {\n \"wallet.accounts\": {\n session: true,\n presence: false,\n params: obj({ walletId, groupIndex, template, network: caip2 }),\n result: union(\n addressResult(\"evm.bip44\"),\n addressResult(\"solana.bip44-change\"),\n obj({\n template: union(\n literal(\"btc.bip44\"),\n literal(\"btc.bip49\"),\n literal(\"btc.bip84\"),\n literal(\"btc.bip86\"),\n ),\n network: caip2,\n xpub: str(111, /^[a-zA-Z0-9]{111}$/),\n fingerprint: str(8, /^[0-9a-f]{8}$/),\n path: str(11, /^m\\/[0-9'/]+$/),\n }),\n ),\n },\n \"chain.sign\": {\n session: true,\n presence: true,\n params: obj({ request: signRequest, verify: factor }),\n result: signResult,\n },\n};\n","/**\n * The nostr module's method table and wire validators. The protocol stays free of @qntx/nostr\n * imports — even types — so the event shapes it validates are declared here structurally; a\n * type-level test in packages/wallet/tests pins them assignable to and from @qntx/nostr's\n * Event/UnsignedEvent/Rumor.\n */\nimport type { DerivedNostrKey, NostrKeyInfo, WalletErrorCode } from \"../types.ts\";\nimport {\n factor,\n identityIndex,\n MAX_BATCH,\n MAX_SNAPSHOT_ITEMS,\n MAX_TAG_ITEM,\n MAX_TAG_ITEMS,\n MAX_TAGS,\n MAX_TEXT,\n publicKey,\n safeTime,\n walletErrorCode,\n walletId,\n} from \"./core.ts\";\nimport type { Factor, MethodSpec } from \"./core.ts\";\nimport type { NullValue, Validator } from \"./validate.ts\";\nimport { arr, bytes, int, literal, nullValue, obj, opt, str, union } from \"./validate.ts\";\n\n/**\n * The unsigned event input the kernel signs. `pubkey` is optional: callers may omit it and the\n * kernel fills the signing key's own. Structurally compatible with @qntx/nostr's UnsignedEvent.\n */\nexport type UnsignedEventInput = {\n readonly kind: number;\n readonly created_at: number;\n readonly tags: ReadonlyArray<ReadonlyArray<string>>;\n readonly content: string;\n readonly pubkey?: string;\n};\n\n/** The signed event the kernel returns — the Nostr event minus `id`-less forms. */\nexport type SignedEvent = {\n readonly id: string;\n readonly pubkey: string;\n readonly sig: string;\n readonly kind: number;\n readonly created_at: number;\n readonly tags: ReadonlyArray<ReadonlyArray<string>>;\n readonly content: string;\n};\n\n/** A NIP-59 rumor: an unsigned event carrying a computed `id` but no `sig`. */\nexport type Rumor = {\n readonly id: string;\n readonly pubkey: string;\n readonly kind: number;\n readonly created_at: number;\n readonly tags: ReadonlyArray<ReadonlyArray<string>>;\n readonly content: string;\n};\n\nexport type NostrExportFormat =\n | { readonly kind: \"nsec\" }\n | { readonly kind: \"ncryptsec\"; readonly password: Uint8Array };\n\nexport type UnwrapResult = { readonly ok: Rumor } | { readonly err: WalletErrorCode };\n\nconst hex128: Validator<string> = str(128, /^[0-9a-f]{128}$/);\n\nconst nostrKeyRef = obj({ kind: literal(\"derived\"), walletId, index: identityIndex });\n\nexport const nostrKeyInfo: Validator<NostrKeyInfo> = obj({\n ref: nostrKeyRef,\n publicKey,\n createdAt: safeTime,\n});\n\n/** The nostr section of the status payload, composed by protocol/index.ts. */\nexport const nostrStatus: Validator<{ readonly keys: ReadonlyArray<NostrKeyInfo> }> = obj({\n keys: arr(nostrKeyInfo, MAX_SNAPSHOT_ITEMS),\n});\n\nconst derivedNostrKey: Validator<DerivedNostrKey> = obj({ index: identityIndex, publicKey });\n\nconst tags: Validator<ReadonlyArray<ReadonlyArray<string>>> = arr(\n arr(str(MAX_TAG_ITEM), MAX_TAG_ITEMS),\n MAX_TAGS,\n);\n\nconst signEventInput: Validator<UnsignedEventInput> = obj({\n kind: int(0, 65535),\n created_at: safeTime,\n tags,\n content: str(MAX_TEXT),\n pubkey: opt(publicKey),\n});\n\nconst signedEvent: Validator<SignedEvent> = obj({\n id: publicKey,\n pubkey: publicKey,\n sig: hex128,\n kind: int(0, 65535),\n created_at: safeTime,\n tags,\n content: str(MAX_TEXT),\n});\n\nconst rumor: Validator<Rumor> = obj({\n id: publicKey,\n pubkey: publicKey,\n kind: int(0, 65535),\n created_at: safeTime,\n tags,\n content: str(MAX_TEXT),\n});\n\nconst nostrExportFormat: Validator<NostrExportFormat> = union(\n obj({ kind: literal(\"nsec\") }),\n obj({ kind: literal(\"ncryptsec\"), password: bytes(1, 1024) }),\n);\n\nconst textParams = obj({ publicKey, peer: publicKey, text: str(MAX_TEXT) });\nconst textResult = str(MAX_TEXT * 4);\n\nexport const NOSTR_METHODS: {\n readonly \"nostr.discover\": MethodSpec<\n { readonly walletId: string; readonly from: number; readonly count: number },\n { readonly keys: ReadonlyArray<DerivedNostrKey> }\n >;\n readonly \"nostr.deriveKey\": MethodSpec<\n { readonly walletId: string; readonly index: number },\n NostrKeyInfo\n >;\n readonly \"nostr.removeKey\": MethodSpec<{ readonly publicKey: string }, NullValue>;\n readonly \"nostr.exportKey\": MethodSpec<\n { readonly verify: Factor; readonly publicKey: string; readonly format: NostrExportFormat },\n Uint8Array\n >;\n readonly \"nostr.signEvent\": MethodSpec<\n { readonly publicKey: string; readonly event: UnsignedEventInput },\n SignedEvent\n >;\n readonly \"nostr.nip04Encrypt\": MethodSpec<\n { readonly publicKey: string; readonly peer: string; readonly text: string },\n string\n >;\n readonly \"nostr.nip04Decrypt\": MethodSpec<\n { readonly publicKey: string; readonly peer: string; readonly text: string },\n string\n >;\n readonly \"nostr.nip44Encrypt\": MethodSpec<\n { readonly publicKey: string; readonly peer: string; readonly text: string },\n string\n >;\n readonly \"nostr.nip44Decrypt\": MethodSpec<\n { readonly publicKey: string; readonly peer: string; readonly text: string },\n string\n >;\n readonly \"nostr.syncKey\": MethodSpec<\n { readonly walletId: string },\n { readonly publicKey: string }\n >;\n readonly \"nostr.syncSign\": MethodSpec<\n { readonly walletId: string; readonly event: UnsignedEventInput },\n SignedEvent\n >;\n readonly \"nostr.syncEncrypt\": MethodSpec<\n { readonly walletId: string; readonly text: string },\n string\n >;\n readonly \"nostr.syncDecrypt\": MethodSpec<\n { readonly walletId: string; readonly text: string },\n string\n >;\n readonly \"nostr.unwrapGiftWraps\": MethodSpec<\n { readonly publicKey: string; readonly events: ReadonlyArray<SignedEvent> },\n { readonly results: ReadonlyArray<UnwrapResult> }\n >;\n} = {\n \"nostr.discover\": {\n session: true,\n presence: false,\n params: obj({ walletId, from: identityIndex, count: int(1, 20) }),\n result: obj({ keys: arr(derivedNostrKey, 20) }),\n },\n \"nostr.deriveKey\": {\n session: true,\n presence: false,\n params: obj({ walletId, index: identityIndex }),\n result: nostrKeyInfo,\n },\n \"nostr.removeKey\": {\n session: true,\n presence: true,\n params: obj({ publicKey }),\n result: nullValue,\n },\n \"nostr.exportKey\": {\n session: true,\n presence: true,\n params: obj({ verify: factor, publicKey, format: nostrExportFormat }),\n result: bytes(16, 4096),\n },\n \"nostr.signEvent\": {\n session: true,\n presence: false,\n params: obj({ publicKey, event: signEventInput }),\n result: signedEvent,\n },\n \"nostr.nip04Encrypt\": { session: true, presence: false, params: textParams, result: textResult },\n \"nostr.nip04Decrypt\": { session: true, presence: false, params: textParams, result: textResult },\n \"nostr.nip44Encrypt\": { session: true, presence: false, params: textParams, result: textResult },\n \"nostr.nip44Decrypt\": { session: true, presence: false, params: textParams, result: textResult },\n \"nostr.unwrapGiftWraps\": {\n session: true,\n presence: false,\n params: obj({ publicKey, events: arr(signedEvent, MAX_BATCH) }),\n result: obj({\n results: arr(union(obj({ ok: rumor }), obj({ err: walletErrorCode })), MAX_BATCH),\n }),\n },\n \"nostr.syncKey\": {\n session: true,\n presence: false,\n params: obj({ walletId }),\n result: obj({ publicKey }),\n },\n \"nostr.syncSign\": {\n session: true,\n presence: false,\n params: obj({ walletId, event: signEventInput }),\n result: signedEvent,\n },\n \"nostr.syncEncrypt\": {\n session: true,\n presence: false,\n params: obj({ walletId, text: str(MAX_TEXT) }),\n result: textResult,\n },\n \"nostr.syncDecrypt\": {\n session: true,\n presence: false,\n params: obj({ walletId, text: str(MAX_TEXT * 4) }),\n result: textResult,\n },\n};\n","/**\n * The spark module's method table and wire validators. The protocol stays free of @qntx/spark\n * imports — even types — so the signer shapes it validates are declared here structurally; a\n * type-level test in packages/wallet/tests pins them assignable to and from @qntx/spark/signer's\n * types.\n *\n * Every method carries `account` — walletId/groupIndex/network — and is session-gated but not\n * presence-bearing (signer work must not hold a session open). List params are capped at MAX_BATCH;\n * the leaf lists of prepareTransfer/prepareClaim are capped at the signer's own 256.\n */\nimport { factor, groupIndex, MAX_BATCH, safeTime, walletId } from \"./core.ts\";\nimport type { Factor, MethodSpec } from \"./core.ts\";\nimport type { Validator } from \"./validate.ts\";\nimport {\n arr,\n bytes,\n int,\n literal,\n obj,\n opt,\n record,\n str,\n union,\n ValidationError,\n} from \"./validate.ts\";\n\n/** The Spark network the account's signer runs on — identical to @qntx/spark's SparkNetwork. */\nexport type SparkNetwork = \"mainnet\" | \"regtest\";\n\n/** The wallet+group+network triple every spark.* request addresses a pooled signer by. */\nexport type SparkAccountRef = {\n readonly walletId: string;\n readonly groupIndex: number;\n readonly network: SparkNetwork;\n};\n\nexport type SparkLeafKey =\n | { readonly type: \"leaf\"; readonly leafId: string }\n | { readonly type: \"static-deposit\"; readonly index: number };\n\nexport type SparkKey =\n | SparkLeafKey\n | { readonly type: \"received\"; readonly ciphertext: Uint8Array };\n\nexport type SigningCommitment = {\n readonly hiding: Uint8Array;\n readonly binding: Uint8Array;\n};\n\nexport type OperatorCommitment = {\n readonly identifier: string;\n readonly commitment: SigningCommitment;\n};\n\nexport type SigningTarget = {\n readonly transaction: Uint8Array;\n readonly inputIndex: number;\n readonly prevouts: ReadonlyArray<{\n script: Uint8Array;\n amount: number;\n }>;\n};\n\nexport type FrostSignJob = {\n readonly key: SparkKey;\n readonly target: SigningTarget;\n readonly verifyingKey: Uint8Array;\n readonly commitment: SigningCommitment;\n readonly operatorCommitments: ReadonlyArray<OperatorCommitment>;\n readonly adaptorPublicKey?: Uint8Array;\n /** Connector-refund proof pair — see `FrostSignJob.exit` in @qntx/spark/signer. */\n readonly exit?: {\n readonly connectorTx: Uint8Array;\n readonly exitTx: Uint8Array;\n };\n};\n\nexport type FrostAggregateJob = {\n readonly key: SparkKey;\n readonly target: SigningTarget;\n readonly verifyingKey: Uint8Array;\n readonly commitment: SigningCommitment;\n readonly signatureShare: Uint8Array;\n readonly operators: ReadonlyArray<{\n readonly identifier: string;\n readonly commitment: SigningCommitment;\n readonly signatureShare: Uint8Array;\n readonly publicKey: Uint8Array;\n }>;\n readonly adaptorPublicKey?: Uint8Array;\n};\n\nexport type StaticDepositClaimStatement = {\n readonly kind: \"static-deposit-claim\";\n readonly network: SparkNetwork;\n readonly txid: Uint8Array;\n readonly vout: number;\n readonly creditAmountSats: number;\n readonly sspSignature: Uint8Array;\n};\n\nexport type IdentityStatement =\n | { readonly kind: \"so-challenge\"; readonly challenge: Uint8Array }\n | { readonly kind: \"ssp-challenge\"; readonly protectedChallenge: string }\n | { readonly kind: \"transfer-package\"; readonly transferId: string; readonly package: Uint8Array }\n | { readonly kind: \"claim-package\"; readonly transferId: string; readonly package: Uint8Array }\n | StaticDepositClaimStatement\n | {\n readonly kind: \"static-deposit-refund\";\n readonly network: SparkNetwork;\n readonly txid: Uint8Array;\n readonly vout: number;\n readonly amount: number;\n readonly target: SigningTarget;\n }\n | {\n readonly kind: \"watchtower-recovery\";\n readonly network: SparkNetwork;\n readonly leafId: string;\n readonly target: SigningTarget;\n }\n | { readonly kind: \"spark-invoice\"; readonly invoice: Uint8Array }\n | { readonly kind: \"token-transaction\"; readonly partialTransaction: Uint8Array }\n | {\n readonly kind: \"lightning-address\";\n readonly action: \"register\";\n readonly domain: string;\n readonly username: string;\n readonly description: string;\n readonly timestamp: number;\n }\n | {\n readonly kind: \"lightning-address\";\n readonly action: \"unregister\";\n readonly domain: string;\n readonly username: string;\n readonly timestamp: number;\n };\n\nexport type PrepareTransferRequest = {\n readonly transferId: string;\n readonly leaves: ReadonlyArray<{\n readonly leafId: string;\n readonly key: SparkLeafKey;\n readonly receiverIdentityPublicKey: Uint8Array;\n }>;\n};\n\nexport type PreparedTransferLeaf = {\n readonly leafId: string;\n readonly newPublicKey: Uint8Array;\n readonly secretCipher: Uint8Array;\n readonly signature: Uint8Array;\n};\n\nexport type PreparedTransfer = {\n readonly operatorPackages: Record<string, Uint8Array>;\n readonly leaves: ReadonlyArray<PreparedTransferLeaf>;\n};\n\nexport type PrepareClaimRequest = {\n readonly transferId: string;\n readonly leaves: ReadonlyArray<{\n readonly leafId: string;\n readonly secretCipher: Uint8Array;\n }>;\n};\n\nexport type PreparedClaim = {\n readonly operatorPackages: Record<string, Uint8Array>;\n};\n\nexport type PreparedLightningReceive = {\n readonly paymentHash: Uint8Array;\n readonly operatorPackages: Record<string, Uint8Array>;\n};\n\nexport type HtlcTimeoutSignRequest = {\n readonly transaction: Uint8Array;\n readonly inputIndex: number;\n readonly prevoutAmountSats: number;\n readonly paymentHash: Uint8Array;\n readonly hashLockPublicKey: Uint8Array;\n};\n\nexport type StaticDepositClaimRequest = {\n readonly index: number;\n readonly statement: StaticDepositClaimStatement;\n};\n\nexport type StaticDepositClaimResult = {\n readonly encryptedSecretKey: Uint8Array;\n readonly signature: Uint8Array;\n};\n\n// Field bounds. Where @qntx/spark/signer constrains a value the same rule is mirrored (64-hex\n// identifiers, 32/33/64-byte keys and signatures, 1..MAX_BATCH counts); where it leaves a value\n// unbounded (leafId/transferId are hashed as UTF-8, ciphertexts and protobuf blobs are bytes) the\n// protocol still needs a size — the MAX_REQUEST_BYTES envelope cap makes these generous bounds\n// sufficient rather than security-critical.\nconst MAX_LEAVES = 256;\nconst MAX_OPERATORS = 16;\nconst MAX_PACKAGE_BYTES = 1_048_576;\nconst MAX_TX_BYTES = 1_048_576;\nconst MAX_PREVOUTS = 1024;\nconst MAX_SCRIPT_BYTES = 16_384;\nconst MAX_CIPHERTEXT_BYTES = 4096;\nconst MAX_SATS = 2_100_000_000_000_000; // 21M BTC in sats\n\nconst network: Validator<SparkNetwork> = union(literal(\"mainnet\"), literal(\"regtest\"));\nconst account: Validator<SparkAccountRef> = obj({ walletId, groupIndex, network });\n\nconst identifier: Validator<string> = str(64, /^[0-9a-f]{64}$/);\nconst leafId: Validator<string> = str(64);\nconst transferId: Validator<string> = str(64);\nconst bytes32: Validator<Uint8Array> = bytes(32);\nconst bytes33: Validator<Uint8Array> = bytes(33);\nconst bytes64: Validator<Uint8Array> = bytes(64);\nconst ciphertext: Validator<Uint8Array> = bytes(1, MAX_CIPHERTEXT_BYTES);\nconst sats: Validator<number> = int(0, MAX_SATS);\n\nconst sparkLeafKey: Validator<SparkLeafKey> = union(\n obj({ type: literal(\"leaf\"), leafId }),\n obj({ type: literal(\"static-deposit\"), index: int(0, 0x7fffffff) }),\n);\n\nconst sparkKey: Validator<SparkKey> = union(\n obj({ type: literal(\"leaf\"), leafId }),\n obj({ type: literal(\"static-deposit\"), index: int(0, 0x7fffffff) }),\n obj({ type: literal(\"received\"), ciphertext }),\n);\n\nconst signingCommitment: Validator<SigningCommitment> = obj({\n hiding: bytes33,\n binding: bytes33,\n});\n\nconst operatorCommitment: Validator<OperatorCommitment> = obj({\n identifier,\n commitment: signingCommitment,\n});\n\nconst signingTarget: Validator<SigningTarget> = obj({\n transaction: bytes(1, MAX_TX_BYTES),\n inputIndex: int(0, 0x7fffffff),\n prevouts: arr(obj({ script: bytes(0, MAX_SCRIPT_BYTES), amount: sats }), MAX_PREVOUTS),\n});\n\nconst adaptorPublicKey = opt(union(bytes(0), bytes(33)));\n\nconst frostSignJob: Validator<FrostSignJob> = obj({\n key: sparkKey,\n target: signingTarget,\n verifyingKey: bytes33,\n commitment: signingCommitment,\n operatorCommitments: arr(operatorCommitment, MAX_OPERATORS),\n adaptorPublicKey,\n});\n\nconst frostAggregateJob: Validator<FrostAggregateJob> = obj({\n key: sparkKey,\n target: signingTarget,\n verifyingKey: bytes33,\n commitment: signingCommitment,\n signatureShare: bytes32,\n operators: arr(\n obj({\n identifier,\n commitment: signingCommitment,\n signatureShare: bytes32,\n publicKey: bytes33,\n }),\n MAX_OPERATORS,\n ),\n adaptorPublicKey,\n});\n\nconst staticDepositClaimStatement: Validator<StaticDepositClaimStatement> = obj({\n kind: literal(\"static-deposit-claim\"),\n network,\n txid: bytes32,\n vout: int(0, 0x7fffffff),\n creditAmountSats: sats,\n sspSignature: bytes(1, 1024),\n});\n\nconst identityStatement: Validator<IdentityStatement> = union(\n obj({ kind: literal(\"so-challenge\"), challenge: bytes(1, 4096) }),\n obj({ kind: literal(\"ssp-challenge\"), protectedChallenge: str(8192) }),\n obj({\n kind: literal(\"transfer-package\"),\n transferId,\n package: bytes(1, MAX_PACKAGE_BYTES),\n }),\n obj({\n kind: literal(\"claim-package\"),\n transferId,\n package: bytes(1, MAX_PACKAGE_BYTES),\n }),\n staticDepositClaimStatement,\n obj({\n kind: literal(\"static-deposit-refund\"),\n network,\n txid: bytes32,\n vout: int(0, 0x7fffffff),\n amount: sats,\n target: signingTarget,\n }),\n obj({\n kind: literal(\"watchtower-recovery\"),\n network,\n leafId,\n target: signingTarget,\n }),\n obj({ kind: literal(\"spark-invoice\"), invoice: bytes(1, 65_536) }),\n obj({ kind: literal(\"token-transaction\"), partialTransaction: bytes(1, MAX_PACKAGE_BYTES) }),\n obj({\n kind: literal(\"lightning-address\"),\n action: literal(\"register\"),\n domain: str(253),\n username: str(64, /^[a-z0-9\\-_.+]{1,64}$/u),\n description: str(512),\n timestamp: safeTime,\n }),\n obj({\n kind: literal(\"lightning-address\"),\n action: literal(\"unregister\"),\n domain: str(253),\n username: str(64, /^[a-z0-9\\-_.+]{1,64}$/u),\n timestamp: safeTime,\n }),\n);\n\nconst htlcTimeoutRequest: Validator<HtlcTimeoutSignRequest> = obj({\n transaction: bytes(1, MAX_TX_BYTES),\n inputIndex: int(0, 0x7fffffff),\n prevoutAmountSats: sats,\n paymentHash: bytes32,\n hashLockPublicKey: bytes33,\n});\n\nconst prepareTransferRequest: Validator<PrepareTransferRequest> = obj({\n transferId,\n leaves: arr(\n obj({ leafId, key: sparkLeafKey, receiverIdentityPublicKey: bytes33 }),\n MAX_LEAVES,\n 1,\n ),\n});\n\nconst preparedTransfer: Validator<PreparedTransfer> = obj({\n operatorPackages: record(identifier, bytes(1, MAX_PACKAGE_BYTES), MAX_OPERATORS),\n leaves: arr(\n obj({\n leafId,\n newPublicKey: bytes33,\n secretCipher: ciphertext,\n signature: bytes64,\n }),\n MAX_LEAVES,\n ),\n});\n\nconst prepareClaimRequest: Validator<PrepareClaimRequest> = obj({\n transferId,\n leaves: arr(obj({ leafId, secretCipher: ciphertext }), MAX_LEAVES, 1),\n});\n\nconst preparedClaim: Validator<PreparedClaim> = obj({\n operatorPackages: record(identifier, bytes(1, MAX_PACKAGE_BYTES), MAX_OPERATORS),\n});\n\nconst preparedLightningReceive: Validator<PreparedLightningReceive> = obj({\n paymentHash: bytes32,\n operatorPackages: record(identifier, bytes(1, MAX_PACKAGE_BYTES), MAX_OPERATORS),\n});\n\nconst staticDepositClaimRequest: Validator<StaticDepositClaimRequest> = obj({\n index: int(0, 0x7fffffff),\n statement: staticDepositClaimStatement,\n});\n\nconst staticDepositClaimResult: Validator<StaticDepositClaimResult> = obj({\n encryptedSecretKey: bytes(1, MAX_CIPHERTEXT_BYTES),\n signature: bytes(64, 128),\n});\n\n/**\n * The intent a `spark.approve` registers — kernel-decoded before the host ever displays it. `token`\n * receivers' amounts are canonical decimal strings in the u128 range.\n */\ntype SparkOutflowIntent =\n | {\n readonly kind: \"exit\";\n readonly address: string;\n readonly amountSats: number;\n readonly maxFeeSats: number;\n }\n | {\n readonly kind: \"onchain\";\n readonly address: string;\n readonly maxFeeSats: number;\n }\n | {\n readonly kind: \"token\";\n readonly tokenIdentifier: Uint8Array;\n readonly receivers: ReadonlyArray<{\n readonly ownerPublicKey: Uint8Array;\n readonly amount: string;\n }>;\n };\n\nexport type SparkApproveIntent =\n | {\n readonly kind: \"transfer\";\n readonly receivers: ReadonlyArray<{\n readonly identityPublicKey: Uint8Array;\n readonly amountSats: number;\n }>;\n }\n | {\n readonly kind: \"lightning\";\n readonly invoice: string;\n readonly amountSats?: number;\n readonly maxFeeSats: number;\n }\n | SparkOutflowIntent;\n\n/**\n * What `spark.approve` returns: the kernel's own decode of the intent — receivers and amounts, the\n * invoice's payment hash and amount, or the exit/onchain destination — never host-provided text.\n */\nexport type SparkApprovalSummary =\n | {\n readonly kind: \"transfer\";\n readonly receivers: ReadonlyArray<{\n readonly identityPublicKey: Uint8Array;\n readonly amountSats: number;\n }>;\n }\n | {\n readonly kind: \"lightning\";\n readonly paymentHash: Uint8Array;\n readonly invoiceAmountSats?: number;\n readonly maxFeeSats: number;\n }\n | SparkOutflowIntent;\n\n// sats amounts are bounded by the protocol's safe-integer contract; u128 token amounts\n// travel as canonical decimal strings.\nconst satsAmount = (): Validator<number> => int(0, Number.MAX_SAFE_INTEGER);\nconst U128_MAX = 340282366920938463463374607431768211455n;\n// Canonical decimal u128: \"0\" or no leading zeros, at most 2^128 − 1.\nconst decimalU128: Validator<string> = (value) => {\n if (\n typeof value !== \"string\" ||\n value.length > 39 ||\n !/^(?:0|[1-9][0-9]*)$/.test(value) ||\n BigInt(value) > U128_MAX\n ) {\n throw new ValidationError();\n }\n return value;\n};\nconst outflowIntents = [\n obj({\n kind: literal(\"exit\"),\n address: str(128),\n amountSats: satsAmount(),\n maxFeeSats: satsAmount(),\n }),\n obj({\n kind: literal(\"onchain\"),\n address: str(128),\n maxFeeSats: satsAmount(),\n }),\n obj({\n kind: literal(\"token\"),\n tokenIdentifier: bytes(32),\n receivers: arr(obj({ ownerPublicKey: bytes(33), amount: decimalU128 }), 256, 1),\n }),\n] as const;\n\nconst approveIntent: Validator<SparkApproveIntent> = union(\n obj({\n kind: literal(\"transfer\"),\n receivers: arr(obj({ identityPublicKey: bytes(33), amountSats: satsAmount() }), 256, 1),\n }),\n obj({\n kind: literal(\"lightning\"),\n invoice: str(4096),\n amountSats: opt(satsAmount()),\n maxFeeSats: satsAmount(),\n }),\n ...outflowIntents,\n);\n\nconst approvalSummary: Validator<SparkApprovalSummary> = union(\n obj({\n kind: literal(\"transfer\"),\n receivers: arr(obj({ identityPublicKey: bytes(33), amountSats: satsAmount() }), 256, 1),\n }),\n obj({\n kind: literal(\"lightning\"),\n paymentHash: bytes(32),\n invoiceAmountSats: opt(satsAmount()),\n maxFeeSats: satsAmount(),\n }),\n ...outflowIntents,\n);\n\nexport const SPARK_METHODS: {\n readonly \"spark.identityPublicKey\": MethodSpec<{ readonly account: SparkAccountRef }, Uint8Array>;\n readonly \"spark.publicKeys\": MethodSpec<\n { readonly account: SparkAccountRef; readonly keys: ReadonlyArray<SparkLeafKey> },\n ReadonlyArray<Uint8Array>\n >;\n readonly \"spark.receivedPublicKeys\": MethodSpec<\n { readonly account: SparkAccountRef; readonly ciphertexts: ReadonlyArray<Uint8Array> },\n ReadonlyArray<Uint8Array>\n >;\n readonly \"spark.newCommitments\": MethodSpec<\n { readonly account: SparkAccountRef; readonly count: number },\n ReadonlyArray<SigningCommitment>\n >;\n readonly \"spark.signFrost\": MethodSpec<\n { readonly account: SparkAccountRef; readonly jobs: ReadonlyArray<FrostSignJob> },\n ReadonlyArray<Uint8Array>\n >;\n readonly \"spark.aggregateFrost\": MethodSpec<\n { readonly account: SparkAccountRef; readonly jobs: ReadonlyArray<FrostAggregateJob> },\n ReadonlyArray<Uint8Array>\n >;\n readonly \"spark.signIdentity\": MethodSpec<\n { readonly account: SparkAccountRef; readonly statement: IdentityStatement },\n Uint8Array\n >;\n readonly \"spark.signKeySpend\": MethodSpec<\n {\n readonly account: SparkAccountRef;\n readonly key: SparkKey;\n readonly target: SigningTarget;\n },\n Uint8Array\n >;\n readonly \"spark.signHtlcTimeout\": MethodSpec<\n { readonly account: SparkAccountRef; readonly request: HtlcTimeoutSignRequest },\n Uint8Array\n >;\n readonly \"spark.prepareTransfer\": MethodSpec<\n { readonly account: SparkAccountRef; readonly request: PrepareTransferRequest },\n PreparedTransfer\n >;\n readonly \"spark.prepareClaim\": MethodSpec<\n { readonly account: SparkAccountRef; readonly request: PrepareClaimRequest },\n PreparedClaim\n >;\n readonly \"spark.prepareLightningReceive\": MethodSpec<\n { readonly account: SparkAccountRef },\n PreparedLightningReceive\n >;\n readonly \"spark.claimStaticDeposit\": MethodSpec<\n { readonly account: SparkAccountRef; readonly request: StaticDepositClaimRequest },\n StaticDepositClaimResult\n >;\n readonly \"spark.approve\": MethodSpec<\n {\n readonly account: SparkAccountRef;\n readonly intent: SparkApproveIntent;\n readonly verify: Factor;\n },\n SparkApprovalSummary\n >;\n} = {\n \"spark.identityPublicKey\": {\n session: true,\n presence: false,\n params: obj({ account }),\n result: bytes33,\n },\n \"spark.publicKeys\": {\n session: true,\n presence: false,\n params: obj({ account, keys: arr(sparkLeafKey, MAX_BATCH) }),\n result: arr(bytes33, MAX_BATCH),\n },\n \"spark.receivedPublicKeys\": {\n session: true,\n presence: false,\n params: obj({ account, ciphertexts: arr(ciphertext, MAX_BATCH) }),\n result: arr(bytes33, MAX_BATCH),\n },\n \"spark.newCommitments\": {\n session: true,\n presence: false,\n params: obj({ account, count: int(1, MAX_BATCH) }),\n result: arr(signingCommitment, MAX_BATCH),\n },\n \"spark.signFrost\": {\n session: true,\n presence: false,\n params: obj({ account, jobs: arr(frostSignJob, MAX_BATCH) }),\n result: arr(bytes32, MAX_BATCH),\n },\n \"spark.aggregateFrost\": {\n session: true,\n presence: false,\n params: obj({ account, jobs: arr(frostAggregateJob, MAX_BATCH) }),\n result: arr(bytes64, MAX_BATCH),\n },\n \"spark.signIdentity\": {\n session: true,\n presence: false,\n params: obj({ account, statement: identityStatement }),\n result: bytes(64, 128),\n },\n \"spark.signKeySpend\": {\n session: true,\n presence: false,\n params: obj({ account, key: sparkKey, target: signingTarget }),\n result: bytes64,\n },\n \"spark.signHtlcTimeout\": {\n session: true,\n presence: false,\n params: obj({ account, request: htlcTimeoutRequest }),\n result: bytes64,\n },\n \"spark.prepareTransfer\": {\n session: true,\n presence: false,\n params: obj({ account, request: prepareTransferRequest }),\n result: preparedTransfer,\n },\n \"spark.prepareClaim\": {\n session: true,\n presence: false,\n params: obj({ account, request: prepareClaimRequest }),\n result: preparedClaim,\n },\n \"spark.prepareLightningReceive\": {\n session: true,\n presence: false,\n params: obj({ account }),\n result: preparedLightningReceive,\n },\n \"spark.claimStaticDeposit\": {\n session: true,\n presence: false,\n params: obj({ account, request: staticDepositClaimRequest }),\n result: staticDepositClaimResult,\n },\n \"spark.approve\": {\n session: true,\n presence: true,\n params: obj({ account, intent: approveIntent, verify: factor }),\n result: approvalSummary,\n },\n};\n","/**\n * Secret-area wire protocol (design/impl/wallet-e0.mdx \"协议与传输\"). Shared by the kernel and the main\n * runtime: the kernel validates every request, the host validates every response. Web/Node carry\n * ProtocolValue via structured clone; the RN host encodes the same values as CBOR.\n *\n * This file is the method-table composition point: `METHODS` spreads the core table\n * (protocol/core.ts) and the nostr module's table (protocol/nostr.ts), and the status result\n * validator composes the core sections with each module's status section.\n */\nimport type { LockReason, StatusPayload, WalletErrorCode } from \"../types.ts\";\nimport { backupInfo } from \"./backup.ts\";\nimport { CHAINS_METHODS } from \"./chains.ts\";\nimport {\n CORE_METHODS,\n factorInfo,\n MAX_SNAPSHOT_ITEMS,\n safeTime,\n walletErrorCode,\n walletInfo,\n} from \"./core.ts\";\nimport type { MethodSpec } from \"./core.ts\";\n// oxlint-disable-next-line unicorn/prefer-export-from -- the table is composed locally AND re-exported\nimport { NOSTR_METHODS, nostrStatus } from \"./nostr.ts\";\n// oxlint-disable-next-line unicorn/prefer-export-from -- the table is composed locally AND re-exported\nimport { SPARK_METHODS } from \"./spark.ts\";\nimport { arr, literal, nullValue, obj, opt, union } from \"./validate.ts\";\nimport type { NullValue, Validator } from \"./validate.ts\";\n\nexport type { WalletErrorCode } from \"../types.ts\";\n\nexport const PROTOCOL_VERSION = 2;\n\n/**\n * Responses to requests whose `id` cannot be parsed (malformed envelope) carry id 0. Main-side\n * request ids start at 1, so a `0` is never a real pending request.\n */\nexport const UNATTRIBUTED_ID = 0;\n\nexport type { NullValue } from \"./validate.ts\";\n\nexport type ProtocolValue =\n | NullValue\n | boolean\n | number // safe integer\n | string\n | Uint8Array\n | ReadonlyArray<ProtocolValue>\n | { readonly [key: string]: ProtocolValue };\n\nexport type Request = {\n readonly v: typeof PROTOCOL_VERSION;\n readonly id: number;\n readonly method: string;\n readonly session?: string;\n readonly params: ProtocolValue;\n};\n\nexport type ErrorPayload = {\n readonly code: WalletErrorCode;\n readonly retryAt?: number; // only for \"rate-limited\"\n};\n\nexport type Response =\n | { readonly v: typeof PROTOCOL_VERSION; readonly id: number; readonly ok: ProtocolValue }\n | { readonly v: typeof PROTOCOL_VERSION; readonly id: number; readonly err: ErrorPayload };\n\nexport type KernelEvent =\n | {\n readonly v: typeof PROTOCOL_VERSION;\n readonly event: \"status\";\n readonly status: StatusPayload;\n }\n | { readonly v: typeof PROTOCOL_VERSION; readonly event: \"locked\"; readonly reason: LockReason };\n\n/**\n * The worst-case encoded size of one request, enforced by both sides: the host refuses to post a\n * request over the cap and the kernel answers an oversized raw request with `invalid-input`.\n * Responses are not capped.\n */\nexport const MAX_REQUEST_BYTES = 1_048_576;\n\n/**\n * Upper-bound byte weight of a protocol value: a string costs `length * 3` (worst-case UTF-8), a\n * Uint8Array its `byteLength`, every scalar and every array element 8, and every object key\n * `key.length * 3 + 8` plus its value. Iterative — a deeply nested value cannot overflow the\n * stack.\n */\nexport function requestBytes(value: ProtocolValue): number {\n let total = 0;\n const stack: ProtocolValue[] = [value];\n while (stack.length > 0) {\n const item = stack.pop();\n if (item === undefined) {\n continue;\n }\n if (typeof item === \"string\") {\n total += item.length * 3;\n } else if (item instanceof Uint8Array) {\n total += item.byteLength;\n } else if (item === null || typeof item === \"boolean\" || typeof item === \"number\") {\n total += 8;\n } else if (Array.isArray(item)) {\n // Array.isArray widens the readonly member to any[] — re-annotate the element domain.\n const elements: ReadonlyArray<ProtocolValue> = item;\n total += elements.length * 8;\n for (const element of elements) {\n stack.push(element);\n }\n } else {\n for (const [key, child] of Object.entries(item)) {\n total += key.length * 3 + 8;\n stack.push(child);\n }\n }\n }\n return total;\n}\n\n/** Deep check that a structured-cloned value is a strict ProtocolValue (no cycles detected). */\nexport function isProtocolValue(value: unknown): value is ProtocolValue {\n switch (typeof value) {\n case \"boolean\":\n case \"string\":\n return true;\n case \"number\":\n return Number.isSafeInteger(value);\n case \"object\":\n break;\n default:\n return false;\n }\n if (value === null || value instanceof Uint8Array) {\n return true;\n }\n if (Array.isArray(value)) {\n return value.every(isProtocolValue);\n }\n if (Object.getPrototypeOf(value) !== Object.prototype) {\n return false;\n }\n return Object.values(value).every(isProtocolValue);\n}\n\n/** The status payload: core sections plus one object section per protocol module. */\nconst statusPayload: Validator<StatusPayload> = obj({\n protocol: literal(PROTOCOL_VERSION),\n vault: union(\n literal(\"uninitialized\"),\n literal(\"locked\"),\n literal(\"unlocked\"),\n literal(\"corrupted\"),\n literal(\"unsupported\"),\n literal(\"unavailable\"),\n ),\n factors: arr(factorInfo, MAX_SNAPSHOT_ITEMS),\n wallets: arr(walletInfo, MAX_SNAPSHOT_ITEMS),\n nostr: nostrStatus,\n backup: union(backupInfo, nullValue),\n});\n\n// The explicit annotation is the composition contract: a key missing from either table fails\n// declaration emit, and a duplicated key fails assignability (the spread's type for that key\n// cannot satisfy the intersection).\nexport const METHODS: {\n readonly status: MethodSpec<NullValue, StatusPayload>;\n} & typeof CORE_METHODS &\n typeof NOSTR_METHODS &\n typeof CHAINS_METHODS &\n typeof SPARK_METHODS = {\n status: {\n session: false,\n presence: false,\n params: nullValue,\n result: statusPayload,\n },\n ...CORE_METHODS,\n ...CHAINS_METHODS,\n ...NOSTR_METHODS,\n ...SPARK_METHODS,\n};\n\n// A method name must live in exactly one table: an overlap violates the never constraint.\ntype AssertNever<T extends never> = T;\nexport type MethodTablesDisjoint = [\n AssertNever<keyof typeof CORE_METHODS & keyof typeof NOSTR_METHODS>,\n AssertNever<keyof typeof CORE_METHODS & keyof typeof SPARK_METHODS>,\n AssertNever<keyof typeof NOSTR_METHODS & keyof typeof SPARK_METHODS>,\n];\n\nexport type MethodName = keyof typeof METHODS;\nexport type ParamsOf<M extends MethodName> = ReturnType<(typeof METHODS)[M][\"params\"]>;\nexport type ResultOf<M extends MethodName> = ReturnType<(typeof METHODS)[M][\"result\"]>;\n\nconst lockReason: Validator<LockReason> = union(\n literal(\"cold-start\"),\n literal(\"user\"),\n literal(\"idle\"),\n literal(\"background\"),\n literal(\"expired\"),\n literal(\"crashed\"),\n literal(\"invalidated\"),\n);\n\nconst errorPayload = obj({ code: walletErrorCode, retryAt: opt(safeTime) });\n\n/** Host-side validators: `kernelEvent` covers the two push messages. */\nexport const kernelEvent: Validator<KernelEvent> = union(\n obj({ v: literal(PROTOCOL_VERSION), event: literal(\"status\"), status: statusPayload }),\n obj({ v: literal(PROTOCOL_VERSION), event: literal(\"locked\"), reason: lockReason }),\n);\n\n/** Validates the `err` payload of a response; `ok` is checked against `METHODS[m].result`. */\nexport const responseError: Validator<{ code: WalletErrorCode; retryAt?: number | undefined }> =\n errorPayload;\n\nexport { NOSTR_METHODS, SPARK_METHODS };\nexport { CHAINS_METHODS } from \"./chains.ts\";\nexport type {\n ChainAccount,\n ChainAccountsParams,\n ChainSignResult,\n ChainTemplate,\n} from \"./chains.ts\";\nexport { CORE_METHODS, walletErrorCode } from \"./core.ts\";\nexport type { MethodSpec } from \"./core.ts\";\nexport {\n backupEnvelope,\n backupEnvelopeFactor,\n backupEnvelopeText,\n backupHeader,\n backupInfo,\n} from \"./backup.ts\";\nexport type {\n BackupFactor,\n BackupUnlockFactor,\n CreatedResult,\n CreateWithPasskeyParams,\n Factor,\n RestoreWithPasskeyParams,\n} from \"./core.ts\";\nexport type {\n BackupEnvelopeFactor,\n BackupEnvelopeWire,\n BackupHeaderWallet,\n BackupHeaderWire,\n BackupInfo,\n} from \"./backup.ts\";\nexport type {\n NostrExportFormat,\n Rumor,\n SignedEvent,\n UnsignedEventInput,\n UnwrapResult,\n} from \"./nostr.ts\";\nexport type {\n FrostAggregateJob,\n SparkApprovalSummary,\n SparkApproveIntent,\n FrostSignJob,\n HtlcTimeoutSignRequest,\n IdentityStatement,\n OperatorCommitment,\n PrepareClaimRequest,\n PreparedClaim,\n PreparedLightningReceive,\n PreparedTransfer,\n PreparedTransferLeaf,\n PrepareTransferRequest,\n SigningCommitment,\n SigningTarget,\n SparkAccountRef,\n SparkKey,\n SparkLeafKey,\n SparkNetwork,\n StaticDepositClaimRequest,\n StaticDepositClaimResult,\n StaticDepositClaimStatement,\n} from \"./spark.ts\";\nexport {\n ValidationError,\n arr,\n bool,\n bytes,\n int,\n literal,\n nullValue,\n obj,\n opt,\n record,\n str,\n union,\n validate,\n type Validator,\n} from \"./validate.ts\";\n"],"mappings":";;;;;;;;AAUA,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AACzB,MAAM,oBAAoB;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AAM,eAAe;AACnD;;AAGA,MAAM,gBAA0C,IAAI;CAClD,UAAU,QAAA,CAAwB;CAClC,OAAO,MACL,QAAQ,eAAe,GACvB,QAAQ,QAAQ,GAChB,QAAQ,UAAU,GAClB,QAAQ,WAAW,GACnB,QAAQ,aAAa,GACrB,QAAQ,aAAa,CACvB;CACA,SAAS,IAAI,YAAY,kBAAkB;CAC3C,SAAS,IAAI,YAAY,kBAAkB;CAC3C,OAAO;CACP,QAAQ,MAAM,YAAY,SAAS;AACrC,CAAC;AAKD,MAAa,UAKY;CACvB,QAAQ;EACN,SAAS;EACT,UAAU;EACV,QAAQ;EACR,QAAQ;CACV;CACA,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;AACL;AAcA,MAAM,aAAoC,MACxC,QAAQ,YAAY,GACpB,QAAQ,MAAM,GACd,QAAQ,MAAM,GACd,QAAQ,YAAY,GACpB,QAAQ,SAAS,GACjB,QAAQ,SAAS,GACjB,QAAQ,aAAa,CACvB;AAEA,MAAM,eAAe,IAAI;CAAE,MAAM;CAAiB,SAAS,IAAI,QAAQ;AAAE,CAAC;;AAG1E,MAAa,cAAsC,MACjD,IAAI;CAAE,GAAG,QAAA,CAAwB;CAAG,OAAO,QAAQ,QAAQ;CAAG,QAAQ;AAAc,CAAC,GACrF,IAAI;CAAE,GAAG,QAAA,CAAwB;CAAG,OAAO,QAAQ,QAAQ;CAAG,QAAQ;AAAW,CAAC,CACpF;;AAGA,MAAa,gBACX"}
@@ -1,3 +1,4 @@
1
- import { b as WalletErrorCode } from "./types-BD9fuAUj.mjs";
2
- import { $ as PreparedTransfer, A as isProtocolValue, At as opt, B as backupEnvelopeFactor, C as PROTOCOL_VERSION, Ct as arr, D as Response, Dt as literal, E as Request, Et as int, F as BackupEnvelopeWire, G as FrostSignJob, H as backupHeader, I as BackupHeaderWallet, J as OperatorCommitment, K as HtlcTimeoutSignRequest, L as BackupHeaderWire, M as requestBytes, Mt as str, N as responseError, Nt as union, O as ResultOf, Ot as nullValue, P as BackupEnvelopeFactor, Pt as validate, Q as PreparedLightningReceive, R as BackupInfo, S as NullValue, St as Validator, T as ProtocolValue, Tt as bytes, U as backupInfo, V as backupEnvelopeText, W as FrostAggregateJob, X as PrepareTransferRequest, Y as PrepareClaimRequest, Z as PreparedClaim, _ as KernelEvent, _t as Rumor, a as ChainSignResult, at as SparkApprovalSummary, b as MethodName, bt as UnwrapResult, c as BackupUnlockFactor, ct as SparkLeafKey, d as CreatedResult, dt as StaticDepositClaimResult, et as PreparedTransferLeaf, f as Factor, ft as StaticDepositClaimStatement, g as ErrorPayload, gt as NostrImportInput, h as walletErrorCode, ht as NostrExportFormat, it as SparkAccountRef, j as kernelEvent, jt as record, k as UNATTRIBUTED_ID, kt as obj, l as CORE_METHODS, lt as SparkNetwork, m as RestoreWithPasskeyParams, mt as NOSTR_METHODS, n as ChainAccount, nt as SigningCommitment, o as ChainTemplate, ot as SparkApproveIntent, p as MethodSpec, pt as KeyResult, q as IdentityStatement, r as ChainAccountsParams, rt as SigningTarget, s as BackupFactor, st as SparkKey, t as CHAINS_METHODS, tt as SPARK_METHODS, u as CreateWithPasskeyParams, ut as StaticDepositClaimRequest, v as MAX_REQUEST_BYTES, vt as SignedEvent, w as ParamsOf, wt as bool, x as MethodTablesDisjoint, xt as ValidationError, y as METHODS, yt as UnsignedEventInput, z as backupEnvelope } from "./chains-D_jfwTPT.mjs";
3
- export { type BackupEnvelopeFactor, type BackupEnvelopeWire, type BackupFactor, type BackupHeaderWallet, type BackupHeaderWire, type BackupInfo, type BackupUnlockFactor, CHAINS_METHODS, CORE_METHODS, type ChainAccount, type ChainAccountsParams, type ChainSignResult, type ChainTemplate, type CreateWithPasskeyParams, type CreatedResult, ErrorPayload, type Factor, type FrostAggregateJob, type FrostSignJob, type HtlcTimeoutSignRequest, type IdentityStatement, KernelEvent, type KeyResult, MAX_REQUEST_BYTES, METHODS, MethodName, type MethodSpec, MethodTablesDisjoint, NOSTR_METHODS, type NostrExportFormat, type NostrImportInput, NullValue, type OperatorCommitment, PROTOCOL_VERSION, ParamsOf, type PrepareClaimRequest, type PrepareTransferRequest, type PreparedClaim, type PreparedLightningReceive, type PreparedTransfer, type PreparedTransferLeaf, ProtocolValue, Request, Response, type RestoreWithPasskeyParams, ResultOf, type Rumor, SPARK_METHODS, type SignedEvent, type SigningCommitment, type SigningTarget, type SparkAccountRef, type SparkApprovalSummary, type SparkApproveIntent, type SparkKey, type SparkLeafKey, type SparkNetwork, type StaticDepositClaimRequest, type StaticDepositClaimResult, type StaticDepositClaimStatement, UNATTRIBUTED_ID, type UnsignedEventInput, type UnwrapResult, ValidationError, type Validator, type WalletErrorCode, arr, backupEnvelope, backupEnvelopeFactor, backupEnvelopeText, backupHeader, backupInfo, bool, bytes, int, isProtocolValue, kernelEvent, literal, nullValue, obj, opt, record, requestBytes, responseError, str, union, validate, walletErrorCode };
1
+ import { b as WalletErrorCode } from "./types-CIYT5uFj.mjs";
2
+ import { A as validate, C as literal, D as record, E as opt, O as str, S as int, T as obj, _ as ValidationError, a as ChainSignResult, b as bool, c as BackupUnlockFactor, d as CreatedResult, f as Factor, g as NullValue, h as walletErrorCode, k as union, l as CORE_METHODS, m as RestoreWithPasskeyParams, n as ChainAccount, o as ChainTemplate, p as MethodSpec, r as ChainAccountsParams, s as BackupFactor, t as CHAINS_METHODS, u as CreateWithPasskeyParams, v as Validator, w as nullValue, x as bytes, y as arr } from "./chains-BdcH4YnJ.mjs";
3
+ import { $ as Rumor, A as HtlcTimeoutSignRequest, B as SigningCommitment, C as backupEnvelope, D as backupInfo, E as backupHeader, F as PreparedClaim, G as SparkKey, H as SparkAccountRef, I as PreparedLightningReceive, J as StaticDepositClaimRequest, K as SparkLeafKey, L as PreparedTransfer, M as OperatorCommitment, N as PrepareClaimRequest, O as FrostAggregateJob, P as PrepareTransferRequest, Q as NostrExportFormat, R as PreparedTransferLeaf, S as BackupInfo, T as backupEnvelopeText, U as SparkApprovalSummary, V as SigningTarget, W as SparkApproveIntent, X as StaticDepositClaimStatement, Y as StaticDepositClaimResult, Z as NOSTR_METHODS, _ as responseError, a as MethodName, b as BackupHeaderWallet, c as ParamsOf, d as Response, et as SignedEvent, f as ResultOf, g as requestBytes, h as kernelEvent, i as METHODS, j as IdentityStatement, k as FrostSignJob, l as ProtocolValue, m as isProtocolValue, n as KernelEvent, nt as UnwrapResult, o as MethodTablesDisjoint, p as UNATTRIBUTED_ID, q as SparkNetwork, r as MAX_REQUEST_BYTES, s as PROTOCOL_VERSION, t as ErrorPayload, tt as UnsignedEventInput, u as Request, v as BackupEnvelopeFactor, w as backupEnvelopeFactor, x as BackupHeaderWire, y as BackupEnvelopeWire, z as SPARK_METHODS } from "./index-BXnQtz55.mjs";
4
+ export { type BackupEnvelopeFactor, type BackupEnvelopeWire, type BackupFactor, type BackupHeaderWallet, type BackupHeaderWire, type BackupInfo, type BackupUnlockFactor, CHAINS_METHODS, CORE_METHODS, type ChainAccount, type ChainAccountsParams, type ChainSignResult, type ChainTemplate, type CreateWithPasskeyParams, type CreatedResult, ErrorPayload, type Factor, type FrostAggregateJob, type FrostSignJob, type HtlcTimeoutSignRequest, type IdentityStatement, KernelEvent, MAX_REQUEST_BYTES, METHODS, MethodName, type MethodSpec, MethodTablesDisjoint, NOSTR_METHODS, type NostrExportFormat, type NullValue, type OperatorCommitment, PROTOCOL_VERSION, ParamsOf, type PrepareClaimRequest, type PrepareTransferRequest, type PreparedClaim, type PreparedLightningReceive, type PreparedTransfer, type PreparedTransferLeaf, ProtocolValue, Request, Response, type RestoreWithPasskeyParams, ResultOf, type Rumor, SPARK_METHODS, type SignedEvent, type SigningCommitment, type SigningTarget, type SparkAccountRef, type SparkApprovalSummary, type SparkApproveIntent, type SparkKey, type SparkLeafKey, type SparkNetwork, type StaticDepositClaimRequest, type StaticDepositClaimResult, type StaticDepositClaimStatement, UNATTRIBUTED_ID, type UnsignedEventInput, type UnwrapResult, ValidationError, type Validator, type WalletErrorCode, arr, backupEnvelope, backupEnvelopeFactor, backupEnvelopeText, backupHeader, backupInfo, bool, bytes, int, isProtocolValue, kernelEvent, literal, nullValue, obj, opt, record, requestBytes, responseError, str, union, validate, walletErrorCode };
package/dist/protocol.mjs CHANGED
@@ -1,3 +1,3 @@
1
- import { C as opt, D as validate, E as union, S as obj, T as str, _ as bool, b as literal, f as walletErrorCode, g as arr, h as ValidationError, t as CORE_METHODS, v as bytes, w as record, x as nullValue, y as int } from "./core-Dmz5SbyJ.mjs";
2
- import { a as isProtocolValue, c as responseError, d as CHAINS_METHODS, f as backupEnvelope, g as backupInfo, h as backupHeader, i as UNATTRIBUTED_ID, l as SPARK_METHODS, m as backupEnvelopeText, n as METHODS, o as kernelEvent, p as backupEnvelopeFactor, r as PROTOCOL_VERSION, s as requestBytes, t as MAX_REQUEST_BYTES, u as NOSTR_METHODS } from "./protocol-DvzlUKB8.mjs";
1
+ import { C as opt, D as validate, E as union, S as obj, T as str, _ as bool, b as literal, f as walletErrorCode, g as arr, h as ValidationError, t as CORE_METHODS, v as bytes, w as record, x as nullValue, y as int } from "./core-Cq5h9X0X.mjs";
2
+ import { a as isProtocolValue, c as responseError, d as CHAINS_METHODS, f as backupEnvelope, g as backupInfo, h as backupHeader, i as UNATTRIBUTED_ID, l as SPARK_METHODS, m as backupEnvelopeText, n as METHODS, o as kernelEvent, p as backupEnvelopeFactor, r as PROTOCOL_VERSION, s as requestBytes, t as MAX_REQUEST_BYTES, u as NOSTR_METHODS } from "./protocol-DbpLncEB.mjs";
3
3
  export { CHAINS_METHODS, CORE_METHODS, MAX_REQUEST_BYTES, METHODS, NOSTR_METHODS, PROTOCOL_VERSION, SPARK_METHODS, UNATTRIBUTED_ID, ValidationError, arr, backupEnvelope, backupEnvelopeFactor, backupEnvelopeText, backupHeader, backupInfo, bool, bytes, int, isProtocolValue, kernelEvent, literal, nullValue, obj, opt, record, requestBytes, responseError, str, union, validate, walletErrorCode };
@@ -1,6 +1,6 @@
1
1
  import { WalletError } from "./types.mjs";
2
2
  import { base64urlnopad } from "@scure/base";
3
- //#region src/factors.ts
3
+ // src/factors.ts
4
4
  /**
5
5
  * Factor plumbing for the host connector: public `UnlockFactor`/`InitialFactor` inputs become wire
6
6
  * `Factor` material, passkey material comes from the host's WebAuthn ceremony, and every secret
@@ -175,8 +175,7 @@ async function resolveInitialFactor(source, factor, transfer, walletCeremony) {
175
175
  }
176
176
  throw noHardware();
177
177
  }
178
- //#endregion
179
- //#region src/secret.ts
178
+ // src/secret.ts
180
179
  /**
181
180
  * One-shot secret bytes handed to the app: `read` returns them exactly once, `wipe` zeroes them.
182
181
  * The second `read` fails closed.
@@ -197,7 +196,6 @@ var SingleUseSecret = class {
197
196
  this.bytes = void 0;
198
197
  }
199
198
  };
200
- //#endregion
201
199
  export { passkeyName as a, resolveBackupUnlockFactor as c, vaultSaltBytes as d, walletSaltBytes as f, defaultUnlockFactor as i, resolveFactor as l, wireSecretText as m, PASSKEY_PURPOSE_VAULT as n, requireCeremony as o, wireBytes as p, PASSKEY_PURPOSE_WALLET as r, resolveBackupFactor as s, SingleUseSecret as t, resolveInitialFactor as u };
202
200
 
203
- //# sourceMappingURL=secret-BiyX0Hus.mjs.map
201
+ //# sourceMappingURL=secret-Dz_ItVt6.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"secret-BiyX0Hus.mjs","names":[],"sources":["../src/factors.ts","../src/secret.ts"],"sourcesContent":["/**\n * Factor plumbing for the host connector: public `UnlockFactor`/`InitialFactor` inputs become wire\n * `Factor` material, passkey material comes from the host's WebAuthn ceremony, and every secret\n * byte travels in a fresh exact-size buffer on the transfer list.\n */\nimport { base64urlnopad } from \"@scure/base\";\n\nimport type { BackupFactor, BackupUnlockFactor, Factor } from \"./protocol/index.ts\";\nimport { WalletError } from \"./types.ts\";\nimport type { FactorInfo, InitialFactor, PasskeyConfig, UnlockFactor } from \"./types.ts\";\n\nexport type PrfSalts = { readonly first: Uint8Array; readonly second?: Uint8Array };\n\n/** Purpose bytes stamped into the first byte of a credential's WebAuthn user handle. */\nexport const PASSKEY_PURPOSE_WALLET = 0x01;\nexport const PASSKEY_PURPOSE_VAULT = 0x02;\n\nexport type PrfResult = {\n readonly credentialId: Uint8Array;\n readonly first: Uint8Array;\n readonly second?: Uint8Array;\n /** The assertion's `userHandle` — its first byte declares the credential's purpose. */\n readonly userHandle?: Uint8Array;\n /** The credential survives this device: the authenticator data's BE and BS flags are both set. */\n readonly synced: boolean;\n};\n\n/**\n * The WebAuthn ceremony the host performs. Implementations throw `WalletError` — \"cancelled\" when\n * the user aborts, \"factor-unavailable\" when the credential cannot produce a PRF. `name` is the new\n * credential's display name, validated by the host before the call (1–64 characters).\n */\nexport type PasskeyCeremony = {\n readonly create: (input: {\n readonly purpose: \"wallet\" | \"vault\";\n readonly name: string;\n readonly salts: PrfSalts;\n }) => Promise<PrfResult>;\n readonly assert: (input: {\n readonly credentialIds?: ReadonlyArray<Uint8Array>;\n readonly salts: PrfSalts;\n }) => Promise<PrfResult>;\n};\n\n/**\n * Which vault factors a host offers: `hardware` (React Native — the platform keystore is the only\n * factor, and omitted factors mean it) or `software` (web/node — passkey and password). The kernel\n * enforces the same rule; resolving here keeps a doomed request from firing a ceremony.\n */\nexport type FactorMode = \"hardware\" | \"software\";\n\n/** What factor resolution needs from the wallet: config, the ceremony, live factor records. */\nexport type FactorSource = {\n readonly mode: FactorMode;\n readonly passkey: PasskeyConfig;\n readonly ceremony: PasskeyCeremony | undefined;\n readonly factors: () => ReadonlyArray<FactorInfo>;\n};\n\nconst HARDWARE: Factor = { kind: \"hardware\" };\n\nfunction hardwareOnly(): WalletError {\n return new WalletError(\"factor-unavailable\", \"this host unlocks only with the hardware factor\");\n}\n\nfunction noHardware(): WalletError {\n return new WalletError(\"factor-unavailable\", \"hardware factors exist only on React Native\");\n}\n\n/** The factor `vault.unlock()` uses when the caller passes none. */\nexport function defaultUnlockFactor(source: FactorSource): UnlockFactor {\n return source.mode === \"hardware\" ? { kind: \"hardware\" } : { kind: \"passkey\" };\n}\n\nexport function vaultSaltBytes(source: FactorSource): Uint8Array {\n return new TextEncoder().encode(source.passkey.vaultSalt);\n}\n\nexport function walletSaltBytes(source: FactorSource): Uint8Array {\n return new TextEncoder().encode(source.passkey.walletSalt);\n}\n\nexport function backupSaltBytes(source: FactorSource): Uint8Array {\n return new TextEncoder().encode(source.passkey.backupSalt);\n}\n\n/**\n * The host-run backup passkey ceremony (web): the PRF is evaluated over `backupSalt` with one of\n * the vault's passkey credentials, producing `prfBackup` instead of the vault `prf`.\n */\nasync function hostBackupPasskey(\n source: FactorSource,\n transfer: ArrayBuffer[],\n): Promise<Extract<BackupFactor, { ceremony: \"host\" }>> {\n const ceremony = requireCeremony(source);\n const result = await ceremony.assert({\n credentialIds: passkeyCredentialIds(source),\n salts: { first: backupSaltBytes(source) },\n });\n return {\n kind: \"passkey\",\n ceremony: \"host\",\n credentialId: wireBytes(result.credentialId, transfer),\n prfBackup: wireBytes(result.first, transfer, true),\n };\n}\n\nfunction backupPassword(\n factor: UnlockFactor,\n transfer: ArrayBuffer[],\n): { readonly kind: \"password\"; readonly password: Uint8Array } | undefined {\n if (factor.kind === \"hardware\") {\n throw new WalletError(\"invalid-input\", \"backup factors are passkeys or passwords\");\n }\n return factor.kind === \"password\"\n ? { kind: \"password\", password: wireSecretText(factor.password, transfer) }\n : undefined;\n}\n\n/**\n * Resolves a public `UnlockFactor` to a factor that seals a new backup key. A hardware host lets\n * the kernel register the protection credential itself; nothing secret crosses the channel.\n */\nexport async function resolveBackupFactor(\n source: FactorSource,\n factor: UnlockFactor,\n transfer: ArrayBuffer[],\n): Promise<BackupFactor> {\n const password = backupPassword(factor, transfer);\n if (password !== undefined) {\n return password;\n }\n if (source.mode === \"hardware\") {\n return {\n kind: \"passkey\",\n ceremony: \"kernel\",\n rpId: source.passkey.rpId,\n rpName: source.passkey.rpName,\n backupSalt: source.passkey.backupSalt,\n };\n }\n return hostBackupPasskey(source, transfer);\n}\n\n/** Resolves a public `UnlockFactor` to a factor that opens a backup envelope. */\nexport async function resolveBackupUnlockFactor(\n source: FactorSource,\n factor: UnlockFactor,\n transfer: ArrayBuffer[],\n): Promise<BackupUnlockFactor> {\n const password = backupPassword(factor, transfer);\n if (password !== undefined) {\n return password;\n }\n if (source.mode === \"hardware\") {\n return {\n kind: \"passkey\",\n ceremony: \"kernel\",\n rpId: source.passkey.rpId,\n backupSalt: source.passkey.backupSalt,\n };\n }\n return hostBackupPasskey(source, transfer);\n}\n\n/** Passkey credential ids of the current vault factors, for `assert`'s allowCredentials. */\nfunction passkeyCredentialIds(source: FactorSource): Uint8Array[] {\n return source\n .factors()\n .flatMap((factor) =>\n factor.kind === \"passkey\" ? [base64urlnopad.decode(factor.credentialId)] : [],\n );\n}\n\n/**\n * A Uint8Array is placed on the wire in a fresh exact-size buffer whose ArrayBuffer goes into the\n * transfer list — the bytes move to the kernel and cannot detach caller-owned memory. Secret\n * sources are wiped after copying.\n */\nexport function wireBytes(\n source: Uint8Array,\n transfer: ArrayBuffer[],\n wipeSource = false,\n): Uint8Array {\n // Always a fresh exact-size buffer: transferring must never detach caller-owned memory.\n const wire = new Uint8Array(source);\n if (wipeSource) {\n source.fill(0);\n }\n transfer.push(wire.buffer);\n return wire;\n}\n\nexport function wireSecretText(text: string, transfer: ArrayBuffer[]): Uint8Array {\n return wireBytes(new TextEncoder().encode(text), transfer);\n}\n\nexport function requireCeremony(source: FactorSource): PasskeyCeremony {\n if (source.ceremony === undefined) {\n throw new WalletError(\"factor-unavailable\", \"no passkey ceremony is configured\");\n }\n return source.ceremony;\n}\n\n/** A passkey credential's display name: trimmed, 1–64 UTF-16 code units, else invalid-input. */\nexport function passkeyName(name: string): string {\n const trimmed = name.trim();\n if (trimmed.length === 0 || trimmed.length > 64) {\n throw new WalletError(\"invalid-input\", \"the passkey name must be 1–64 characters\");\n }\n return trimmed;\n}\n\n/**\n * Resolves a public `UnlockFactor` to wire factor material. `transfer` collects every buffer the\n * port must move. Ceremony errors surface as they are (cancelled / factor-unavailable).\n */\nexport async function resolveFactor(\n source: FactorSource,\n factor: UnlockFactor,\n transfer: ArrayBuffer[],\n): Promise<Factor> {\n if (source.mode === \"hardware\") {\n if (factor.kind !== \"hardware\") {\n throw hardwareOnly();\n }\n return HARDWARE;\n }\n if (factor.kind === \"hardware\") {\n throw noHardware();\n }\n if (factor.kind === \"password\") {\n return { kind: \"password\", password: wireSecretText(factor.password, transfer) };\n }\n const ceremony = requireCeremony(source);\n const result = await ceremony.assert({\n credentialIds: passkeyCredentialIds(source),\n salts: { first: vaultSaltBytes(source) },\n });\n return {\n kind: \"passkey\",\n credentialId: wireBytes(result.credentialId, transfer),\n prf: wireBytes(result.first, transfer, true),\n };\n}\n\n/**\n * Resolves a public `InitialFactor` (a factor being created). For `create/restoreWithPasskey` the\n * default passkey factor reuses the wallet ceremony's own credential and `second` PRF output; a\n * hardware host always establishes the hardware factor and drops that output.\n */\nexport async function resolveInitialFactor(\n source: FactorSource,\n factor: InitialFactor | undefined,\n transfer: ArrayBuffer[],\n walletCeremony?: PrfResult,\n): Promise<Factor> {\n if (source.mode === \"hardware\") {\n walletCeremony?.second?.fill(0);\n if (factor !== undefined && factor.kind !== \"hardware\") {\n throw hardwareOnly();\n }\n return HARDWARE;\n }\n if (factor === undefined || factor.kind === \"passkey\") {\n const name = factor === undefined ? undefined : passkeyName(factor.name);\n if (walletCeremony !== undefined) {\n const { second } = walletCeremony;\n if (second === undefined) {\n throw new WalletError(\"factor-unavailable\", \"the ceremony returned no vault PRF output\");\n }\n return {\n kind: \"passkey\",\n credentialId: wireBytes(walletCeremony.credentialId, transfer),\n prf: wireBytes(second, transfer, true),\n };\n }\n if (name === undefined) {\n // No caller reaches this today (createFactorParam requires a factor), but the ceremony\n // contract needs a name — fail closed rather than inventing one.\n throw new WalletError(\"invalid-input\", \"a passkey factor requires a name\");\n }\n const result = await requireCeremony(source).create({\n purpose: \"vault\",\n name,\n salts: { first: vaultSaltBytes(source) },\n });\n return {\n kind: \"passkey\",\n credentialId: wireBytes(result.credentialId, transfer),\n prf: wireBytes(result.first, transfer, true),\n };\n }\n if (factor.kind === \"password\") {\n walletCeremony?.second?.fill(0); // the passkey vault factor is not needed\n return { kind: \"password\", password: wireSecretText(factor.password, transfer) };\n }\n throw noHardware();\n}\n","import { WalletError } from \"./types.ts\";\nimport type { ExportedSecret } from \"./types.ts\";\n\n/**\n * One-shot secret bytes handed to the app: `read` returns them exactly once, `wipe` zeroes them.\n * The second `read` fails closed.\n */\nexport class SingleUseSecret implements ExportedSecret {\n private bytes: Uint8Array | undefined;\n\n constructor(bytes: Uint8Array) {\n this.bytes = bytes;\n }\n\n read(): Uint8Array {\n const { bytes } = this;\n if (bytes === undefined) {\n throw new WalletError(\"invalid-input\", \"secret already read or wiped\");\n }\n this.bytes = undefined;\n return bytes;\n }\n\n wipe(): void {\n this.bytes?.fill(0);\n this.bytes = undefined;\n }\n}\n"],"mappings":";;;;;;;;;AAcA,MAAa,yBAAyB;AACtC,MAAa,wBAAwB;AA4CrC,MAAM,WAAmB,EAAE,MAAM,WAAW;AAE5C,SAAS,eAA4B;CACnC,OAAO,IAAI,YAAY,sBAAsB,iDAAiD;AAChG;AAEA,SAAS,aAA0B;CACjC,OAAO,IAAI,YAAY,sBAAsB,6CAA6C;AAC5F;;AAGA,SAAgB,oBAAoB,QAAoC;CACtE,OAAO,OAAO,SAAS,aAAa,EAAE,MAAM,WAAW,IAAI,EAAE,MAAM,UAAU;AAC/E;AAEA,SAAgB,eAAe,QAAkC;CAC/D,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,OAAO,QAAQ,SAAS;AAC1D;AAEA,SAAgB,gBAAgB,QAAkC;CAChE,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,OAAO,QAAQ,UAAU;AAC3D;AAEA,SAAgB,gBAAgB,QAAkC;CAChE,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,OAAO,QAAQ,UAAU;AAC3D;;;;;AAMA,eAAe,kBACb,QACA,UACsD;CAEtD,MAAM,SAAS,MADE,gBAAgB,MACL,CAAC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AO,WAAW,KAAA,IAAY,KAAA,IAAY,YAAY,OAAO,IAAI;EACvE,IAAI,mBAAmB,KAAA,GAAW;GAChC,MAAM,EAAE,WAAW;GACnB,IAAI,WAAW,KAAA,GACb,MAAM,IAAI,YAAY,sBAAsB,2CAA2C;GAEzF,OAAO;IACL,MAAM;IACN,cAAc,UAAU,eAAe,cAAc,QAAQ;IAC7D,KAAK,UAAU,QAAQ,UAAU,IAAI;GACvC;EACF;EACA,IAAI,SAAS,KAAA,GAGX,MAAM,IAAI,YAAY,iBAAiB,kCAAkC;EAE3E,MAAM,SAAS,MAAM,gBAAgB,MAAM,CAAC,CAAC,OAAO;GAClD,SAAS;GACT;GACA,OAAO,EAAE,OAAO,eAAe,MAAM,EAAE;EACzC,CAAC;EACD,OAAO;GACL,MAAM;GACN,cAAc,UAAU,OAAO,cAAc,QAAQ;GACrD,KAAK,UAAU,OAAO,OAAO,UAAU,IAAI;EAC7C;CACF;CACA,IAAI,OAAO,SAAS,YAAY;EAC9B,gBAAgB,QAAQ,KAAK,CAAC;EAC9B,OAAO;GAAE,MAAM;GAAY,UAAU,eAAe,OAAO,UAAU,QAAQ;EAAE;CACjF;CACA,MAAM,WAAW;AACnB;;;;;;;ACnSA,IAAa,kBAAb,MAAuD;CACrD;CAEA,YAAY,OAAmB;EAC7B,KAAK,QAAQ;CACf;CAEA,OAAmB;EACjB,MAAM,EAAE,UAAU;EAClB,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,YAAY,iBAAiB,8BAA8B;EAEvE,KAAK,QAAQ,KAAA;EACb,OAAO;CACT;CAEA,OAAa;EACX,KAAK,OAAO,KAAK,CAAC;EAClB,KAAK,QAAQ,KAAA;CACf;AACF"}
1
+ {"version":3,"file":"secret-Dz_ItVt6.mjs","names":[],"sources":["../src/factors.ts","../src/secret.ts"],"sourcesContent":["/**\n * Factor plumbing for the host connector: public `UnlockFactor`/`InitialFactor` inputs become wire\n * `Factor` material, passkey material comes from the host's WebAuthn ceremony, and every secret\n * byte travels in a fresh exact-size buffer on the transfer list.\n */\nimport { base64urlnopad } from \"@scure/base\";\n\nimport type { BackupFactor, BackupUnlockFactor, Factor } from \"./protocol/index.ts\";\nimport { WalletError } from \"./types.ts\";\nimport type { FactorInfo, InitialFactor, PasskeyConfig, UnlockFactor } from \"./types.ts\";\n\nexport type PrfSalts = { readonly first: Uint8Array; readonly second?: Uint8Array };\n\n/** Purpose bytes stamped into the first byte of a credential's WebAuthn user handle. */\nexport const PASSKEY_PURPOSE_WALLET = 0x01;\nexport const PASSKEY_PURPOSE_VAULT = 0x02;\n\nexport type PrfResult = {\n readonly credentialId: Uint8Array;\n readonly first: Uint8Array;\n readonly second?: Uint8Array;\n /** The assertion's `userHandle` — its first byte declares the credential's purpose. */\n readonly userHandle?: Uint8Array;\n /** The credential survives this device: the authenticator data's BE and BS flags are both set. */\n readonly synced: boolean;\n};\n\n/**\n * The WebAuthn ceremony the host performs. Implementations throw `WalletError` — \"cancelled\" when\n * the user aborts, \"factor-unavailable\" when the credential cannot produce a PRF. `name` is the new\n * credential's display name, validated by the host before the call (1–64 characters).\n */\nexport type PasskeyCeremony = {\n readonly create: (input: {\n readonly purpose: \"wallet\" | \"vault\";\n readonly name: string;\n readonly salts: PrfSalts;\n }) => Promise<PrfResult>;\n readonly assert: (input: {\n readonly credentialIds?: ReadonlyArray<Uint8Array>;\n readonly salts: PrfSalts;\n }) => Promise<PrfResult>;\n};\n\n/**\n * Which vault factors a host offers: `hardware` (React Native — the platform keystore is the only\n * factor, and omitted factors mean it) or `software` (web/node — passkey and password). The kernel\n * enforces the same rule; resolving here keeps a doomed request from firing a ceremony.\n */\nexport type FactorMode = \"hardware\" | \"software\";\n\n/** What factor resolution needs from the wallet: config, the ceremony, live factor records. */\nexport type FactorSource = {\n readonly mode: FactorMode;\n readonly passkey: PasskeyConfig;\n readonly ceremony: PasskeyCeremony | undefined;\n readonly factors: () => ReadonlyArray<FactorInfo>;\n};\n\nconst HARDWARE: Factor = { kind: \"hardware\" };\n\nfunction hardwareOnly(): WalletError {\n return new WalletError(\"factor-unavailable\", \"this host unlocks only with the hardware factor\");\n}\n\nfunction noHardware(): WalletError {\n return new WalletError(\"factor-unavailable\", \"hardware factors exist only on React Native\");\n}\n\n/** The factor `vault.unlock()` uses when the caller passes none. */\nexport function defaultUnlockFactor(source: FactorSource): UnlockFactor {\n return source.mode === \"hardware\" ? { kind: \"hardware\" } : { kind: \"passkey\" };\n}\n\nexport function vaultSaltBytes(source: FactorSource): Uint8Array {\n return new TextEncoder().encode(source.passkey.vaultSalt);\n}\n\nexport function walletSaltBytes(source: FactorSource): Uint8Array {\n return new TextEncoder().encode(source.passkey.walletSalt);\n}\n\nexport function backupSaltBytes(source: FactorSource): Uint8Array {\n return new TextEncoder().encode(source.passkey.backupSalt);\n}\n\n/**\n * The host-run backup passkey ceremony (web): the PRF is evaluated over `backupSalt` with one of\n * the vault's passkey credentials, producing `prfBackup` instead of the vault `prf`.\n */\nasync function hostBackupPasskey(\n source: FactorSource,\n transfer: ArrayBuffer[],\n): Promise<Extract<BackupFactor, { ceremony: \"host\" }>> {\n const ceremony = requireCeremony(source);\n const result = await ceremony.assert({\n credentialIds: passkeyCredentialIds(source),\n salts: { first: backupSaltBytes(source) },\n });\n return {\n kind: \"passkey\",\n ceremony: \"host\",\n credentialId: wireBytes(result.credentialId, transfer),\n prfBackup: wireBytes(result.first, transfer, true),\n };\n}\n\nfunction backupPassword(\n factor: UnlockFactor,\n transfer: ArrayBuffer[],\n): { readonly kind: \"password\"; readonly password: Uint8Array } | undefined {\n if (factor.kind === \"hardware\") {\n throw new WalletError(\"invalid-input\", \"backup factors are passkeys or passwords\");\n }\n return factor.kind === \"password\"\n ? { kind: \"password\", password: wireSecretText(factor.password, transfer) }\n : undefined;\n}\n\n/**\n * Resolves a public `UnlockFactor` to a factor that seals a new backup key. A hardware host lets\n * the kernel register the protection credential itself; nothing secret crosses the channel.\n */\nexport async function resolveBackupFactor(\n source: FactorSource,\n factor: UnlockFactor,\n transfer: ArrayBuffer[],\n): Promise<BackupFactor> {\n const password = backupPassword(factor, transfer);\n if (password !== undefined) {\n return password;\n }\n if (source.mode === \"hardware\") {\n return {\n kind: \"passkey\",\n ceremony: \"kernel\",\n rpId: source.passkey.rpId,\n rpName: source.passkey.rpName,\n backupSalt: source.passkey.backupSalt,\n };\n }\n return hostBackupPasskey(source, transfer);\n}\n\n/** Resolves a public `UnlockFactor` to a factor that opens a backup envelope. */\nexport async function resolveBackupUnlockFactor(\n source: FactorSource,\n factor: UnlockFactor,\n transfer: ArrayBuffer[],\n): Promise<BackupUnlockFactor> {\n const password = backupPassword(factor, transfer);\n if (password !== undefined) {\n return password;\n }\n if (source.mode === \"hardware\") {\n return {\n kind: \"passkey\",\n ceremony: \"kernel\",\n rpId: source.passkey.rpId,\n backupSalt: source.passkey.backupSalt,\n };\n }\n return hostBackupPasskey(source, transfer);\n}\n\n/** Passkey credential ids of the current vault factors, for `assert`'s allowCredentials. */\nfunction passkeyCredentialIds(source: FactorSource): Uint8Array[] {\n return source\n .factors()\n .flatMap((factor) =>\n factor.kind === \"passkey\" ? [base64urlnopad.decode(factor.credentialId)] : [],\n );\n}\n\n/**\n * A Uint8Array is placed on the wire in a fresh exact-size buffer whose ArrayBuffer goes into the\n * transfer list — the bytes move to the kernel and cannot detach caller-owned memory. Secret\n * sources are wiped after copying.\n */\nexport function wireBytes(\n source: Uint8Array,\n transfer: ArrayBuffer[],\n wipeSource = false,\n): Uint8Array {\n // Always a fresh exact-size buffer: transferring must never detach caller-owned memory.\n const wire = new Uint8Array(source);\n if (wipeSource) {\n source.fill(0);\n }\n transfer.push(wire.buffer);\n return wire;\n}\n\nexport function wireSecretText(text: string, transfer: ArrayBuffer[]): Uint8Array {\n return wireBytes(new TextEncoder().encode(text), transfer);\n}\n\nexport function requireCeremony(source: FactorSource): PasskeyCeremony {\n if (source.ceremony === undefined) {\n throw new WalletError(\"factor-unavailable\", \"no passkey ceremony is configured\");\n }\n return source.ceremony;\n}\n\n/** A passkey credential's display name: trimmed, 1–64 UTF-16 code units, else invalid-input. */\nexport function passkeyName(name: string): string {\n const trimmed = name.trim();\n if (trimmed.length === 0 || trimmed.length > 64) {\n throw new WalletError(\"invalid-input\", \"the passkey name must be 1–64 characters\");\n }\n return trimmed;\n}\n\n/**\n * Resolves a public `UnlockFactor` to wire factor material. `transfer` collects every buffer the\n * port must move. Ceremony errors surface as they are (cancelled / factor-unavailable).\n */\nexport async function resolveFactor(\n source: FactorSource,\n factor: UnlockFactor,\n transfer: ArrayBuffer[],\n): Promise<Factor> {\n if (source.mode === \"hardware\") {\n if (factor.kind !== \"hardware\") {\n throw hardwareOnly();\n }\n return HARDWARE;\n }\n if (factor.kind === \"hardware\") {\n throw noHardware();\n }\n if (factor.kind === \"password\") {\n return { kind: \"password\", password: wireSecretText(factor.password, transfer) };\n }\n const ceremony = requireCeremony(source);\n const result = await ceremony.assert({\n credentialIds: passkeyCredentialIds(source),\n salts: { first: vaultSaltBytes(source) },\n });\n return {\n kind: \"passkey\",\n credentialId: wireBytes(result.credentialId, transfer),\n prf: wireBytes(result.first, transfer, true),\n };\n}\n\n/**\n * Resolves a public `InitialFactor` (a factor being created). For `create/restoreWithPasskey` the\n * default passkey factor reuses the wallet ceremony's own credential and `second` PRF output; a\n * hardware host always establishes the hardware factor and drops that output.\n */\nexport async function resolveInitialFactor(\n source: FactorSource,\n factor: InitialFactor | undefined,\n transfer: ArrayBuffer[],\n walletCeremony?: PrfResult,\n): Promise<Factor> {\n if (source.mode === \"hardware\") {\n walletCeremony?.second?.fill(0);\n if (factor !== undefined && factor.kind !== \"hardware\") {\n throw hardwareOnly();\n }\n return HARDWARE;\n }\n if (factor === undefined || factor.kind === \"passkey\") {\n const name = factor === undefined ? undefined : passkeyName(factor.name);\n if (walletCeremony !== undefined) {\n const { second } = walletCeremony;\n if (second === undefined) {\n throw new WalletError(\"factor-unavailable\", \"the ceremony returned no vault PRF output\");\n }\n return {\n kind: \"passkey\",\n credentialId: wireBytes(walletCeremony.credentialId, transfer),\n prf: wireBytes(second, transfer, true),\n };\n }\n if (name === undefined) {\n // No caller reaches this today (createFactorParam requires a factor), but the ceremony\n // contract needs a name — fail closed rather than inventing one.\n throw new WalletError(\"invalid-input\", \"a passkey factor requires a name\");\n }\n const result = await requireCeremony(source).create({\n purpose: \"vault\",\n name,\n salts: { first: vaultSaltBytes(source) },\n });\n return {\n kind: \"passkey\",\n credentialId: wireBytes(result.credentialId, transfer),\n prf: wireBytes(result.first, transfer, true),\n };\n }\n if (factor.kind === \"password\") {\n walletCeremony?.second?.fill(0); // the passkey vault factor is not needed\n return { kind: \"password\", password: wireSecretText(factor.password, transfer) };\n }\n throw noHardware();\n}\n","import { WalletError } from \"./types.ts\";\nimport type { ExportedSecret } from \"./types.ts\";\n\n/**\n * One-shot secret bytes handed to the app: `read` returns them exactly once, `wipe` zeroes them.\n * The second `read` fails closed.\n */\nexport class SingleUseSecret implements ExportedSecret {\n private bytes: Uint8Array | undefined;\n\n constructor(bytes: Uint8Array) {\n this.bytes = bytes;\n }\n\n read(): Uint8Array {\n const { bytes } = this;\n if (bytes === undefined) {\n throw new WalletError(\"invalid-input\", \"secret already read or wiped\");\n }\n this.bytes = undefined;\n return bytes;\n }\n\n wipe(): void {\n this.bytes?.fill(0);\n this.bytes = undefined;\n }\n}\n"],"mappings":";;;;;;;;;AAcA,MAAa,yBAAyB;AACtC,MAAa,wBAAwB;AA4CrC,MAAM,WAAmB,EAAE,MAAM,WAAW;AAE5C,SAAS,eAA4B;CACnC,OAAO,IAAI,YAAY,sBAAsB,iDAAiD;AAChG;AAEA,SAAS,aAA0B;CACjC,OAAO,IAAI,YAAY,sBAAsB,6CAA6C;AAC5F;;AAGA,SAAgB,oBAAoB,QAAoC;CACtE,OAAO,OAAO,SAAS,aAAa,EAAE,MAAM,WAAW,IAAI,EAAE,MAAM,UAAU;AAC/E;AAEA,SAAgB,eAAe,QAAkC;CAC/D,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,OAA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,KAAK,QAAQ,KAAA;EACb,OAAO;CACT;CAEA,OAAa;EACX,KAAK,OAAO,KAAK,CAAC;EAClB,KAAK,QAAQ,KAAA;CACf;AACF"}
package/dist/spark.d.mts CHANGED
@@ -1,7 +1,6 @@
1
- import { h as UnlockFactor, v as Wallet } from "./types-BD9fuAUj.mjs";
2
- import { at as SparkApprovalSummary, it as SparkAccountRef, ot as SparkApproveIntent } from "./chains-D_jfwTPT.mjs";
1
+ import { h as UnlockFactor, v as Wallet } from "./types-CIYT5uFj.mjs";
2
+ import { H as SparkAccountRef, U as SparkApprovalSummary, W as SparkApproveIntent } from "./index-BXnQtz55.mjs";
3
3
  import { SparkSigner, SparkSigner as SparkSigner$1 } from "@qntx/spark/signer";
4
- //#region src/spark/types.d.ts
5
4
  type SparkApi = {
6
5
  /**
7
6
  * The SparkSigner for one wallet account group on one network. The kernel owns the signer pool —
@@ -22,9 +21,6 @@ type SparkApi = {
22
21
  readonly verify: UnlockFactor;
23
22
  }) => Promise<SparkApprovalSummary>;
24
23
  };
25
- //#endregion
26
- //#region src/spark/index.d.ts
27
24
  export declare function spark(wallet: Wallet): SparkApi;
28
- //#endregion
29
25
  export type { SparkAccountRef, SparkApi, SparkSigner };
30
26
  //# sourceMappingURL=spark.d.mts.map
package/dist/spark.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { WalletError } from "./types.mjs";
2
- import { t as internalsOf } from "./internal-LBHal13j.mjs";
3
- //#region src/spark/wire.ts
2
+ import { t as internalsOf } from "./internal-CAKfHjIg.mjs";
3
+ // src/spark/wire.ts
4
4
  function bad(what) {
5
5
  throw new WalletError("invalid-input", `spark: unexpected ${what}`);
6
6
  }
@@ -175,8 +175,7 @@ function staticDepositClaimRequest(req) {
175
175
  statement: depositClaimStatement(req.statement)
176
176
  };
177
177
  }
178
- //#endregion
179
- //#region src/spark/signer.ts
178
+ // src/spark/signer.ts
180
179
  function proxySigner(account, internals) {
181
180
  return {
182
181
  identityPublicKey: async () => internals.call("spark.identityPublicKey", { account }),
@@ -267,8 +266,7 @@ function proxySigner(account, internals) {
267
266
  dispose: () => void 0
268
267
  };
269
268
  }
270
- //#endregion
271
- //#region src/spark/index.ts
269
+ // src/spark/index.ts
272
270
  /**
273
271
  * The spark module of @qntx/wallet: `spark(wallet)` returns the wallet's Spark API — proxy
274
272
  * SparkSigners backed by the enclave's signer pool. The API is memoized per wallet so repeated
@@ -297,7 +295,6 @@ function spark(wallet) {
297
295
  }
298
296
  return api;
299
297
  }
300
- //#endregion
301
298
  export { spark };
302
299
 
303
300
  //# sourceMappingURL=spark.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"spark.mjs","names":[],"sources":["../src/spark/wire.ts","../src/spark/signer.ts","../src/spark/index.ts"],"sourcesContent":["/**\n * Input projection for the proxy signer: every request value is rebuilt from its declared wire\n * fields only — callers (e.g. SparkClient) hand us library objects that may carry extra keys\n * (protobuf-es `$typeName`, branding), and the kernel's strict obj() validators reject any key not\n * in the shape. Unknown `kind`/`type` discriminants fail `invalid-input` here, before any request\n * is posted.\n */\nimport type {\n FrostAggregateJob,\n FrostSignJob,\n HtlcTimeoutSignRequest,\n IdentityStatement,\n OperatorCommitment,\n PrepareClaimRequest,\n PrepareTransferRequest,\n SigningCommitment,\n SigningTarget,\n SparkKey,\n SparkLeafKey,\n StaticDepositClaimRequest,\n StaticDepositClaimStatement,\n} from \"../protocol/index.ts\";\nimport { WalletError } from \"../types.ts\";\n\nfunction bad(what: string): never {\n throw new WalletError(\"invalid-input\", `spark: unexpected ${what}`);\n}\n\nconst u8 = (v: Uint8Array, what: string): Uint8Array => (v instanceof Uint8Array ? v : bad(what));\nconst s = (v: string, what: string): string => (typeof v === \"string\" ? v : bad(what));\nconst n = (v: number, what: string): number => (typeof v === \"number\" ? v : bad(what));\n\nexport function leafKey(key: SparkLeafKey): SparkLeafKey {\n if (key.type === \"leaf\") {\n return { type: \"leaf\", leafId: s(key.leafId, \"leafId\") };\n }\n if (key.type === \"static-deposit\") {\n return { type: \"static-deposit\", index: n(key.index, \"index\") };\n }\n return bad(\"leaf key type\");\n}\n\nexport function sparkKey(key: SparkKey): SparkKey {\n if (key.type === \"received\") {\n return { type: \"received\", ciphertext: u8(key.ciphertext, \"ciphertext\") };\n }\n return leafKey(key);\n}\n\nexport function commitment(c: SigningCommitment): SigningCommitment {\n return {\n hiding: u8(c.hiding, \"commitment.hiding\"),\n binding: u8(c.binding, \"commitment.binding\"),\n };\n}\n\nfunction operatorCommitment(c: OperatorCommitment): OperatorCommitment {\n return { identifier: s(c.identifier, \"identifier\"), commitment: commitment(c.commitment) };\n}\n\nexport function signingTarget(target: SigningTarget): SigningTarget {\n return {\n transaction: u8(target.transaction, \"target.transaction\"),\n inputIndex: n(target.inputIndex, \"target.inputIndex\"),\n prevouts: target.prevouts.map((p) => ({\n script: u8(p.script, \"prevout.script\"),\n amount: n(p.amount, \"prevout.amount\"),\n })),\n };\n}\n\nexport function frostSignJob(job: FrostSignJob): FrostSignJob {\n return {\n key: sparkKey(job.key),\n target: signingTarget(job.target),\n verifyingKey: u8(job.verifyingKey, \"verifyingKey\"),\n commitment: commitment(job.commitment),\n operatorCommitments: job.operatorCommitments.map(operatorCommitment),\n ...(job.adaptorPublicKey === undefined\n ? {}\n : { adaptorPublicKey: u8(job.adaptorPublicKey, \"adaptorPublicKey\") }),\n ...(job.exit === undefined\n ? {}\n : {\n exit: {\n connectorTx: u8(job.exit.connectorTx, \"exit.connectorTx\"),\n exitTx: u8(job.exit.exitTx, \"exit.exitTx\"),\n },\n }),\n };\n}\n\nexport function frostAggregateJob(job: FrostAggregateJob): FrostAggregateJob {\n return {\n key: sparkKey(job.key),\n target: signingTarget(job.target),\n verifyingKey: u8(job.verifyingKey, \"verifyingKey\"),\n commitment: commitment(job.commitment),\n signatureShare: u8(job.signatureShare, \"signatureShare\"),\n operators: job.operators.map((op) => ({\n identifier: s(op.identifier, \"identifier\"),\n commitment: commitment(op.commitment),\n signatureShare: u8(op.signatureShare, \"operator.signatureShare\"),\n publicKey: u8(op.publicKey, \"operator.publicKey\"),\n })),\n ...(job.adaptorPublicKey === undefined\n ? {}\n : { adaptorPublicKey: u8(job.adaptorPublicKey, \"adaptorPublicKey\") }),\n };\n}\n\nfunction depositClaimStatement(\n st: Extract<IdentityStatement, { kind: \"static-deposit-claim\" }>,\n): StaticDepositClaimStatement {\n return {\n kind: \"static-deposit-claim\",\n network: st.network,\n txid: u8(st.txid, \"txid\"),\n vout: n(st.vout, \"vout\"),\n creditAmountSats: n(st.creditAmountSats, \"creditAmountSats\"),\n sspSignature: u8(st.sspSignature, \"sspSignature\"),\n };\n}\n\nexport function identityStatement(statement: IdentityStatement): IdentityStatement {\n const { kind } = statement;\n if (kind === \"so-challenge\") {\n return { kind: \"so-challenge\", challenge: u8(statement.challenge, \"challenge\") };\n }\n if (kind === \"ssp-challenge\") {\n return {\n kind: \"ssp-challenge\",\n protectedChallenge: s(statement.protectedChallenge, \"protectedChallenge\"),\n };\n }\n if (kind === \"transfer-package\" || kind === \"claim-package\") {\n return {\n kind,\n transferId: s(statement.transferId, \"transferId\"),\n package: u8(statement.package, \"package\"),\n };\n }\n if (kind === \"static-deposit-claim\") {\n return depositClaimStatement(statement);\n }\n if (kind === \"static-deposit-refund\") {\n return {\n kind: \"static-deposit-refund\",\n network: statement.network,\n txid: u8(statement.txid, \"txid\"),\n vout: n(statement.vout, \"vout\"),\n amount: n(statement.amount, \"amount\"),\n target: signingTarget(statement.target),\n };\n }\n if (kind === \"watchtower-recovery\") {\n return {\n kind: \"watchtower-recovery\",\n network: statement.network,\n leafId: s(statement.leafId, \"leafId\"),\n target: signingTarget(statement.target),\n };\n }\n if (kind === \"spark-invoice\") {\n return { kind: \"spark-invoice\", invoice: u8(statement.invoice, \"invoice\") };\n }\n if (kind === \"token-transaction\") {\n return {\n kind: \"token-transaction\",\n partialTransaction: u8(statement.partialTransaction, \"partialTransaction\"),\n };\n }\n if (kind === \"lightning-address\") {\n return statement.action === \"register\"\n ? {\n kind: \"lightning-address\",\n action: \"register\",\n domain: s(statement.domain, \"domain\"),\n username: s(statement.username, \"username\"),\n description: s(statement.description, \"description\"),\n timestamp: n(statement.timestamp, \"timestamp\"),\n }\n : {\n kind: \"lightning-address\",\n action: \"unregister\",\n domain: s(statement.domain, \"domain\"),\n username: s(statement.username, \"username\"),\n timestamp: n(statement.timestamp, \"timestamp\"),\n };\n }\n return bad(\"statement kind\");\n}\nexport function prepareTransferRequest(req: PrepareTransferRequest): PrepareTransferRequest {\n return {\n transferId: s(req.transferId, \"transferId\"),\n leaves: req.leaves.map((leaf) => ({\n leafId: s(leaf.leafId, \"leafId\"),\n key: leafKey(leaf.key),\n receiverIdentityPublicKey: u8(leaf.receiverIdentityPublicKey, \"receiverIdentityPublicKey\"),\n })),\n };\n}\n\nexport function prepareClaimRequest(req: PrepareClaimRequest): PrepareClaimRequest {\n return {\n transferId: s(req.transferId, \"transferId\"),\n leaves: req.leaves.map((leaf) => ({\n leafId: s(leaf.leafId, \"leafId\"),\n secretCipher: u8(leaf.secretCipher, \"secretCipher\"),\n })),\n };\n}\n\nexport function htlcTimeoutRequest(req: HtlcTimeoutSignRequest): HtlcTimeoutSignRequest {\n return {\n transaction: u8(req.transaction, \"transaction\"),\n inputIndex: n(req.inputIndex, \"inputIndex\"),\n prevoutAmountSats: n(req.prevoutAmountSats, \"prevoutAmountSats\"),\n paymentHash: u8(req.paymentHash, \"paymentHash\"),\n hashLockPublicKey: u8(req.hashLockPublicKey, \"hashLockPublicKey\"),\n };\n}\n\nexport function staticDepositClaimRequest(\n req: StaticDepositClaimRequest,\n): StaticDepositClaimRequest {\n return { index: n(req.index, \"index\"), statement: depositClaimStatement(req.statement) };\n}\n","/**\n * The proxy SparkSigner: every method is one spark.* request on the kernel channel carrying the\n * account ref. List-shaped calls chunk by MAX_BATCH sequentially and concatenate in order — the\n * wire caps a batch at 64 while the signer interface allows up to 256 — exactly like the nostr\n * proxy's unwrapGiftWraps. `dispose` is a no-op: signer lifetime belongs to the kernel, which wipes\n * signers on lock and on wallet deletion.\n */\nimport type { SparkSigner } from \"@qntx/spark/signer\";\n\nimport type { WalletInternals } from \"../internal.ts\";\nimport { MAX_BATCH } from \"../protocol/core.ts\";\nimport type { SparkAccountRef } from \"../protocol/index.ts\";\nimport {\n frostAggregateJob,\n frostSignJob,\n htlcTimeoutRequest,\n identityStatement,\n leafKey,\n prepareClaimRequest,\n prepareTransferRequest,\n signingTarget,\n sparkKey,\n staticDepositClaimRequest,\n} from \"./wire.ts\";\n\nexport function proxySigner(account: SparkAccountRef, internals: WalletInternals): SparkSigner {\n return {\n identityPublicKey: async () => internals.call(\"spark.identityPublicKey\", { account }),\n\n publicKeys: async (keys) => {\n const wire = keys.map(leafKey);\n const results: Uint8Array[] = [];\n for (let start = 0; start < wire.length; start += MAX_BATCH) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- sequential on purpose: chunks round-trip in order\n const batch = await internals.call(\"spark.publicKeys\", {\n account,\n keys: wire.slice(start, start + MAX_BATCH),\n });\n results.push(...batch);\n }\n return results;\n },\n\n receivedPublicKeys: async (ciphertexts) => {\n const results: Uint8Array[] = [];\n for (let start = 0; start < ciphertexts.length; start += MAX_BATCH) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- sequential on purpose: chunks round-trip in order\n const batch = await internals.call(\"spark.receivedPublicKeys\", {\n account,\n ciphertexts: ciphertexts.slice(start, start + MAX_BATCH),\n });\n results.push(...batch);\n }\n return results;\n },\n\n newCommitments: async (count) => {\n const results: Array<Awaited<ReturnType<SparkSigner[\"newCommitments\"]>>[number]> = [];\n for (let remaining = count; remaining > 0; remaining -= MAX_BATCH) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- sequential on purpose: chunks round-trip in order\n const batch = await internals.call(\"spark.newCommitments\", {\n account,\n count: Math.min(MAX_BATCH, remaining),\n });\n results.push(...batch);\n }\n return results;\n },\n\n signFrost: async (jobs) => {\n const wire = jobs.map(frostSignJob);\n const results: Uint8Array[] = [];\n for (let start = 0; start < wire.length; start += MAX_BATCH) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- sequential on purpose: chunks round-trip in order\n const batch = await internals.call(\"spark.signFrost\", {\n account,\n jobs: wire.slice(start, start + MAX_BATCH),\n });\n results.push(...batch);\n }\n return results;\n },\n\n aggregateFrost: async (jobs) => {\n const wire = jobs.map(frostAggregateJob);\n const results: Uint8Array[] = [];\n for (let start = 0; start < wire.length; start += MAX_BATCH) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- sequential on purpose: chunks round-trip in order\n const batch = await internals.call(\"spark.aggregateFrost\", {\n account,\n jobs: wire.slice(start, start + MAX_BATCH),\n });\n results.push(...batch);\n }\n return results;\n },\n\n signIdentity: async (statement) =>\n internals.call(\"spark.signIdentity\", { account, statement: identityStatement(statement) }),\n\n signKeySpend: async (key, target) =>\n internals.call(\"spark.signKeySpend\", {\n account,\n key: sparkKey(key),\n target: signingTarget(target),\n }),\n\n signHtlcTimeout: async (request) =>\n internals.call(\"spark.signHtlcTimeout\", { account, request: htlcTimeoutRequest(request) }),\n\n prepareTransfer: async (request) =>\n internals.call(\"spark.prepareTransfer\", {\n account,\n request: prepareTransferRequest(request),\n }),\n\n prepareClaim: async (request) =>\n internals.call(\"spark.prepareClaim\", { account, request: prepareClaimRequest(request) }),\n\n prepareLightningReceive: async () =>\n internals.call(\"spark.prepareLightningReceive\", { account }),\n\n claimStaticDeposit: async (request) =>\n internals.call(\"spark.claimStaticDeposit\", {\n account,\n request: staticDepositClaimRequest(request),\n }),\n\n dispose: () => undefined,\n };\n}\n","/**\n * The spark module of @qntx/wallet: `spark(wallet)` returns the wallet's Spark API — proxy\n * SparkSigners backed by the enclave's signer pool. The API is memoized per wallet so repeated\n * calls return the same object (stable React identity); a foreign object is rejected because only a\n * Wallet from this package holds a registered channel.\n */\nimport { internalsOf } from \"../internal.ts\";\nimport type { WalletInternals } from \"../internal.ts\";\nimport type { Wallet } from \"../types.ts\";\nimport { proxySigner } from \"./signer.ts\";\nimport type { SparkApi } from \"./types.ts\";\n\nexport type { SparkAccountRef, SparkApi, SparkSigner } from \"./types.ts\";\n\nfunction createSparkApi(internals: WalletInternals): SparkApi {\n return {\n signer: (ref) => proxySigner(ref, internals),\n approve: async (params) =>\n internals.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const verify = await internals.resolveFactor(params.verify, transfer);\n return internals.call(\"spark.approve\", { ...params, verify });\n }),\n };\n}\n\nconst apis = new WeakMap<Wallet, SparkApi>();\n\nexport function spark(wallet: Wallet): SparkApi {\n const internals = internalsOf(wallet);\n let api = apis.get(wallet);\n if (api === undefined) {\n api = createSparkApi(internals);\n apis.set(wallet, api);\n }\n return api;\n}\n"],"mappings":";;;AAwBA,SAAS,IAAI,MAAqB;CAChC,MAAM,IAAI,YAAY,iBAAiB,qBAAqB,MAAM;AACpE;AAEA,MAAM,MAAM,GAAe,SAA8B,aAAa,aAAa,IAAI,IAAI,IAAI;AAC/F,MAAM,KAAK,GAAW,SAA0B,OAAO,MAAM,WAAW,IAAI,IAAI,IAAI;AACpF,MAAM,KAAK,GAAW,SAA0B,OAAO,MAAM,WAAW,IAAI,IAAI,IAAI;AAEpF,SAAgB,QAAQ,KAAiC;CACvD,IAAI,IAAI,SAAS,QACf,OAAO;EAAE,MAAM;EAAQ,QAAQ,EAAE,IAAI,QAAQ,QAAQ;CAAE;CAEzD,IAAI,IAAI,SAAS,kBACf,OAAO;EAAE,MAAM;EAAkB,OAAO,EAAE,IAAI,OAAO,OAAO;CAAE;CAEhE,OAAO,IAAI,eAAe;AAC5B;AAEA,SAAgB,SAAS,KAAyB;CAChD,IAAI,IAAI,SAAS,YACf,OAAO;EAAE,MAAM;EAAY,YAAY,GAAG,IAAI,YAAY,YAAY;CAAE;CAE1E,OAAO,QAAQ,GAAG;AACpB;AAEA,SAAgB,WAAW,GAAyC;CAClE,OAAO;EACL,QAAQ,GAAG,EAAE,QAAQ,mBAAmB;EACxC,SAAS,GAAG,EAAE,SAAS,oBAAoB;CAC7C;AACF;A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M,SAAS,MAAM,UAAU,cAAc,OAAO,QAAQ,CAAO,CAAC;GACpE,OAAO,UAAU,KAAK,iBAAiB;IAAE,GAAG;IAAQ;GAAO,CAAC;EAC9D,CAAC;CACL;AACF;AAEA,MAAM,uBAAO,IAAI,QAA0B;AAE3C,SAAgB,MAAM,QAA0B;CAC9C,MAAM,YAAY,YAAY,MAAM;CACpC,IAAI,MAAM,KAAK,IAAI,MAAM;CACzB,IAAI,QAAQ,KAAA,GAAW;EACrB,MAAM,eAAe,SAAS;EAC9B,KAAK,IAAI,QAAQ,GAAG;CACtB;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"spark.mjs","names":[],"sources":["../src/spark/wire.ts","../src/spark/signer.ts","../src/spark/index.ts"],"sourcesContent":["/**\n * Input projection for the proxy signer: every request value is rebuilt from its declared wire\n * fields only — callers (e.g. SparkClient) hand us library objects that may carry extra keys\n * (protobuf-es `$typeName`, branding), and the kernel's strict obj() validators reject any key not\n * in the shape. Unknown `kind`/`type` discriminants fail `invalid-input` here, before any request\n * is posted.\n */\nimport type {\n FrostAggregateJob,\n FrostSignJob,\n HtlcTimeoutSignRequest,\n IdentityStatement,\n OperatorCommitment,\n PrepareClaimRequest,\n PrepareTransferRequest,\n SigningCommitment,\n SigningTarget,\n SparkKey,\n SparkLeafKey,\n StaticDepositClaimRequest,\n StaticDepositClaimStatement,\n} from \"../protocol/index.ts\";\nimport { WalletError } from \"../types.ts\";\n\nfunction bad(what: string): never {\n throw new WalletError(\"invalid-input\", `spark: unexpected ${what}`);\n}\n\nconst u8 = (v: Uint8Array, what: string): Uint8Array => (v instanceof Uint8Array ? v : bad(what));\nconst s = (v: string, what: string): string => (typeof v === \"string\" ? v : bad(what));\nconst n = (v: number, what: string): number => (typeof v === \"number\" ? v : bad(what));\n\nexport function leafKey(key: SparkLeafKey): SparkLeafKey {\n if (key.type === \"leaf\") {\n return { type: \"leaf\", leafId: s(key.leafId, \"leafId\") };\n }\n if (key.type === \"static-deposit\") {\n return { type: \"static-deposit\", index: n(key.index, \"index\") };\n }\n return bad(\"leaf key type\");\n}\n\nexport function sparkKey(key: SparkKey): SparkKey {\n if (key.type === \"received\") {\n return { type: \"received\", ciphertext: u8(key.ciphertext, \"ciphertext\") };\n }\n return leafKey(key);\n}\n\nexport function commitment(c: SigningCommitment): SigningCommitment {\n return {\n hiding: u8(c.hiding, \"commitment.hiding\"),\n binding: u8(c.binding, \"commitment.binding\"),\n };\n}\n\nfunction operatorCommitment(c: OperatorCommitment): OperatorCommitment {\n return { identifier: s(c.identifier, \"identifier\"), commitment: commitment(c.commitment) };\n}\n\nexport function signingTarget(target: SigningTarget): SigningTarget {\n return {\n transaction: u8(target.transaction, \"target.transaction\"),\n inputIndex: n(target.inputIndex, \"target.inputIndex\"),\n prevouts: target.prevouts.map((p) => ({\n script: u8(p.script, \"prevout.script\"),\n amount: n(p.amount, \"prevout.amount\"),\n })),\n };\n}\n\nexport function frostSignJob(job: FrostSignJob): FrostSignJob {\n return {\n key: sparkKey(job.key),\n target: signingTarget(job.target),\n verifyingKey: u8(job.verifyingKey, \"verifyingKey\"),\n commitment: commitment(job.commitment),\n operatorCommitments: job.operatorCommitments.map(operatorCommitment),\n ...(job.adaptorPublicKey === undefined\n ? {}\n : { adaptorPublicKey: u8(job.adaptorPublicKey, \"adaptorPublicKey\") }),\n ...(job.exit === undefined\n ? {}\n : {\n exit: {\n connectorTx: u8(job.exit.connectorTx, \"exit.connectorTx\"),\n exitTx: u8(job.exit.exitTx, \"exit.exitTx\"),\n },\n }),\n };\n}\n\nexport function frostAggregateJob(job: FrostAggregateJob): FrostAggregateJob {\n return {\n key: sparkKey(job.key),\n target: signingTarget(job.target),\n verifyingKey: u8(job.verifyingKey, \"verifyingKey\"),\n commitment: commitment(job.commitment),\n signatureShare: u8(job.signatureShare, \"signatureShare\"),\n operators: job.operators.map((op) => ({\n identifier: s(op.identifier, \"identifier\"),\n commitment: commitment(op.commitment),\n signatureShare: u8(op.signatureShare, \"operator.signatureShare\"),\n publicKey: u8(op.publicKey, \"operator.publicKey\"),\n })),\n ...(job.adaptorPublicKey === undefined\n ? {}\n : { adaptorPublicKey: u8(job.adaptorPublicKey, \"adaptorPublicKey\") }),\n };\n}\n\nfunction depositClaimStatement(\n st: Extract<IdentityStatement, { kind: \"static-deposit-claim\" }>,\n): StaticDepositClaimStatement {\n return {\n kind: \"static-deposit-claim\",\n network: st.network,\n txid: u8(st.txid, \"txid\"),\n vout: n(st.vout, \"vout\"),\n creditAmountSats: n(st.creditAmountSats, \"creditAmountSats\"),\n sspSignature: u8(st.sspSignature, \"sspSignature\"),\n };\n}\n\nexport function identityStatement(statement: IdentityStatement): IdentityStatement {\n const { kind } = statement;\n if (kind === \"so-challenge\") {\n return { kind: \"so-challenge\", challenge: u8(statement.challenge, \"challenge\") };\n }\n if (kind === \"ssp-challenge\") {\n return {\n kind: \"ssp-challenge\",\n protectedChallenge: s(statement.protectedChallenge, \"protectedChallenge\"),\n };\n }\n if (kind === \"transfer-package\" || kind === \"claim-package\") {\n return {\n kind,\n transferId: s(statement.transferId, \"transferId\"),\n package: u8(statement.package, \"package\"),\n };\n }\n if (kind === \"static-deposit-claim\") {\n return depositClaimStatement(statement);\n }\n if (kind === \"static-deposit-refund\") {\n return {\n kind: \"static-deposit-refund\",\n network: statement.network,\n txid: u8(statement.txid, \"txid\"),\n vout: n(statement.vout, \"vout\"),\n amount: n(statement.amount, \"amount\"),\n target: signingTarget(statement.target),\n };\n }\n if (kind === \"watchtower-recovery\") {\n return {\n kind: \"watchtower-recovery\",\n network: statement.network,\n leafId: s(statement.leafId, \"leafId\"),\n target: signingTarget(statement.target),\n };\n }\n if (kind === \"spark-invoice\") {\n return { kind: \"spark-invoice\", invoice: u8(statement.invoice, \"invoice\") };\n }\n if (kind === \"token-transaction\") {\n return {\n kind: \"token-transaction\",\n partialTransaction: u8(statement.partialTransaction, \"partialTransaction\"),\n };\n }\n if (kind === \"lightning-address\") {\n return statement.action === \"register\"\n ? {\n kind: \"lightning-address\",\n action: \"register\",\n domain: s(statement.domain, \"domain\"),\n username: s(statement.username, \"username\"),\n description: s(statement.description, \"description\"),\n timestamp: n(statement.timestamp, \"timestamp\"),\n }\n : {\n kind: \"lightning-address\",\n action: \"unregister\",\n domain: s(statement.domain, \"domain\"),\n username: s(statement.username, \"username\"),\n timestamp: n(statement.timestamp, \"timestamp\"),\n };\n }\n return bad(\"statement kind\");\n}\nexport function prepareTransferRequest(req: PrepareTransferRequest): PrepareTransferRequest {\n return {\n transferId: s(req.transferId, \"transferId\"),\n leaves: req.leaves.map((leaf) => ({\n leafId: s(leaf.leafId, \"leafId\"),\n key: leafKey(leaf.key),\n receiverIdentityPublicKey: u8(leaf.receiverIdentityPublicKey, \"receiverIdentityPublicKey\"),\n })),\n };\n}\n\nexport function prepareClaimRequest(req: PrepareClaimRequest): PrepareClaimRequest {\n return {\n transferId: s(req.transferId, \"transferId\"),\n leaves: req.leaves.map((leaf) => ({\n leafId: s(leaf.leafId, \"leafId\"),\n secretCipher: u8(leaf.secretCipher, \"secretCipher\"),\n })),\n };\n}\n\nexport function htlcTimeoutRequest(req: HtlcTimeoutSignRequest): HtlcTimeoutSignRequest {\n return {\n transaction: u8(req.transaction, \"transaction\"),\n inputIndex: n(req.inputIndex, \"inputIndex\"),\n prevoutAmountSats: n(req.prevoutAmountSats, \"prevoutAmountSats\"),\n paymentHash: u8(req.paymentHash, \"paymentHash\"),\n hashLockPublicKey: u8(req.hashLockPublicKey, \"hashLockPublicKey\"),\n };\n}\n\nexport function staticDepositClaimRequest(\n req: StaticDepositClaimRequest,\n): StaticDepositClaimRequest {\n return { index: n(req.index, \"index\"), statement: depositClaimStatement(req.statement) };\n}\n","/**\n * The proxy SparkSigner: every method is one spark.* request on the kernel channel carrying the\n * account ref. List-shaped calls chunk by MAX_BATCH sequentially and concatenate in order — the\n * wire caps a batch at 64 while the signer interface allows up to 256 — exactly like the nostr\n * proxy's unwrapGiftWraps. `dispose` is a no-op: signer lifetime belongs to the kernel, which wipes\n * signers on lock and on wallet deletion.\n */\nimport type { SparkSigner } from \"@qntx/spark/signer\";\n\nimport type { WalletInternals } from \"../internal.ts\";\nimport { MAX_BATCH } from \"../protocol/core.ts\";\nimport type { SparkAccountRef } from \"../protocol/index.ts\";\nimport {\n frostAggregateJob,\n frostSignJob,\n htlcTimeoutRequest,\n identityStatement,\n leafKey,\n prepareClaimRequest,\n prepareTransferRequest,\n signingTarget,\n sparkKey,\n staticDepositClaimRequest,\n} from \"./wire.ts\";\n\nexport function proxySigner(account: SparkAccountRef, internals: WalletInternals): SparkSigner {\n return {\n identityPublicKey: async () => internals.call(\"spark.identityPublicKey\", { account }),\n\n publicKeys: async (keys) => {\n const wire = keys.map(leafKey);\n const results: Uint8Array[] = [];\n for (let start = 0; start < wire.length; start += MAX_BATCH) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- sequential on purpose: chunks round-trip in order\n const batch = await internals.call(\"spark.publicKeys\", {\n account,\n keys: wire.slice(start, start + MAX_BATCH),\n });\n results.push(...batch);\n }\n return results;\n },\n\n receivedPublicKeys: async (ciphertexts) => {\n const results: Uint8Array[] = [];\n for (let start = 0; start < ciphertexts.length; start += MAX_BATCH) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- sequential on purpose: chunks round-trip in order\n const batch = await internals.call(\"spark.receivedPublicKeys\", {\n account,\n ciphertexts: ciphertexts.slice(start, start + MAX_BATCH),\n });\n results.push(...batch);\n }\n return results;\n },\n\n newCommitments: async (count) => {\n const results: Array<Awaited<ReturnType<SparkSigner[\"newCommitments\"]>>[number]> = [];\n for (let remaining = count; remaining > 0; remaining -= MAX_BATCH) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- sequential on purpose: chunks round-trip in order\n const batch = await internals.call(\"spark.newCommitments\", {\n account,\n count: Math.min(MAX_BATCH, remaining),\n });\n results.push(...batch);\n }\n return results;\n },\n\n signFrost: async (jobs) => {\n const wire = jobs.map(frostSignJob);\n const results: Uint8Array[] = [];\n for (let start = 0; start < wire.length; start += MAX_BATCH) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- sequential on purpose: chunks round-trip in order\n const batch = await internals.call(\"spark.signFrost\", {\n account,\n jobs: wire.slice(start, start + MAX_BATCH),\n });\n results.push(...batch);\n }\n return results;\n },\n\n aggregateFrost: async (jobs) => {\n const wire = jobs.map(frostAggregateJob);\n const results: Uint8Array[] = [];\n for (let start = 0; start < wire.length; start += MAX_BATCH) {\n // oxlint-disable-next-line eslint/no-await-in-loop -- sequential on purpose: chunks round-trip in order\n const batch = await internals.call(\"spark.aggregateFrost\", {\n account,\n jobs: wire.slice(start, start + MAX_BATCH),\n });\n results.push(...batch);\n }\n return results;\n },\n\n signIdentity: async (statement) =>\n internals.call(\"spark.signIdentity\", { account, statement: identityStatement(statement) }),\n\n signKeySpend: async (key, target) =>\n internals.call(\"spark.signKeySpend\", {\n account,\n key: sparkKey(key),\n target: signingTarget(target),\n }),\n\n signHtlcTimeout: async (request) =>\n internals.call(\"spark.signHtlcTimeout\", { account, request: htlcTimeoutRequest(request) }),\n\n prepareTransfer: async (request) =>\n internals.call(\"spark.prepareTransfer\", {\n account,\n request: prepareTransferRequest(request),\n }),\n\n prepareClaim: async (request) =>\n internals.call(\"spark.prepareClaim\", { account, request: prepareClaimRequest(request) }),\n\n prepareLightningReceive: async () =>\n internals.call(\"spark.prepareLightningReceive\", { account }),\n\n claimStaticDeposit: async (request) =>\n internals.call(\"spark.claimStaticDeposit\", {\n account,\n request: staticDepositClaimRequest(request),\n }),\n\n dispose: () => undefined,\n };\n}\n","/**\n * The spark module of @qntx/wallet: `spark(wallet)` returns the wallet's Spark API — proxy\n * SparkSigners backed by the enclave's signer pool. The API is memoized per wallet so repeated\n * calls return the same object (stable React identity); a foreign object is rejected because only a\n * Wallet from this package holds a registered channel.\n */\nimport { internalsOf } from \"../internal.ts\";\nimport type { WalletInternals } from \"../internal.ts\";\nimport type { Wallet } from \"../types.ts\";\nimport { proxySigner } from \"./signer.ts\";\nimport type { SparkApi } from \"./types.ts\";\n\nexport type { SparkAccountRef, SparkApi, SparkSigner } from \"./types.ts\";\n\nfunction createSparkApi(internals: WalletInternals): SparkApi {\n return {\n signer: (ref) => proxySigner(ref, internals),\n approve: async (params) =>\n internals.withVerifying(async () => {\n const transfer: ArrayBuffer[] = [];\n const verify = await internals.resolveFactor(params.verify, transfer);\n return internals.call(\"spark.approve\", { ...params, verify });\n }),\n };\n}\n\nconst apis = new WeakMap<Wallet, SparkApi>();\n\nexport function spark(wallet: Wallet): SparkApi {\n const internals = internalsOf(wallet);\n let api = apis.get(wallet);\n if (api === undefined) {\n api = createSparkApi(internals);\n apis.set(wallet, api);\n }\n return api;\n}\n"],"mappings":";;;AAwBA,SAAS,IAAI,MAAqB;CAChC,MAAM,IAAI,YAAY,iBAAiB,qBAAqB,MAAM;AACpE;AAEA,MAAM,MAAM,GAAe,SAA8B,aAAa,aAAa,IAAI,IAAI,IAAI;AAC/F,MAAM,KAAK,GAAW,SAA0B,OAAO,MAAM,WAAW,IAAI,IAAI,IAAI;AACpF,MAAM,KAAK,GAAW,SAA0B,OAAO,MAAM,WAAW,IAAI,IAAI,IAAI;AAEpF,SAAgB,QAAQ,KAAiC;CACvD,IAAI,IAAI,SAAS,QACf,OAAO;EAAE,MAAM;EAAQ,QAAQ,EAAE,IAAI,QAAQ,QAAQ;CAAE;CAEzD,IAAI,IAAI,SAAS,kBACf,OAAO;EAAE,MAAM;EAAkB,OAAO,EAAE,IAAI,OAAO,OAAO;CAAE;CAEhE,OAAO,IAAI,eAAe;AAC5B;AAEA,SAAgB,SAAS,KAAyB;CAChD,IAAI,IAAI,SAAS,YACf,OAAO;EAAE,MAAM;EAAY,YAAY,GAAG,IAAI,YAAY,YAAY;CAAE;CAE1E,OAAO,QAAQ,GAAG;AACpB;AAEA,SAAgB,WAAW,GAAyC;CAClE,OAAO;EACL,QAAQ,GAAG,EAAE,QAAQ,mBAAmB;EACxC,SAAS,GAAG,EAAE,SAAS,oBAAoB;CAC7C;AACF;AAE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AS,MAAM,UAAU,cAAc,OAAO,QAAQ,CAAO,CAAC;GACpE,OAAO,UAAU,KAAK,iBAAiB;IAAE,GAAG;IAAQ;GAAO,CAAC;EAC9D,CAAC;CACL;AACF;AAEA,MAAM,uBAAO,IAAI,QAA0B;AAE3C,SAAgB,MAAM,QAA0B;CAC9C,MAAM,YAAY,YAAY,MAAM;CACpC,IAAI,MAAM,KAAK,IAAI,MAAM;CACzB,IAAI,QAAQ,KAAA,GAAW;EACrB,MAAM,eAAe,SAAS;EAC9B,KAAK,IAAI,QAAQ,GAAG;CACtB;CACA,OAAO;AACT"}
@@ -1,4 +1,3 @@
1
- //#region src/types.d.ts
2
1
  /** Public types of @qntx/wallet, per design/entry.mdx. Secret data never appears here. */
3
2
  type LockReason = "cold-start" | "user" | "idle" | "background" | "expired" | "crashed" | "invalidated";
4
3
  type FactorInfo = {
@@ -32,28 +31,16 @@ type WalletInfo = {
32
31
  type NostrKeyRef = {
33
32
  readonly kind: "derived";
34
33
  readonly walletId: string;
35
- readonly groupIndex: number;
36
- } | {
37
- readonly kind: "standalone";
38
- readonly id: string;
39
- } | {
40
- readonly kind: "nip46-client";
41
- readonly id: string;
34
+ readonly index: number;
42
35
  };
43
36
  type NostrKeyInfo = {
44
37
  readonly ref: NostrKeyRef;
45
38
  readonly publicKey: string;
46
- readonly origin: "derived" | "nsec" | "ncryptsec" | "generated" | "nip46-client";
47
- /**
48
- * Only standalone keys carry it: derived keys recover from the wallet, nip46-client keys are
49
- * ephemeral.
50
- */
51
- readonly backedUp?: boolean;
52
39
  readonly createdAt: number;
53
40
  };
54
- /** One entry of a `nostr.discover` result: the public key an account group would produce. */
41
+ /** One entry of a `nostr.discover` result: the public key an identity index produces. */
55
42
  type DerivedNostrKey = {
56
- readonly groupIndex: number;
43
+ readonly index: number;
57
44
  readonly publicKey: string;
58
45
  };
59
46
  type WalletErrorCode = "locked" | "cancelled" | "factor-unavailable" | "factor-invalidated" | "wrong-password" | "wrong-passkey" | "rate-limited" | "invalid-input" | "not-found" | "already-exists" | "conflict" | "unsupported" | "unavailable" | "integrity" | "approval-required" | "crashed";
@@ -69,7 +56,7 @@ type VaultState = "uninitialized" | "locked" | "unlocked" | "corrupted" | "unsup
69
56
  * Each protocol module contributes one section (here: `nostr`).
70
57
  */
71
58
  type StatusPayload = {
72
- readonly protocol: 1;
59
+ readonly protocol: 2;
73
60
  readonly vault: VaultState;
74
61
  readonly factors: ReadonlyArray<FactorInfo>;
75
62
  readonly wallets: ReadonlyArray<WalletInfo>;
@@ -138,10 +125,6 @@ type AutoLockPolicy = {
138
125
  readonly platform: "web";
139
126
  readonly idleMinutes: 5 | 15 | 60;
140
127
  };
141
- type WalletOptions = {
142
- readonly passkey: PasskeyConfig;
143
- readonly autoLock: AutoLockPolicy;
144
- };
145
128
  type WalletSnapshot = {
146
129
  readonly vault: VaultState;
147
130
  readonly lockReason: LockReason | undefined;
@@ -224,6 +207,5 @@ type Wallet = {
224
207
  readonly backup: BackupApi;
225
208
  readonly destroy: () => Promise<void>;
226
209
  };
227
- //#endregion
228
- export { WalletSnapshot as C, WalletOptions as S, VaultState as _, DerivedNostrKey as a, WalletErrorCode as b, InitialFactor as c, NostrKeyInfo as d, NostrKeyRef as f, VaultApi as g, UnlockFactor as h, DataKeyApi as i, LockReason as l, StatusPayload as m, BackupApi as n, ExportedSecret as o, PasskeyConfig as p, BackupInfo as r, FactorInfo as s, AutoLockPolicy as t, MnemonicDraft as u, Wallet as v, WalletsApi as w, WalletInfo as x, WalletError as y };
229
- //# sourceMappingURL=types-BD9fuAUj.d.mts.map
210
+ export { WalletsApi as C, WalletSnapshot as S, VaultState as _, DerivedNostrKey as a, WalletErrorCode as b, InitialFactor as c, NostrKeyInfo as d, NostrKeyRef as f, VaultApi as g, UnlockFactor as h, DataKeyApi as i, LockReason as l, StatusPayload as m, BackupApi as n, ExportedSecret as o, PasskeyConfig as p, BackupInfo as r, FactorInfo as s, AutoLockPolicy as t, MnemonicDraft as u, Wallet as v, WalletInfo as x, WalletError as y };
211
+ //# sourceMappingURL=types-CIYT5uFj.d.mts.map
package/dist/types.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { C as WalletSnapshot, S as WalletOptions, _ as VaultState, a as DerivedNostrKey, b as WalletErrorCode, c as InitialFactor, d as NostrKeyInfo, f as NostrKeyRef, g as VaultApi, h as UnlockFactor, i as DataKeyApi, l as LockReason, m as StatusPayload, n as BackupApi, o as ExportedSecret, p as PasskeyConfig, r as BackupInfo, s as FactorInfo, t as AutoLockPolicy, u as MnemonicDraft, v as Wallet, w as WalletsApi, x as WalletInfo, y as WalletError } from "./types-BD9fuAUj.mjs";
2
- export { AutoLockPolicy, BackupApi, BackupInfo, DataKeyApi, DerivedNostrKey, ExportedSecret, FactorInfo, InitialFactor, LockReason, MnemonicDraft, NostrKeyInfo, NostrKeyRef, PasskeyConfig, StatusPayload, UnlockFactor, VaultApi, VaultState, Wallet, WalletError, WalletErrorCode, WalletInfo, WalletOptions, WalletSnapshot, WalletsApi };
1
+ import { C as WalletsApi, S as WalletSnapshot, _ as VaultState, a as DerivedNostrKey, b as WalletErrorCode, c as InitialFactor, d as NostrKeyInfo, f as NostrKeyRef, g as VaultApi, h as UnlockFactor, i as DataKeyApi, l as LockReason, m as StatusPayload, n as BackupApi, o as ExportedSecret, p as PasskeyConfig, r as BackupInfo, s as FactorInfo, t as AutoLockPolicy, u as MnemonicDraft, v as Wallet, x as WalletInfo, y as WalletError } from "./types-CIYT5uFj.mjs";
2
+ export { AutoLockPolicy, BackupApi, BackupInfo, DataKeyApi, DerivedNostrKey, ExportedSecret, FactorInfo, InitialFactor, LockReason, MnemonicDraft, NostrKeyInfo, NostrKeyRef, PasskeyConfig, StatusPayload, UnlockFactor, VaultApi, VaultState, Wallet, WalletError, WalletErrorCode, WalletInfo, WalletSnapshot, WalletsApi };
package/dist/types.mjs CHANGED
@@ -1,4 +1,4 @@
1
- //#region src/types.ts
1
+ // src/types.ts
2
2
  /** One error class for the whole API; `code` carries the distinction. Messages never echo input. */
3
3
  var WalletError = class extends Error {
4
4
  code;
@@ -10,7 +10,6 @@ var WalletError = class extends Error {
10
10
  this.retryAt = retryAt;
11
11
  }
12
12
  };
13
- //#endregion
14
13
  export { WalletError };
15
14
 
16
15
  //# sourceMappingURL=types.mjs.map