@qntx/wallet 0.4.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{index-Dhf6wGjQ.d.mts → chains-D_jfwTPT.d.mts} +299 -117
- package/dist/chains.d.mts +14 -0
- package/dist/chains.mjs +70 -0
- package/dist/chains.mjs.map +1 -0
- package/dist/{secret-IcTjjaX0.mjs → channel-ChYtMklb.mjs} +19 -155
- package/dist/channel-ChYtMklb.mjs.map +1 -0
- package/dist/{core-QJ66nLLG.mjs → core-Dmz5SbyJ.mjs} +55 -23
- package/dist/core-Dmz5SbyJ.mjs.map +1 -0
- package/dist/host.d.mts +17 -4
- package/dist/host.mjs +37 -9
- package/dist/host.mjs.map +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +2 -2
- package/dist/nostr.d.mts +1 -1
- package/dist/nostr.mjs +2 -1
- package/dist/nostr.mjs.map +1 -1
- package/dist/{protocol-D9xBuMzq.mjs → protocol-DvzlUKB8.mjs} +147 -3
- package/dist/protocol-DvzlUKB8.mjs.map +1 -0
- package/dist/protocol.d.mts +3 -3
- package/dist/protocol.mjs +3 -3
- package/dist/secret-BiyX0Hus.mjs +203 -0
- package/dist/secret-BiyX0Hus.mjs.map +1 -0
- package/dist/spark.d.mts +2 -2
- package/dist/{types-D4OUjGVS.d.mts → types-BD9fuAUj.d.mts} +9 -2
- package/dist/types.d.mts +1 -1
- package/dist/types.mjs.map +1 -1
- package/package.json +19 -7
- package/dist/core-QJ66nLLG.mjs.map +0 -1
- package/dist/protocol-D9xBuMzq.mjs.map +0 -1
- package/dist/secret-IcTjjaX0.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"protocol-D9xBuMzq.mjs","names":[],"sources":["../src/protocol/backup.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 readonly importedNostrKeyCount: number;\n readonly importedChainKeyCount: number;\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 importedNostrKeyCount: int(0, 10_000),\n importedChainKeyCount: int(0, 10_000),\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 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 groupIndex,\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 sessionId,\n walletErrorCode,\n walletId,\n} from \"./core.ts\";\nimport type { Factor } from \"./core.ts\";\nimport type { MethodSpec, NullValue } from \"./index.ts\";\nimport type { Validator } from \"./validate.ts\";\nimport { arr, bool, 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 NostrImportInput =\n | { readonly kind: \"nsec\"; readonly nsec: Uint8Array }\n | { readonly kind: \"ncryptsec\"; readonly ncryptsec: string; readonly password: Uint8Array };\n\nexport type NostrExportFormat =\n | { readonly kind: \"nsec\" }\n | { readonly kind: \"ncryptsec\"; readonly password: Uint8Array };\n\n/** One \"import/generate a key\" result: the key's public info plus the session it may have opened. */\nexport type KeyResult = { readonly key: NostrKeyInfo; readonly session: string };\n\nexport type UnwrapResult = { readonly ok: Rumor } | { readonly err: WalletErrorCode };\n\nconst hex128: Validator<string> = str(128, /^[0-9a-f]{128}$/);\n\nconst nostrKeyRef = union(\n obj({ kind: literal(\"derived\"), walletId, groupIndex }),\n obj({ kind: literal(\"standalone\"), id: publicKey }),\n obj({ kind: literal(\"nip46-client\"), id: publicKey }),\n);\n\n// `backedUp` exists only on the standalone origins — the kernel never emits it for derived or\n// nip46-client keys, and a peer that does is untrustworthy.\nexport const nostrKeyInfo: Validator<NostrKeyInfo> = union(\n obj({\n ref: nostrKeyRef,\n publicKey,\n origin: union(literal(\"nsec\"), literal(\"ncryptsec\"), literal(\"generated\")),\n backedUp: bool,\n createdAt: safeTime,\n }),\n obj({\n ref: nostrKeyRef,\n publicKey,\n origin: union(literal(\"derived\"), literal(\"nip46-client\")),\n createdAt: safeTime,\n }),\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 keyResult: Validator<KeyResult> = obj({ key: nostrKeyInfo, session: sessionId });\n\nconst derivedNostrKey: Validator<DerivedNostrKey> = obj({ groupIndex, 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 nostrImportInput: Validator<NostrImportInput> = union(\n obj({ kind: literal(\"nsec\"), nsec: bytes(1, 256) }),\n obj({ kind: literal(\"ncryptsec\"), ncryptsec: str(512, /^ncryptsec1/), password: bytes(1, 1024) }),\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 groupIndex: number },\n NostrKeyInfo\n >;\n readonly \"nostr.importKey\": MethodSpec<\n { readonly input: NostrImportInput; readonly factor?: Factor },\n KeyResult\n >;\n readonly \"nostr.generateKey\": MethodSpec<{ readonly factor?: Factor }, KeyResult>;\n readonly \"nostr.createNip46ClientKey\": MethodSpec<NullValue, NostrKeyInfo>;\n readonly \"nostr.removeKey\": MethodSpec<\n { readonly publicKey: string; readonly verify?: Factor },\n NullValue\n >;\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.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: groupIndex, 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, groupIndex }),\n result: nostrKeyInfo,\n },\n \"nostr.importKey\": {\n session: false,\n presence: true,\n params: obj({ input: nostrImportInput, factor: opt(factor) }),\n result: keyResult,\n },\n \"nostr.generateKey\": {\n session: false,\n presence: true,\n params: obj({ factor: opt(factor) }),\n result: keyResult,\n },\n \"nostr.createNip46ClientKey\": {\n session: true,\n presence: false,\n params: nullValue,\n result: nostrKeyInfo,\n },\n \"nostr.removeKey\": {\n session: true,\n presence: true,\n params: obj({ publicKey, verify: opt(factor) }),\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};\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 } from \"./core.ts\";\nimport type { MethodSpec } from \"./index.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 */\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 | {\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\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 | {\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\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 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 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);\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 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);\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 {\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 { Validator } from \"./validate.ts\";\n\nexport type { WalletErrorCode } from \"../types.ts\";\n\nexport const PROTOCOL_VERSION = 1;\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\n// oxlint-disable-next-line typescript/no-restricted-types -- JSON null is a protocol value\nexport type NullValue = null;\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: 1;\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: 1; readonly id: number; readonly ok: ProtocolValue }\n | { readonly v: 1; readonly id: number; readonly err: ErrorPayload };\n\nexport type KernelEvent =\n | { readonly v: 1; readonly event: \"status\"; readonly status: StatusPayload }\n | { readonly v: 1; 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(1),\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 SPARK_METHODS = {\n status: {\n session: false,\n presence: false,\n params: nullValue,\n result: statusPayload,\n },\n ...CORE_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(1), event: literal(\"status\"), status: statusPayload }),\n obj({ v: literal(1), 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 { 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 { BackupFactor, CreatedResult, Factor } from \"./core.ts\";\nexport type {\n BackupEnvelopeFactor,\n BackupEnvelopeWire,\n BackupHeaderWallet,\n BackupHeaderWire,\n BackupInfo,\n} from \"./backup.ts\";\nexport type {\n KeyResult,\n NostrExportFormat,\n NostrImportInput,\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,o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A,MAAM,gBAA0C,IAAI;CAClD,UAAU,QAAQ,CAAC;CACnB,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,UAIY;CACvB,QAAQ;EACN,SAAS;EACT,UAAU;EACV,QAAQ;EACR,QAAQ;CACV;CACA,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,QAAQ,CAAC;CAAG,OAAO,QAAQ,QAAQ;CAAG,QAAQ;AAAc,CAAC,GACtE,IAAI;CAAE,GAAG,QAAQ,CAAC;CAAG,OAAO,QAAQ,QAAQ;CAAG,QAAQ;AAAW,CAAC,CACrE;;AAGA,MAAa,gBACX"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"secret-IcTjjaX0.mjs","names":[],"sources":["../src/channel.ts","../src/factors.ts","../src/secret.ts"],"sourcesContent":["/**\n * The host side of the kernel channel (design/enclave.mdx \"协议与传输\"): port lifecycle, respawn,\n * request/response correlation and wire validation. Internal to the `./host` subpath — reserved for\n * host packages (wallet-worker, wallet-native); applications must not use it.\n */\nimport {\n isProtocolValue,\n kernelEvent,\n MAX_REQUEST_BYTES,\n METHODS,\n PROTOCOL_VERSION,\n requestBytes,\n responseError,\n ValidationError,\n} from \"./protocol/index.ts\";\nimport type { MethodName, ParamsOf, ProtocolValue, ResultOf } from \"./protocol/index.ts\";\nimport { WalletError } from \"./types.ts\";\nimport type { LockReason, StatusPayload } from \"./types.ts\";\n\n/** The host packages' side of the kernel channel (worker, JSI runtime, in-process test port). */\nexport type MainPort = {\n readonly post: (message: ProtocolValue, transfer: ArrayBuffer[]) => void;\n readonly listen: (handler: (message: unknown) => void) => () => void;\n readonly onExit: (handler: () => void) => () => void;\n readonly terminate: () => void;\n};\n\nexport function integrity(message: string): WalletError {\n return new WalletError(\"integrity\", message);\n}\n\n/** Schedules `fn` after `delayMs` and returns a cancel function — injected by the host package. */\nexport type SetTimer = (delayMs: number, fn: () => void) => () => void;\n\n/**\n * A silent kernel is a wedged kernel: the request at the head of the kernel's serial queue gets\n * this long before the port is replaced. Requests still queued behind it are not timed — the kernel\n * answers in order, so only the head can wedge.\n */\nconst CALL_TIMEOUT_MS = 60_000;\n\ntype Pending = {\n readonly method: MethodName;\n readonly resolve: (value: unknown) => void;\n readonly reject: (error: WalletError) => void;\n};\n\n/**\n * State callbacks: the channel owns the port lifecycle and message ordering; the wallet owns the\n * snapshot state these events describe. `onLocked`/`onCrashed` fire before the port is replaced so\n * the wallet can stamp the lock reason.\n */\nexport type ChannelHandlers = {\n readonly onStatus: (status: StatusPayload) => void;\n readonly onLocked: (reason: LockReason) => void;\n readonly onCrashed: () => void;\n};\n\nexport class Channel {\n /** The live kernel session; attached to every request and cleared whenever it is gone. */\n session: string | undefined;\n\n private port: MainPort | undefined;\n private unlisten: (() => void) | undefined;\n private unlistenExit: (() => void) | undefined;\n private generation = 0;\n\n private readonly pending = new Map<number, Pending>();\n /** Times the earliest pending request — the one the kernel is working on. */\n private watchdog: { readonly id: number; readonly cancel: () => void } | undefined;\n private nextId = 1;\n private destroyed = false;\n /** Terminal state: the kernel peer proved untrustworthy; every later call fails with it. */\n private broken: WalletError | undefined;\n /** An unlocked status held back until the session it belongs to is installed. */\n private deferredStatus: StatusPayload | undefined;\n /** Whether the current port has delivered its first valid status event. */\n private portReady = false;\n private readyPromise: Promise<void>;\n private resolveReady: (() => void) | undefined;\n private rejectReady: ((error: WalletError) => void) | undefined;\n\n private readonly spawn: () => MainPort;\n private readonly handlers: ChannelHandlers;\n private readonly setTimer: SetTimer;\n\n constructor(spawn: () => MainPort, handlers: ChannelHandlers, setTimer: SetTimer) {\n this.spawn = spawn;\n this.handlers = handlers;\n this.setTimer = setTimer;\n this.readyPromise = new Promise((resolve, reject) => {\n this.resolveReady = resolve;\n this.rejectReady = reject;\n });\n }\n\n /** Spawns the first kernel and resolves once its initial status event arrives. */\n async start(): Promise<void> {\n this.respawn();\n return this.readyPromise;\n }\n\n /** Resolves when the current port has delivered its first status event. */\n get ready(): Promise<void> {\n return this.readyPromise;\n }\n\n /**\n * Terminates the current port and spawns a fresh secret runtime, keeping the vault image (the\n * host-side store survives the worker). \"Lock destroys the enclave.\"\n */\n respawn(): void {\n if (this.destroyed || this.broken !== undefined) {\n return;\n }\n this.unlisten?.();\n this.unlistenExit?.();\n this.port?.terminate();\n this.port = undefined;\n this.session = undefined;\n this.deferredStatus = undefined;\n this.watchdog?.cancel();\n this.watchdog = undefined;\n this.portReady = false;\n\n const generation = ++this.generation;\n // Settle the previous gate: a call still awaiting it must not hang — the kernel it was\n // waiting for is gone, so \"locked\" (session destroyed) applies.\n // oxlint-disable-next-line promise/prefer-await-to-then -- marks the stale gate as handled without swallowing it for awaiters\n void this.readyPromise.catch(() => undefined);\n this.rejectReady?.(new WalletError(\"locked\", \"the kernel restarted\"));\n this.readyPromise = new Promise((resolve, reject) => {\n this.resolveReady = resolve;\n this.rejectReady = reject;\n });\n // A rejected gate with nobody awaiting it (e.g. destroy() mid-boot) must not surface as\n // an unhandled rejection; callers that do await still observe the rejection.\n // oxlint-disable-next-line promise/prefer-await-to-then -- marks the gate as handled without swallowing it for awaiters\n void this.readyPromise.catch(() => undefined);\n try {\n const port = this.spawn();\n this.unlisten = port.listen((message) => {\n this.onMessage(message, generation);\n });\n this.unlistenExit = port.onExit(() => {\n this.onExit(generation);\n });\n this.port = port;\n } catch {\n // A host that cannot spawn has no kernel to talk to — fail closed like a dead peer.\n this.breakChannel(integrity(\"could not spawn the kernel port\"));\n }\n }\n\n private onExit(generation: number): void {\n if (generation !== this.generation || this.destroyed || this.broken !== undefined) {\n return;\n }\n this.session = undefined;\n this.deferredStatus = undefined;\n if (!this.portReady) {\n // Death before the first valid status means the runtime never ran honestly (worker\n // blocked by CSP, a script that fails to load, protocol skew): no respawn — a fresh\n // spawn would face the same broken peer. Initial connect rejects with integrity;\n // a respawned port dying this way breaks the wallet.\n this.breakChannel(integrity(\"the kernel port died before its first status\"));\n return;\n }\n // A proven port dying is a crash: fail everything in flight, mark it, respawn.\n this.failPending(new WalletError(\"crashed\", \"the kernel port exited\"));\n this.handlers.onCrashed();\n this.respawn();\n }\n\n /**\n * Immediate host-side lock: no kernel round trip. Fails everything in flight with `locked`, drops\n * the session, reports the user lock, and replaces the port — the old worker can never answer\n * again. Safe mid-commit: IndexedDB transactions are atomic.\n */\n lockNow(): void {\n if (this.destroyed || this.broken !== undefined) {\n return;\n }\n this.session = undefined;\n this.deferredStatus = undefined;\n this.failPending(new WalletError(\"locked\", \"the vault locked\"));\n this.handlers.onLocked(\"user\");\n this.respawn();\n }\n\n private onCallTimeout(): void {\n if (this.destroyed || this.broken !== undefined) {\n return;\n }\n this.failPending(new WalletError(\"crashed\", \"the kernel did not answer in time\"));\n this.handlers.onCrashed();\n this.respawn();\n }\n\n private failPending(error: WalletError): void {\n this.watchdog?.cancel();\n this.watchdog = undefined;\n for (const [, pending] of this.pending) {\n pending.reject(error);\n }\n this.pending.clear();\n }\n\n /** (Re)arms the watchdog on `pending`'s insertion-ordered head, or clears it when empty. */\n private armWatchdog(): void {\n this.watchdog?.cancel();\n const head = this.pending.keys().next().value;\n this.watchdog =\n head === undefined\n ? undefined\n : {\n id: head,\n cancel: this.setTimer(CALL_TIMEOUT_MS, () => {\n this.onCallTimeout();\n }),\n };\n }\n\n /** Removes the pending entry, re-timing the watchdog when the head settled, then runs `fn`. */\n private settle(id: number, fn: (pending: Pending) => void): void {\n const pending = this.pending.get(id);\n if (pending !== undefined) {\n this.pending.delete(id);\n if (this.watchdog?.id === id) {\n this.armWatchdog();\n }\n fn(pending);\n }\n }\n\n /**\n * Terminal failure: terminate the port, fail everything in flight, and latch `broken` so every\n * later call rejects with the same error. The snapshot is left untouched.\n */\n private breakChannel(error: WalletError): void {\n this.broken = error;\n this.session = undefined;\n this.deferredStatus = undefined;\n this.failPending(error);\n this.rejectReady?.(error);\n this.unlisten?.();\n this.unlistenExit?.();\n this.port?.terminate();\n this.port = undefined;\n this.generation++; // anything the dead port still emits is stale\n }\n\n /** A malformed protocol peer cannot be trusted — it fails closed, never respawns. */\n private poison(reason: string): void {\n this.breakChannel(integrity(reason));\n }\n\n private onMessage(raw: unknown, generation: number): void {\n if (generation !== this.generation) {\n return; // a dead port must not steer the wallet\n }\n if (\n !isProtocolValue(raw) ||\n typeof raw !== \"object\" ||\n raw === null ||\n raw instanceof Uint8Array ||\n Array.isArray(raw)\n ) {\n this.poison(\"malformed kernel message\");\n return;\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- narrowed to a plain record above\n const message = raw as Readonly<Record<string, ProtocolValue>>;\n if (\"id\" in message) {\n this.onResponse(message);\n return;\n }\n if (\"event\" in message) {\n let event;\n try {\n event = kernelEvent(message);\n } catch (error) {\n if (!(error instanceof ValidationError)) {\n throw error;\n }\n this.poison(\"malformed kernel event\");\n return;\n }\n if (event.event === \"status\") {\n if (event.status.vault !== \"unlocked\") {\n this.session = undefined;\n this.deferredStatus = undefined;\n this.handlers.onStatus(event.status);\n } else if (this.session === undefined) {\n // The unlock/create response has not delivered the session yet — subscribers must\n // never see \"unlocked\" while requests would go out sessionless.\n this.deferredStatus = event.status;\n } else {\n this.handlers.onStatus(event.status);\n }\n this.portReady = true;\n this.resolveReady?.();\n } else {\n // A locked event destroys the enclave: drop the session, tear down the port, respawn.\n this.session = undefined;\n this.deferredStatus = undefined;\n this.handlers.onLocked(event.reason);\n this.failPending(new WalletError(\"locked\", \"the vault locked\"));\n this.respawn();\n }\n return;\n }\n this.poison(\"unrecognised kernel message\");\n }\n\n private onResponse(message: Readonly<Record<string, ProtocolValue>>): void {\n const { id } = message;\n if (typeof id !== \"number\" || !Number.isSafeInteger(id) || message[\"v\"] !== PROTOCOL_VERSION) {\n this.poison(\"malformed response envelope\");\n return;\n }\n const pending = this.pending.get(id);\n if (pending === undefined) {\n // Includes UNATTRIBUTED_ID 0 — never a live request.\n this.poison(\"response for an unknown request\");\n return;\n }\n const hasOk = \"ok\" in message;\n const hasErr = \"err\" in message;\n if (hasOk === hasErr) {\n // Keep the entry so poison's failPending rejects this caller too.\n this.poison(\"malformed response body\");\n return;\n }\n if (hasErr) {\n try {\n const err = responseError(message[\"err\"]);\n this.settle(id, (p) => {\n p.reject(\n new WalletError(\n err.code,\n `kernel returned ${err.code}`,\n typeof err.retryAt === \"number\" ? err.retryAt : undefined,\n ),\n );\n });\n } catch (error) {\n if (!(error instanceof ValidationError)) {\n throw error;\n }\n this.poison(\"malformed error payload\");\n }\n return;\n }\n try {\n const result = METHODS[pending.method].result(message[\"ok\"]);\n this.settle(id, (p) => {\n p.resolve(result);\n });\n } catch (error) {\n if (!(error instanceof ValidationError)) {\n throw error;\n }\n this.poison(\"invalid result from the kernel\");\n }\n }\n\n /**\n * Sends one request and resolves with the validated result. The kernel answers with status →\n * response → locked, so the snapshot is already current when this promise settles.\n */\n async call<M extends MethodName>(\n method: M,\n params: ParamsOf<M>,\n transfer: ArrayBuffer[] = [],\n ): Promise<ResultOf<M>> {\n await this.readyPromise;\n if (this.broken !== undefined) {\n throw this.broken;\n }\n const { port } = this;\n if (this.destroyed || port === undefined) {\n throw new WalletError(\"locked\", \"wallet is destroyed\");\n }\n const id = this.nextId++;\n const message: Record<string, ProtocolValue> = { v: PROTOCOL_VERSION, id, method, params };\n // Attach the session whenever we hold one: the create/import methods are session:false\n // in the table because the rule is dynamic (required exactly when the vault is initialized).\n if (this.session !== undefined) {\n message[\"session\"] = this.session;\n }\n // The whole envelope counts against the cap — an oversized request never reaches the port.\n if (requestBytes(message) > MAX_REQUEST_BYTES) {\n throw new WalletError(\"invalid-input\", \"request exceeds the size limit\");\n }\n const result = await new Promise<unknown>((resolve, reject) => {\n this.pending.set(id, { method, resolve, reject });\n if (this.watchdog === undefined) {\n // Pending went empty → non-empty: this request is the head the kernel works on next.\n this.armWatchdog();\n }\n try {\n port.post(message, transfer);\n } catch {\n this.pending.delete(id);\n if (this.watchdog?.id === id) {\n this.armWatchdog();\n }\n reject(integrity(\"the kernel port refused the message\"));\n }\n });\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- validated by METHODS[method].result\n return result as ResultOf<M>;\n }\n\n /** Fires the deferred unlocked status, if any, once the session is installed. */\n flushStatus(): void {\n const status = this.deferredStatus;\n if (status !== undefined && this.session !== undefined) {\n this.deferredStatus = undefined;\n this.handlers.onStatus(status);\n }\n }\n\n /** Terminates the port without respawn; later calls fail \"locked\". */\n destroy(): void {\n if (this.destroyed) {\n return;\n }\n this.destroyed = true;\n this.unlisten?.();\n this.unlistenExit?.();\n this.port?.terminate();\n this.port = undefined;\n this.session = undefined;\n this.deferredStatus = undefined;\n this.rejectReady?.(new WalletError(\"locked\", \"wallet is destroyed\"));\n this.failPending(new WalletError(\"locked\", \"wallet is destroyed\"));\n }\n}\n","/**\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 { Factor, BackupFactor } 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/** What factor resolution needs from the wallet: config, the ceremony, live factor records. */\nexport type FactorSource = {\n readonly passkey: PasskeyConfig;\n readonly ceremony: PasskeyCeremony | undefined;\n readonly factors: () => ReadonlyArray<FactorInfo>;\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 * Resolves a public `UnlockFactor` to wire backup-factor material: the passkey ceremony evaluates\n * the PRF over `backupSalt` (purpose `0x02`), producing `prfBackup` instead of the vault `prf`.\n */\nexport async function resolveBackupFactor(\n source: FactorSource,\n factor: UnlockFactor,\n transfer: ArrayBuffer[],\n): Promise<BackupFactor> {\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: backupSaltBytes(source) },\n });\n return {\n kind: \"passkey\",\n credentialId: wireBytes(result.credentialId, transfer),\n prfBackup: wireBytes(result.first, transfer, true),\n };\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 (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.\n */\nexport async function resolveInitialFactor(\n source: FactorSource,\n factor: InitialFactor | undefined,\n transfer: ArrayBuffer[],\n walletCeremony?: PrfResult,\n): Promise<Factor> {\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 new WalletError(\"factor-unavailable\", \"hardware factors exist only on React Native\");\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":";;;;;;;;;;AA2BA,SAAgB,UAAU,SAA8B;CACtD,OAAO,IAAI,YAAY,aAAa,OAAO;AAC7C;;;;;;AAUA,MAAM,kBAAkB;AAmBxB,IAAa,UAAb,MAAqB;;CAEnB;CAEA;CACA;CACA;CACA,aAAqB;CAErB,0BAA2B,IAAI,IAAqB;;CAEpD;CACA,SAAiB;CACjB,YAAoB;;CAEpB;;CAEA;;CAEA,YAAoB;CACpB;CACA;CACA;CAEA;CACA;CACA;CAEA,YAAY,OAAuB,UAA2B,UAAoB;EAChF,KAAK,QAAQ;EACb,KAAK,WAAW;EAChB,KAAK,WAAW;EAChB,KAAK,eAAe,IAAI,SAAS,SAAS,WAAW;GACnD,KAAK,eAAe;GACpB,KAAK,cAAc;EACrB,CAAC;CACH;;CAGA,MAAM,QAAuB;EAC3B,KAAK,QAAQ;EACb,OAAO,KAAK;CACd;;CAGA,IAAI,QAAuB;EACzB,OAAO,KAAK;CACd;;;;;CAMA,UAAgB;EACd,IAAI,KAAK,aAAa,KAAK,WAAW,KAAA,GACpC;EAEF,KAAK,WAAW;EAChB,KAAK,eAAe;EACpB,KAAK,MAAM,UAAU;EACrB,KAAK,OAAO,KAAA;EACZ,KAAK,UAAU,KAAA;EACf,KAAK,iBAAiB,KAAA;EACtB,KAAK,UAAU,OAAO;EACtB,KAAK,WAAW,KAAA;EAChB,KAAK,YAAY;EAEjB,MAAM,aAAa,EAAE,KAAK;EAI1B,KAAU,aAAa,YAAY,KAAA,CAAS;EAC5C,KAAK,cAAc,IAAI,YAAY,UAAU,sBAAsB,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