@qntx/wallet 0.13.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +145 -22
- package/dist/backup-CLzMs8DP.mjs +51 -0
- package/dist/backup-CLzMs8DP.mjs.map +1 -0
- package/dist/card.d.mts +12 -0
- package/dist/card.mjs +119 -0
- package/dist/card.mjs.map +1 -0
- package/dist/{chains-B-FmFmuV.d.mts → chains-u1M0CWkT.d.mts} +148 -31
- package/dist/chains.d.mts +11 -4
- package/dist/chains.mjs +19 -67
- package/dist/chains.mjs.map +1 -1
- package/dist/{channel-BLwce5hh.mjs → channel-BCZXU3pt.mjs} +105 -44
- package/dist/channel-BCZXU3pt.mjs.map +1 -0
- package/dist/check-C1fUpgva.mjs +193 -0
- package/dist/check-C1fUpgva.mjs.map +1 -0
- package/dist/{core-DaRwkTaV.mjs → core-Cx7p-0nG.mjs} +99 -19
- package/dist/core-Cx7p-0nG.mjs.map +1 -0
- package/dist/hardware-BL6zvhQh.d.mts +107 -0
- package/dist/hardware.d.mts +81 -0
- package/dist/hardware.mjs +446 -0
- package/dist/hardware.mjs.map +1 -0
- package/dist/host.d.mts +27 -19
- package/dist/host.mjs +440 -164
- package/dist/host.mjs.map +1 -1
- package/dist/{index-CEhrd0Pl.d.mts → index-UclKfprm.d.mts} +269 -19
- package/dist/index.d.mts +5 -3
- package/dist/index.mjs +3 -33
- package/dist/{internal-CAKfHjIg.mjs → internal-DwCus_Ws.mjs} +1 -6
- package/dist/internal-DwCus_Ws.mjs.map +1 -0
- package/dist/nostr.d.mts +2 -2
- package/dist/nostr.mjs +14 -14
- package/dist/nostr.mjs.map +1 -1
- package/dist/{protocol-fXHXJguP.mjs → protocol-DLE6lHmP.mjs} +475 -49
- package/dist/protocol-DLE6lHmP.mjs.map +1 -0
- package/dist/protocol.d.mts +5 -4
- package/dist/protocol.mjs +3 -3
- package/dist/secret-CbjbY5-f.mjs +25 -0
- package/dist/secret-CbjbY5-f.mjs.map +1 -0
- package/dist/sessions.d.mts +52 -0
- package/dist/sessions.mjs +71 -0
- package/dist/sessions.mjs.map +1 -0
- package/dist/spark.d.mts +3 -3
- package/dist/spark.mjs +5 -8
- package/dist/spark.mjs.map +1 -1
- package/dist/types-CRnacSqJ.d.mts +390 -0
- package/dist/types.d.mts +2 -2
- package/dist/types.mjs +7 -1
- package/dist/types.mjs.map +1 -1
- package/package.json +27 -13
- package/dist/channel-BLwce5hh.mjs.map +0 -1
- package/dist/core-DaRwkTaV.mjs.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/internal-CAKfHjIg.mjs.map +0 -1
- package/dist/protocol-fXHXJguP.mjs.map +0 -1
- package/dist/secret-CcjyF8D3.mjs +0 -205
- package/dist/secret-CcjyF8D3.mjs.map +0 -1
- package/dist/types-cAQAJBLi.d.mts +0 -260
package/README.md
CHANGED
|
@@ -2,25 +2,35 @@
|
|
|
2
2
|
|
|
3
3
|
Public API surface of the qntx wallet: the `Wallet` interface, the immutable `WalletSnapshot`,
|
|
4
4
|
`WalletError`, the core API groups (vault, wallets, dataKeys), the host/kernel wire protocol, and
|
|
5
|
-
the `@qntx/wallet/nostr` subpath — the first protocol module
|
|
5
|
+
the `@qntx/wallet/nostr` subpath — the first protocol module (`./spark`, `./chains`,
|
|
6
|
+
`./sessions`, `./hardware` and `./card` are the other module subpaths). This package contains no runtime of
|
|
6
7
|
its own — a `Wallet` comes from a host package that spawns the kernel, currently
|
|
7
|
-
[`@qntx/wallet-worker`](https://www.npmjs.com/package/@qntx/wallet-worker) for Web and Node
|
|
8
|
+
[`@qntx/wallet-worker`](https://www.npmjs.com/package/@qntx/wallet-worker) for Web and Node and
|
|
9
|
+
[`@qntx/wallet-native`](https://www.npmjs.com/package/@qntx/wallet-native) for React Native.
|
|
8
10
|
|
|
9
11
|
```bash
|
|
10
12
|
npm install @qntx/wallet @qntx/wallet-worker
|
|
11
13
|
```
|
|
12
14
|
|
|
15
|
+
`@qntx/nostr`, `@qntx/spark`, `@qntx/wallet-chains` and `@qntx/ur` are optional peers, each needed
|
|
16
|
+
only by the subpaths that use it: `@qntx/nostr` by `./nostr`; `@qntx/spark` by the types of
|
|
17
|
+
`./spark`; `@qntx/wallet-chains` at runtime by `./chains`, `./sessions`, `./card` and `./hardware`,
|
|
18
|
+
and by the root's session protocol types (a host compiling with `skipLibCheck: false` installs it);
|
|
19
|
+
`@qntx/ur` by `./hardware`. The root entry and `./spark` load without any of them.
|
|
20
|
+
|
|
13
21
|
## Usage
|
|
14
22
|
|
|
15
23
|
```ts
|
|
24
|
+
import { verifyEvent } from "@qntx/nostr";
|
|
16
25
|
import { createWebWallet } from "@qntx/wallet-worker/browser";
|
|
17
26
|
|
|
18
27
|
const wallet = await createWebWallet({
|
|
19
28
|
passkey: {
|
|
20
|
-
rpId: "
|
|
29
|
+
rpId: "wallet.example.com", // a wallet-only domain — see the notes on its trust boundary
|
|
21
30
|
rpName: "Example",
|
|
22
31
|
walletSalt: "example/wallet",
|
|
23
32
|
vaultSalt: "example/vault",
|
|
33
|
+
backupSalt: "example/backup",
|
|
24
34
|
},
|
|
25
35
|
autoLock: { platform: "web", idleMinutes: 15 },
|
|
26
36
|
// Verifies every event the kernel signs; pass your app's native verifier where one exists.
|
|
@@ -42,16 +52,76 @@ const signer = nostr(wallet).signer(key.ref);
|
|
|
42
52
|
const event = await signer.signEvent({
|
|
43
53
|
kind: 1,
|
|
44
54
|
created_at: Math.floor(Date.now() / 1000),
|
|
55
|
+
pubkey: key.publicKey,
|
|
45
56
|
tags: [],
|
|
46
57
|
content: "gm",
|
|
47
58
|
});
|
|
48
59
|
```
|
|
49
60
|
|
|
61
|
+
`@qntx/wallet/sessions` manages the kernel-held session keys: `sessions(wallet).create` derives a
|
|
62
|
+
secp256k1 key inside the enclave for one HD account under a named scheme and returns its address,
|
|
63
|
+
`list`/`delete` manage the set, and `sign` produces the key's signature over the document its
|
|
64
|
+
scheme defines — for `hyperliquid-l1-agent`, the phantom-agent signature over an allow-listed L1
|
|
65
|
+
action. A `hyperliquid-l1-agent` session is approved and metered: `create` takes the owner's
|
|
66
|
+
`limits` (a notional budget, a leverage cap and per-asset size caps) and a `verify` factor,
|
|
67
|
+
`open(address, verify)` re-approves it after every lock, and the kernel charges every signed order
|
|
68
|
+
against the limits (`limit-exceeded` past them). On React Native the scheme needs the app lock on
|
|
69
|
+
(`app-lock-required` otherwise). A Hyperliquid agent only becomes valid once the owner approves it on Hyperliquid — the
|
|
70
|
+
kernel binds that signature's `agentName` to the recorded validity window — and the private key
|
|
71
|
+
never leaves the enclave. For `hyperliquid-l1-agent` every signature must carry an `expiresAfter`
|
|
72
|
+
at most 60 s after it is made and a nonce within ±60 s, both measured on the device clock. The
|
|
73
|
+
kernel has no trusted time: a
|
|
74
|
+
device clock running S ahead of real time stretches the 60 s to S + 60 s of real time. The engine
|
|
75
|
+
refuses to sign when the device is more than 5 s off Hyperliquid's server time, but that check runs
|
|
76
|
+
in the main runtime.
|
|
77
|
+
|
|
78
|
+
`@qntx/wallet/hardware` drives external signers that keep their seed entirely off the device
|
|
79
|
+
running the wallet. `hardware(wallet).start(op, { io, verify })` runs `pair`, `accounts`, `sign` or
|
|
80
|
+
`verify-address` over a host `DeviceIo` that transports the kernel's requests (for a Keystone:
|
|
81
|
+
animate `qrParts(request.show)`, fold scanned frames through `qrReader(request.scan)`; for Ledger
|
|
82
|
+
and OneKey: `ledgerIo` / `oneKeyIo` over a host `HidPort` or `BlePort`). The kernel validates every
|
|
83
|
+
frame, checks every returned signature, and a `sign` re-runs the same verification as
|
|
84
|
+
`chains().sign`; the host only moves bytes and shows prompts. Pairing requires a `verify`, and a
|
|
85
|
+
pinned key stays `confirmed: false` until `verify-address` shows it on the device. `@qntx/ur` is an
|
|
86
|
+
optional peer required only by this subpath.
|
|
87
|
+
|
|
88
|
+
| Device | Transport | Verified on | Source-only (untested) |
|
|
89
|
+
| ------------------------------------------------ | ------------ | ----------------------------------------------------------------------------------- | ----------------------------------------- |
|
|
90
|
+
| Keystone 3 Pro | QR (UR) | nothing — vendor encoders and firmware 3.2.2 sources only | every model and firmware |
|
|
91
|
+
| Ledger Nano S Plus / Nano X / Stax / Flex | USB HID, BLE | Speculos Nano S Plus with Bitcoin 2.5.1, Ethereum 1.24.0, Solana 1.16.0, Tron 0.8.2 | Nano X, Stax, Flex; any physical device |
|
|
92
|
+
| OneKey Classic 1S / Pro / Classic / Mini / Touch | USB HID, BLE | vendor emulators: Classic 1S firmware 3.21.0, Pro firmware 4.21.0 | Classic, Mini, Touch; any physical device |
|
|
93
|
+
|
|
94
|
+
`@qntx/wallet/card` drives qntx card wallets (React Native only; Web and Node answer
|
|
95
|
+
`unsupported`). A card wallet's seed lives only on its one to three cards — `WalletInfo.custody`
|
|
96
|
+
is `"card"` — so `chains(wallet).sign` answers `device-required` and the host runs the request as a
|
|
97
|
+
card task instead:
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
import type { Wallet } from "@qntx/wallet";
|
|
101
|
+
import { card } from "@qntx/wallet/card";
|
|
102
|
+
import type { ChainSignRequest } from "@qntx/wallet/chains";
|
|
103
|
+
|
|
104
|
+
const sign = async (wallet: Wallet, request: ChainSignRequest) => {
|
|
105
|
+
const task = card(wallet).start({ kind: "sign", request }, { verify: { kind: "hardware" } });
|
|
106
|
+
task.observe((step) => {
|
|
107
|
+
// "input": mount SecureInput from @qntx/wallet-native/secure-input
|
|
108
|
+
// "tap": show the hold-the-card instruction; "done": the result is ready
|
|
109
|
+
});
|
|
110
|
+
const outcome = await task.result; // { kind: "sign", result: ChainSignResult }
|
|
111
|
+
};
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
The host only starts, observes and cancels: the kernel reads the access code from the secure
|
|
115
|
+
field, exchanges the APDUs with the native NFC reader and sets the NFC sheet's text from the
|
|
116
|
+
request it decoded. `create`, `add`, `accounts`, `health`, `change-access`, `erase`, `transfer`
|
|
117
|
+
and `reseal` run the same way. **This release pins no production card certificate anchor, so
|
|
118
|
+
every card answers `card-not-genuine`** until a later release ships the anchor.
|
|
119
|
+
|
|
50
120
|
### React
|
|
51
121
|
|
|
52
122
|
`getSnapshot` and `subscribe` are bound properties, safe to pass unbound:
|
|
53
123
|
|
|
54
|
-
```
|
|
124
|
+
```jsx
|
|
55
125
|
import { useSyncExternalStore } from "react";
|
|
56
126
|
|
|
57
127
|
const snapshot = useSyncExternalStore(wallet.subscribe, wallet.getSnapshot);
|
|
@@ -68,14 +138,26 @@ What to do with each vault state:
|
|
|
68
138
|
- `unavailable` — the vault store failed transiently. Retry; the kernel retries a load on the
|
|
69
139
|
next request itself.
|
|
70
140
|
|
|
141
|
+
Resetting requires the live session while the vault is open and healthy; a locked or unhealthy
|
|
142
|
+
vault resets without one. On Web/Node reset is not an authentication boundary — same-origin code
|
|
143
|
+
can delete IndexedDB directly — so hosts must put their own confirmation UX in front of it. On
|
|
144
|
+
React Native the device owner proves presence before anything is erased.
|
|
145
|
+
|
|
71
146
|
## Security notes
|
|
72
147
|
|
|
73
|
-
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
148
|
+
- Seed, keys and the DEK exist only inside the kernel's Web Worker. The password and the
|
|
149
|
+
passkey PRF output, however, necessarily pass through the host thread: WebAuthn runs only on
|
|
150
|
+
the main thread, and for a passkey wallet the PRF output _is_ the wallet entropy.
|
|
151
|
+
- The Web host is a **hot wallet**. The Worker keeps secrets away from passive leaks (logs, error
|
|
152
|
+
reports, third-party scripts reading globals) and from reads of in-session memory. It does not
|
|
153
|
+
protect against an active attacker on the main thread: XSS or a malicious dependency can capture
|
|
154
|
+
the next password or PRF output and decrypt the same-origin IndexedDB vault, which is equivalent
|
|
155
|
+
to stealing the wallet. Ship a strict CSP, review dependencies, and steer large balances to the
|
|
156
|
+
mobile or hardware wallet.
|
|
77
157
|
- Your CSP must allow the bundled worker: `worker-src 'self'` (the worker loads from your own
|
|
78
158
|
origin — a stricter policy breaks the wallet).
|
|
159
|
+
With Trusted Types enforced, also allow the kernel worker in a `default` policy; see the
|
|
160
|
+
`@qntx/wallet-worker` README.
|
|
79
161
|
- Vite users: set `optimizeDeps.exclude: ["@qntx/wallet-worker"]` so the worker URL survives dev;
|
|
80
162
|
production builds need nothing — `vite build` emits `kernel.worker.js` as an asset.
|
|
81
163
|
- `@qntx/wallet/host` is reserved for host packages — applications must not use it.
|
|
@@ -85,26 +167,67 @@ What to do with each vault state:
|
|
|
85
167
|
- Password unlock is rate-limited inside the kernel: five counted misses arm a backoff
|
|
86
168
|
(30 s → 60 s → 300 s), a `rate-limited` error carries `retryAt`, and retrying during backoff
|
|
87
169
|
does not push the deadline. Passkey unlocks are never gated by it.
|
|
88
|
-
- Sessions idle-lock after 5, 15 or 60 minutes (`autoLock.idleMinutes`, worker-enforced) with
|
|
89
|
-
|
|
90
|
-
nor shorten a session. On the Web only
|
|
91
|
-
|
|
92
|
-
traffic cannot hold a session open. On
|
|
170
|
+
- Sessions idle-lock after 5, 15 or 60 minutes (`autoLock.idleMinutes`, worker-enforced) with an
|
|
171
|
+
absolute maximum of 12 hours on Web and Node and 24 hours on React Native, measured on a
|
|
172
|
+
monotonic clock — a wall-clock jump can neither extend nor shorten a session. On the Web only
|
|
173
|
+
user presence refreshes the idle timer (input events and tab visibility, throttled to one
|
|
174
|
+
`session.touch` per 30 s); signing and other background traffic cannot hold a session open. On
|
|
175
|
+
Node every successful request counts.
|
|
93
176
|
- `WalletInfo.backup` tells the UI whether the wallet survives losing this device: `"mnemonic"`
|
|
94
177
|
(the user passed the quiz, imported a phrase, or exported it at least once — `exportMnemonic`
|
|
95
178
|
upgrades the record), `"passkey"` (a synced passkey — still lost with the password-manager
|
|
96
179
|
account, so prompt to export), or `"none"` (a device-bound passkey — lost with the device).
|
|
180
|
+
- Blind signing is a vault setting, off by default. A request is blind only when the chain
|
|
181
|
+
decoder marks it so: a raw-byte or digest-shaped message (exactly 32 bytes, hidden or
|
|
182
|
+
deceptive characters, or text that encodes raw bytes), typed data too large or misformed
|
|
183
|
+
to show or carrying a hash or raw-bytes leaf the signature does not name, typed data a
|
|
184
|
+
recognised family claims in an unknown shape or a Seaport order over the item limit, a call
|
|
185
|
+
into an unrecognised function of a listed token, calldata that runs the signing account's own
|
|
186
|
+
code, an undecoded instruction of a core Solana program the signer signs, an undecoded Solana
|
|
187
|
+
program handed the signature whose reachable accounts cannot be listed, or a Safe
|
|
188
|
+
delegatecall or unbounded refund. `chains(wallet).sign` fails a blind request with
|
|
189
|
+
`blind-signing-disabled` — before any verification — until `vault.setBlindSigning(true, verify)`;
|
|
190
|
+
`snapshot.blindSigning` reports the setting. Requests the wallet can describe but not verify —
|
|
191
|
+
an unknown contract call, readable unrecognised typed data that fits the display budget,
|
|
192
|
+
a decoded 1inch, UniswapX or CoW order, an unknown Solana program or a core instruction the
|
|
193
|
+
signer does not sign, a multi-party PSBT — sign without the setting and their prompt carries
|
|
194
|
+
a "cannot verify" line. Through the dApp surface the engine still creates the pending request
|
|
195
|
+
and `requests.approve` throws `BlindSigningDisabledError` while the setting is off — enable it
|
|
196
|
+
and approve the same request again. Which requests are blind follows the rules above;
|
|
197
|
+
blind never means hidden — readable message text is shown, and 32-byte,
|
|
198
|
+
hidden-character or byte-encoding text is blind but still shown.
|
|
199
|
+
- `verify` parameters take a `VerifyFactor` — `hardware`, `passkey` or `password`. The silent
|
|
200
|
+
`device` factor proves no user presence: only `vault.unlock` accepts it (`UnlockFactor`). On
|
|
201
|
+
React Native `vault.enrolVerification()` registers the verifying factor and `vault.setAppLock`
|
|
202
|
+
makes every unlock verify — see the `@qntx/wallet-native` README.
|
|
97
203
|
- Changing the password or removing a factor rotates the vault DEK: sessions in other tabs lock
|
|
98
204
|
with reason `invalidated` and must re-unlock. Adding a passkey factor keeps the current DEK.
|
|
99
|
-
- `
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
205
|
+
- **The `rpId` scope is the wallet's trust boundary.** WebAuthn binds a credential and its PRF
|
|
206
|
+
to the RP id, not to an origin, and a passkey wallet's seed is the PRF over `walletSalt`. A
|
|
207
|
+
script on any origin that may claim the RP id — each of its subdomains, each origin listed in
|
|
208
|
+
`/.well-known/webauthn`, each app associated with it — can derive that seed from one passkey
|
|
209
|
+
prompt that looks like a sign-in. Use a domain that serves only the wallet
|
|
210
|
+
(`wallet.example.com`), never a registrable parent shared with other pages, user content or
|
|
211
|
+
third-party scripts, and treat every related origin and associated app as part of the wallet.
|
|
212
|
+
- `passkey.rpId`, `walletSalt`, `vaultSalt` and `backupSalt` are permanent identifiers — changing
|
|
213
|
+
any of them makes every existing passkey factor and passkey-derived wallet unrecoverable, and
|
|
214
|
+
the salts must differ. Moving domains requires WebAuthn related origins
|
|
215
|
+
(`/.well-known/webauthn`); offer `exportMnemonic` for passkey-derived wallets so they survive an
|
|
216
|
+
RP migration. `connectKernel` rejects an empty or colliding config before the worker spawns.
|
|
217
|
+
- Every Nostr key the vault holds is derived from a wallet — a `NostrKeyRef` is always
|
|
218
|
+
`{ kind: "derived", walletId, index }`, so keys come back with the wallet's own backup and
|
|
219
|
+
`nostr(wallet).removeKey` drops one. `nostr.exportKey` re-verifies on every call, and the
|
|
220
|
+
`ncryptsec` export always carries NIP-49 key-security byte `0x02` at scrypt logN 16.
|
|
221
|
+
- Cloud-backup envelopes leave the device, so the backup password is stretched with Argon2id
|
|
222
|
+
(64 MiB, 3 passes, 4 lanes) and must be at least 12 characters. On React Native the kernel
|
|
223
|
+
collects the backup password through its own secure input — the main runtime never holds it.
|
|
224
|
+
`backup.restore` adopts the file's backup key when the restore establishes the vault through a
|
|
225
|
+
kernel-run ceremony (React Native passkey or kernel-entered password); every other restore
|
|
226
|
+
leaves backup off until it is enabled again.
|
|
227
|
+
- A card wallet's seed, access code, access-code hashes and card session keys exist only on the
|
|
228
|
+
cards and in the kernel; no message to the host carries them. Each tap checks the card's
|
|
229
|
+
certificate against a pinned anchor and its identity against the vault record before any
|
|
230
|
+
access-code hash is sent, so an unknown or swapped card never learns anything.
|
|
108
231
|
- Requests are capped at 1 MiB on both sides of the channel; larger calls fail `invalid-input`
|
|
109
232
|
without reaching the kernel.
|
|
110
233
|
- `dist/kernel.manifest.json` in `@qntx/wallet-worker` records the protocol version, vault
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { WalletError } from "./types.mjs";
|
|
2
|
+
import { A as validate } from "./core-Cx7p-0nG.mjs";
|
|
3
|
+
import { g as backupEnvelope, y as backupHeader } from "./protocol-DLE6lHmP.mjs";
|
|
4
|
+
import { base64urlnopad } from "@scure/base";
|
|
5
|
+
// src/backup.ts
|
|
6
|
+
function integrity(msg) {
|
|
7
|
+
throw new WalletError("integrity", `backup: ${msg}`);
|
|
8
|
+
}
|
|
9
|
+
function json(text, what) {
|
|
10
|
+
try {
|
|
11
|
+
return JSON.parse(text);
|
|
12
|
+
} catch {
|
|
13
|
+
return integrity(`${what} is not JSON`);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/** Strictly validates the envelope and returns the header fields — no secrets, no writes. */
|
|
17
|
+
function parseBackupHeader(envelope) {
|
|
18
|
+
if (envelope.length > 4e6) integrity("envelope too large");
|
|
19
|
+
const parsed = validate(backupEnvelope, json(envelope, "envelope"));
|
|
20
|
+
if (parsed === void 0) integrity("malformed envelope");
|
|
21
|
+
const header = validate(backupHeader, json(parsed.header, "header"));
|
|
22
|
+
if (header === void 0) integrity("malformed header");
|
|
23
|
+
const factorKinds = parsed.factors.map((f) => f.kind);
|
|
24
|
+
if (factorKinds.filter((k) => k === "password").length > 1) integrity("at most one password factor");
|
|
25
|
+
return {
|
|
26
|
+
version: 1,
|
|
27
|
+
createdAt: parsed.createdAt,
|
|
28
|
+
wallets: header.wallets,
|
|
29
|
+
keys: header.keys ?? [],
|
|
30
|
+
factorKinds
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The passkey credential ids the envelope's factor entries name — the allow-list a restore's
|
|
35
|
+
* passkey assertion is scoped to (a restored vault's own credentials are a different set).
|
|
36
|
+
*/
|
|
37
|
+
function backupPasskeyCredentialIds(envelope) {
|
|
38
|
+
const parsed = validate(backupEnvelope, json(envelope, "envelope"));
|
|
39
|
+
if (parsed === void 0) integrity("malformed envelope");
|
|
40
|
+
return parsed.factors.flatMap((factor) => {
|
|
41
|
+
if (factor.kind !== "passkey") return [];
|
|
42
|
+
try {
|
|
43
|
+
return [base64urlnopad.decode(factor.credentialId)];
|
|
44
|
+
} catch {
|
|
45
|
+
return integrity("invalid credential encoding");
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
export { parseBackupHeader as n, backupPasskeyCredentialIds as t };
|
|
50
|
+
|
|
51
|
+
//# sourceMappingURL=backup-CLzMs8DP.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"backup-CLzMs8DP.mjs","names":[],"sources":["../src/backup.ts"],"sourcesContent":["// Read-only envelope inspection for the host: lists what a backup restores before the factor\n// ceremony runs. `header` is authenticated by the payload tag at restore time — this parser only\n// validates structure (bounded lengths, unknown fields rejected via the shared validators), so\n// nothing garbage reaches the kernel.\n\nimport { base64urlnopad } from \"@scure/base\";\n\nimport type { BackupHeaderKey, BackupHeaderWire } from \"./protocol/index.ts\";\nimport { backupEnvelope, backupHeader, validate } from \"./protocol/index.ts\";\nimport { WalletError } from \"./types.ts\";\n\nexport type BackupHeaderWallet = BackupHeaderWire[\"wallets\"][number];\nexport type { BackupHeaderKey } from \"./protocol/index.ts\";\n\nexport type BackupHeader = {\n readonly version: 1;\n readonly createdAt: number;\n readonly wallets: ReadonlyArray<BackupHeaderWallet>;\n /** Imported keys carried by the payload; empty when there are none. */\n readonly keys: ReadonlyArray<BackupHeaderKey>;\n /** The factor kinds the envelope can be unwrapped with. */\n readonly factorKinds: ReadonlyArray<\"passkey\" | \"password\">;\n};\n\nfunction integrity(msg: string): never {\n throw new WalletError(\"integrity\", `backup: ${msg}`);\n}\n\nfunction json(text: string, what: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return integrity(`${what} is not JSON`);\n }\n}\n\n/** Strictly validates the envelope and returns the header fields — no secrets, no writes. */\nexport function parseBackupHeader(envelope: string): BackupHeader {\n if (envelope.length > 4_000_000) {\n integrity(\"envelope too large\");\n }\n const parsed = validate(backupEnvelope, json(envelope, \"envelope\"));\n if (parsed === undefined) {\n integrity(\"malformed envelope\");\n }\n const header = validate(backupHeader, json(parsed.header, \"header\"));\n if (header === undefined) {\n integrity(\"malformed header\");\n }\n const factorKinds = parsed.factors.map((f) => f.kind);\n if (factorKinds.filter((k) => k === \"password\").length > 1) {\n integrity(\"at most one password factor\");\n }\n return {\n version: 1,\n createdAt: parsed.createdAt,\n wallets: header.wallets,\n keys: header.keys ?? [],\n factorKinds,\n };\n}\n\n/**\n * The passkey credential ids the envelope's factor entries name — the allow-list a restore's\n * passkey assertion is scoped to (a restored vault's own credentials are a different set).\n */\nexport function backupPasskeyCredentialIds(envelope: string): ReadonlyArray<Uint8Array> {\n const parsed = validate(backupEnvelope, json(envelope, \"envelope\"));\n if (parsed === undefined) {\n integrity(\"malformed envelope\");\n }\n return parsed.factors.flatMap((factor) => {\n if (factor.kind !== \"passkey\") {\n return [];\n }\n try {\n return [base64urlnopad.decode(factor.credentialId)];\n } catch {\n return integrity(\"invalid credential encoding\");\n }\n });\n}\n"],"mappings":";;;;;AAwBA,SAAS,UAAU,KAAoB;CACrC,MAAM,IAAI,YAAY,aAAa,WAAW,KAAK;AACrD;AAEA,SAAS,KAAK,MAAc,MAAuB;CACjD,IAAI;EACF,OAAO,KAAK,MAAM,IAAI;CACxB,QAAQ;EACN,OAAO,UAAU,GAAG,KAAK,aAAa;CACxC;AACF;;AAGA,SAAgB,kBAAkB,UAAgC;CAChE,IAAI,SAAS,SAAS,KACpB,UAAU,oBAAoB;CAEhC,MAAM,SAAS,SAAS,gBAAgB,KAAK,UAAU,UAAU,CAAC;CAClE,IAAI,WAAW,KAAA,GACb,UAAU,oBAAoB;CAEhC,MAAM,SAAS,SAAS,cAAc,KAAK,OAAO,QAAQ,QAAQ,CAAC;CACnE,IAAI,WAAW,KAAA,GACb,UAAU,kBAAkB;CAE9B,MAAM,cAAc,OAAO,QAAQ,KAAK,MAAM,EAAE,IAAI;CACpD,IAAI,YAAY,QAAQ,MAAM,MAAM,UAAU,CAAC,CAAC,SAAS,GACvD,UAAU,6BAA6B;CAEzC,OAAO;EACL,SAAS;EACT,WAAW,OAAO;EAClB,SAAS,OAAO;EAChB,MAAM,OAAO,QAAQ,CAAC;EACtB;CACF;AACF;;;;;AAMA,SAAgB,2BAA2B,UAA6C;CACtF,MAAM,SAAS,SAAS,gBAAgB,KAAK,UAAU,UAAU,CAAC;CAClE,IAAI,WAAW,KAAA,GACb,UAAU,oBAAoB;CAEhC,OAAO,OAAO,QAAQ,SAAS,WAAW;EACxC,IAAI,OAAO,SAAS,WAClB,OAAO,CAAC;EAEV,IAAI;GACF,OAAO,CAAC,eAAe,OAAO,OAAO,YAAY,CAAC;EACpD,QAAQ;GACN,OAAO,UAAU,6BAA6B;EAChD;CACF,CAAC;AACH"}
|
package/dist/card.d.mts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { A as VerifyFactor, j as Wallet, w as SignerTask } from "./types-CRnacSqJ.mjs";
|
|
2
|
+
import { St as CardTapReason, _t as CardInputPurpose, bt as CardStep, vt as CardOpResult, yt as CardOperation } from "./index-UclKfprm.mjs";
|
|
3
|
+
/** One running card operation: the host renders steps, never drives APDUs. */
|
|
4
|
+
export type CardTask = SignerTask<CardStep, CardOpResult>;
|
|
5
|
+
export type CardApi = {
|
|
6
|
+
readonly start: (op: CardOperation, options?: {
|
|
7
|
+
readonly verify?: VerifyFactor;
|
|
8
|
+
}) => CardTask;
|
|
9
|
+
};
|
|
10
|
+
export declare function card(wallet: Wallet): CardApi;
|
|
11
|
+
export type { CardInputPurpose, CardOpResult, CardOperation, CardStep, CardTapReason };
|
|
12
|
+
//# sourceMappingURL=card.d.mts.map
|
package/dist/card.mjs
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { WalletError } from "./types.mjs";
|
|
2
|
+
import { t as internalsOf } from "./internal-DwCus_Ws.mjs";
|
|
3
|
+
import { r as integrity } from "./channel-BCZXU3pt.mjs";
|
|
4
|
+
import { n as checkSignResult } from "./check-C1fUpgva.mjs";
|
|
5
|
+
// src/card/index.ts
|
|
6
|
+
/**
|
|
7
|
+
* The card module of @qntx/wallet: `card(wallet)` returns the wallet's card API. `start` runs one
|
|
8
|
+
* kernel card operation and hands back a `CardTask`: the host observes the step stream and renders
|
|
9
|
+
* it — an `input` step means "mount SecureInput", a `tap` step means "show the hold-the-card
|
|
10
|
+
* instruction". APDUs, access codes and reader sessions stay inside the kernel; the facade never
|
|
11
|
+
* drives them. The API is memoized per wallet like `sessions(wallet)`.
|
|
12
|
+
*/
|
|
13
|
+
const cancelledError = () => new WalletError("cancelled", "the card operation was cancelled");
|
|
14
|
+
function run(internals, op, verify) {
|
|
15
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
16
|
+
/** The most recent step the kernel reported — a late observe starts from it. */
|
|
17
|
+
let current;
|
|
18
|
+
let opId;
|
|
19
|
+
/** `cancel` raced `card.begin` — fire `card.cancel` the moment the opId lands. */
|
|
20
|
+
let cancelRequested = false;
|
|
21
|
+
let ackCancel;
|
|
22
|
+
let cancelAck;
|
|
23
|
+
let done = false;
|
|
24
|
+
let resolveResult;
|
|
25
|
+
let rejectResult;
|
|
26
|
+
const result = new Promise((resolve, reject) => {
|
|
27
|
+
resolveResult = resolve;
|
|
28
|
+
rejectResult = reject;
|
|
29
|
+
});
|
|
30
|
+
(async () => {
|
|
31
|
+
try {
|
|
32
|
+
await result;
|
|
33
|
+
} catch {}
|
|
34
|
+
})();
|
|
35
|
+
const emit = (step) => {
|
|
36
|
+
current = step;
|
|
37
|
+
for (const listener of listeners) listener(step);
|
|
38
|
+
};
|
|
39
|
+
const cancel = async () => {
|
|
40
|
+
if (done) return;
|
|
41
|
+
cancelRequested = true;
|
|
42
|
+
if (opId === void 0) {
|
|
43
|
+
cancelAck ??= new Promise((resolve) => {
|
|
44
|
+
ackCancel = resolve;
|
|
45
|
+
});
|
|
46
|
+
await cancelAck;
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
await internals.call("card.cancel", { opId }).catch(() => void 0);
|
|
50
|
+
};
|
|
51
|
+
(async () => {
|
|
52
|
+
try {
|
|
53
|
+
const begun = await internals.secretCall("card.begin", async (wire) => ({
|
|
54
|
+
op,
|
|
55
|
+
...verify === void 0 ? {} : { verify: await internals.resolveVerifyFactor(verify, wire) }
|
|
56
|
+
}));
|
|
57
|
+
({opId} = begun);
|
|
58
|
+
if (cancelRequested) {
|
|
59
|
+
await internals.call("card.cancel", { opId }).catch(() => void 0);
|
|
60
|
+
emit(begun.step);
|
|
61
|
+
done = true;
|
|
62
|
+
rejectResult(cancelledError());
|
|
63
|
+
ackCancel?.();
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
let { step } = begun;
|
|
67
|
+
while (step.kind !== "done") {
|
|
68
|
+
emit(step);
|
|
69
|
+
step = await internals.call("card.step", { opId });
|
|
70
|
+
}
|
|
71
|
+
const outcome = step.result;
|
|
72
|
+
if (outcome.kind === "sign") {
|
|
73
|
+
if (op.kind !== "sign") throw integrity("card.begin answered a sign result for a non-sign operation");
|
|
74
|
+
await checkSignResult(internals, op.request, outcome.result);
|
|
75
|
+
}
|
|
76
|
+
emit(step);
|
|
77
|
+
done = true;
|
|
78
|
+
resolveResult(outcome);
|
|
79
|
+
} catch (error) {
|
|
80
|
+
done = true;
|
|
81
|
+
ackCancel?.();
|
|
82
|
+
if (cancelRequested) rejectResult(cancelledError());
|
|
83
|
+
else rejectResult(error instanceof WalletError ? error : integrity("the card channel answered in bad shape"));
|
|
84
|
+
}
|
|
85
|
+
})();
|
|
86
|
+
return {
|
|
87
|
+
observe: (listener) => {
|
|
88
|
+
listeners.add(listener);
|
|
89
|
+
if (current !== void 0) listener(current);
|
|
90
|
+
return () => {
|
|
91
|
+
listeners.delete(listener);
|
|
92
|
+
};
|
|
93
|
+
},
|
|
94
|
+
cancel,
|
|
95
|
+
result
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
function createCardApi(internals) {
|
|
99
|
+
/** The running task, if any — a second `start` cancels it (the kernel does the same). */
|
|
100
|
+
let active;
|
|
101
|
+
return { start: (op, options) => {
|
|
102
|
+
active?.cancel();
|
|
103
|
+
active = run(internals, op, options?.verify);
|
|
104
|
+
return active;
|
|
105
|
+
} };
|
|
106
|
+
}
|
|
107
|
+
const apis = /* @__PURE__ */ new WeakMap();
|
|
108
|
+
function card(wallet) {
|
|
109
|
+
const internals = internalsOf(wallet);
|
|
110
|
+
let api = apis.get(wallet);
|
|
111
|
+
if (api === void 0) {
|
|
112
|
+
api = createCardApi(internals);
|
|
113
|
+
apis.set(wallet, api);
|
|
114
|
+
}
|
|
115
|
+
return api;
|
|
116
|
+
}
|
|
117
|
+
export { card };
|
|
118
|
+
|
|
119
|
+
//# sourceMappingURL=card.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"card.mjs","names":[],"sources":["../src/card/index.ts"],"sourcesContent":["/**\n * The card module of @qntx/wallet: `card(wallet)` returns the wallet's card API. `start` runs one\n * kernel card operation and hands back a `CardTask`: the host observes the step stream and renders\n * it — an `input` step means \"mount SecureInput\", a `tap` step means \"show the hold-the-card\n * instruction\". APDUs, access codes and reader sessions stay inside the kernel; the facade never\n * drives them. The API is memoized per wallet like `sessions(wallet)`.\n */\nimport { checkSignResult } from \"../chains/check.ts\";\nimport { integrity } from \"../channel.ts\";\nimport { internalsOf } from \"../internal.ts\";\nimport type { WalletInternals } from \"../internal.ts\";\nimport type { CardOperation, CardOpResult, CardStep } from \"../protocol/index.ts\";\nimport { WalletError } from \"../types.ts\";\nimport type { SignerTask, VerifyFactor, Wallet } from \"../types.ts\";\n\nexport type {\n CardInputPurpose,\n CardOperation,\n CardOpResult,\n CardStep,\n CardTapReason,\n} from \"../protocol/index.ts\";\n\n/** One running card operation: the host renders steps, never drives APDUs. */\nexport type CardTask = SignerTask<CardStep, CardOpResult>;\n\nexport type CardApi = {\n readonly start: (op: CardOperation, options?: { readonly verify?: VerifyFactor }) => CardTask;\n};\n\nconst cancelledError = (): WalletError =>\n new WalletError(\"cancelled\", \"the card operation was cancelled\");\n\nfunction run(internals: WalletInternals, op: CardOperation, verify?: VerifyFactor): CardTask {\n const listeners = new Set<(step: CardStep) => void>();\n /** The most recent step the kernel reported — a late observe starts from it. */\n let current: CardStep | undefined;\n let opId: string | undefined;\n /** `cancel` raced `card.begin` — fire `card.cancel` the moment the opId lands. */\n let cancelRequested = false;\n let ackCancel: (() => void) | undefined;\n let cancelAck: Promise<void> | undefined;\n let done = false;\n let resolveResult!: (result: CardOpResult) => void;\n let rejectResult!: (error: WalletError) => void;\n const result = new Promise<CardOpResult>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n // The task owns `result`'s rejection — it must never surface as unhandled.\n void (async (): Promise<void> => {\n try {\n await result;\n } catch {\n // `result` itself surfaces the WalletError to whoever awaited it.\n }\n })();\n\n const emit = (step: CardStep): void => {\n current = step;\n for (const listener of listeners) {\n listener(step);\n }\n };\n\n const cancel = async (): Promise<void> => {\n if (done) {\n return;\n }\n cancelRequested = true;\n if (opId === undefined) {\n // `card.begin` has not answered: remember and resolve once the deferred cancel lands.\n cancelAck ??= new Promise<void>((resolve) => {\n ackCancel = resolve;\n });\n await cancelAck;\n return;\n }\n // The in-flight or next `card.step` answers `cancelled`/`not-found`; the runner maps both to\n // `cancelled` because this request asked for it.\n await internals.call(\"card.cancel\", { opId }).catch(() => undefined);\n };\n\n void (async (): Promise<void> => {\n try {\n const begun = await internals.secretCall(\"card.begin\", async (wire) => ({\n op,\n ...(verify === undefined\n ? {}\n : { verify: await internals.resolveVerifyFactor(verify, wire) }),\n }));\n ({ opId } = begun);\n if (cancelRequested) {\n await internals.call(\"card.cancel\", { opId }).catch(() => undefined);\n emit(begun.step);\n done = true;\n rejectResult(cancelledError());\n ackCancel?.();\n return;\n }\n let { step } = begun;\n while (step.kind !== \"done\") {\n emit(step);\n // oxlint-disable-next-line eslint/no-await-in-loop -- the kernel's poll cadence\n step = await internals.call(\"card.step\", { opId });\n }\n const outcome = step.result;\n if (outcome.kind === \"sign\") {\n if (op.kind !== \"sign\") {\n throw integrity(\"card.begin answered a sign result for a non-sign operation\");\n }\n // The `done` step goes out only once the result verifies — an observer never sees a\n // forged signature reported as done.\n await checkSignResult(internals, op.request, outcome.result);\n }\n emit(step);\n done = true;\n resolveResult(outcome);\n } catch (error) {\n done = true;\n ackCancel?.();\n if (cancelRequested) {\n rejectResult(cancelledError());\n } else {\n rejectResult(\n error instanceof WalletError\n ? error\n : integrity(\"the card channel answered in bad shape\"),\n );\n }\n }\n })();\n\n return {\n observe: (listener) => {\n listeners.add(listener);\n if (current !== undefined) {\n listener(current);\n }\n return () => {\n listeners.delete(listener);\n };\n },\n cancel,\n result,\n };\n}\n\nfunction createCardApi(internals: WalletInternals): CardApi {\n /** The running task, if any — a second `start` cancels it (the kernel does the same). */\n let active: CardTask | undefined;\n return {\n start: (op, options) => {\n void active?.cancel();\n active = run(internals, op, options?.verify);\n return active;\n },\n };\n}\n\nconst apis = new WeakMap<Wallet, CardApi>();\n\nexport function card(wallet: Wallet): CardApi {\n const internals = internalsOf(wallet);\n let api = apis.get(wallet);\n if (api === undefined) {\n api = createCardApi(internals);\n apis.set(wallet, api);\n }\n return api;\n}\n"],"mappings":";;;;;;;;;;;;AA8BA,MAAM,uBACJ,IAAI,YAAY,aAAa,kCAAkC;AAEjE,SAAS,IAAI,WAA4B,IAAmB,QAAiC;CAC3F,MAAM,4BAAY,IAAI,IAA8B;;CAEpD,IAAI;CACJ,IAAI;;CAEJ,IAAI,kBAAkB;CACtB,IAAI;CACJ,IAAI;CACJ,IAAI,OAAO;CACX,IAAI;CACJ,IAAI;CACJ,MAAM,SAAS,IAAI,SAAuB,SAAS,WAAW;EAC5D,gBAAgB;EAChB,eAAe;CACjB,CAAC;CAED,CAAM,YAA2B;EAC/B,IAAI;GACF,MAAM;EACR,QAAQ,CAER;CACF,EAAA,CAAG;CAEH,MAAM,QAAQ,SAAyB;EACrC,UAAU;EACV,KAAK,MAAM,YAAY,WACrB,SAAS,IAAI;CAEjB;CAEA,MAAM,SAAS,YAA2B;EACxC,IAAI,MACF;EAEF,kBAAkB;EAClB,IAAI,SAAS,KAAA,GAAW;GAEtB,cAAc,IAAI,SAAe,YAAY;IAC3C,YAAY;GACd,CAAC;GACD,MAAM;GACN;EACF;EAGA,MAAM,UAAU,KAAK,eAAe,EAAE,KAAK,CAAC,CAAC,CAAC,YAAY,KAAA,CAAS;CACrE;CAEA,CAAM,YAA2B;EAC/B,IAAI;GACF,MAAM,QAAQ,MAAM,UAAU,WAAW,cAAc,OAAO,UAAU;IACtE;IACA,GAAI,WAAW,KAAA,IACX,CAAC,IACD,EAAE,QAAQ,MAAM,UAAU,oBAAoB,QAAQ,IAAI,EAAE;GAClE,EAAE;GACF,CAAC,CAAE,QAAS;GACZ,IAAI,iBAAiB;IACnB,MAAM,UAAU,KAAK,eAAe,EAAE,KAAK,CAAC,CAAC,CAAC,YAAY,KAAA,CAAS;IACnE,KAAK,MAAM,IAAI;IACf,OAAO;IACP,aAAa,eAAe,CAAC;IAC7B,YAAY;IACZ;GACF;GACA,IAAI,EAAE,SAAS;GACf,OAAO,KAAK,SAAS,QAAQ;IAC3B,KAAK,IAAI;IAET,OAAO,MAAM,UAAU,KAAK,aAAa,EAAE,KAAK,CAAC;GACnD;GACA,MAAM,UAAU,KAAK;GACrB,IAAI,QAAQ,SAAS,QAAQ;IAC3B,IAAI,GAAG,SAAS,QACd,MAAM,UAAU,4DAA4D;IAI9E,MAAM,gBAAgB,WAAW,GAAG,SAAS,QAAQ,MAAM;GAC7D;GACA,KAAK,IAAI;GACT,OAAO;GACP,cAAc,OAAO;EACvB,SAAS,OAAO;GACd,OAAO;GACP,YAAY;GACZ,IAAI,iBACF,aAAa,eAAe,CAAC;QAE7B,aACE,iBAAiB,cACb,QACA,UAAU,wCAAwC,CACxD;EAEJ;CACF,EAAA,CAAG;CAEH,OAAO;EACL,UAAU,aAAa;GACrB,UAAU,IAAI,QAAQ;GACtB,IAAI,YAAY,KAAA,GACd,SAAS,OAAO;GAElB,aAAa;IACX,UAAU,OAAO,QAAQ;GAC3B;EACF;EACA;EACA;CACF;AACF;AAEA,SAAS,cAAc,WAAqC;;CAE1D,IAAI;CACJ,OAAO,EACL,QAAQ,IAAI,YAAY;EACtB,QAAa,OAAO;EACpB,SAAS,IAAI,WAAW,IAAI,SAAS,MAAM;EAC3C,OAAO;CACT,EACF;AACF;AAEA,MAAM,uBAAO,IAAI,QAAyB;AAE1C,SAAgB,KAAK,QAAyB;CAC5C,MAAM,YAAY,YAAY,MAAM;CACpC,IAAI,MAAM,KAAK,IAAI,MAAM;CACzB,IAAI,QAAQ,KAAA,GAAW;EACrB,MAAM,cAAc,SAAS;EAC7B,KAAK,IAAI,QAAQ,GAAG;CACtB;CACA,OAAO;AACT"}
|