diff --git a/CHANGELOG.md b/CHANGELOG.md index a449f2351..3d4e18348 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,7 @@ Members-only content in public repositories, Environments and the secret scan. P - **Secrets in a public push.** `git push` to a public repository checks every file it publishes for the first time. It refuses a new `.env` file, a PEM private key, an AWS key pair or a GitHub or GitLab token with a valid checksum (E807), and warns about `.envrc` files, random-looking values and keys in test folders. `-o allow-secret=` or `.forge/secret-scan-allow` lets a checked finding through. See [Secrets in a push](docs/guides/quick-start.md#secrets-in-a-push). - **Wallet sign-in keeps your encryption key.** The web app stores the encryption key the Dash Wallet registers in the browser's vault, every one of them across approvals, so private repositories and members-only content open after one unlock per tab. When the identity's key came from somewhere else, it says "Your encryption key is held elsewhere. Import it under Settings → Private repos." - **Wallet sign-in with App Connect v2: one approval for all of Forge.** Where the network runs protocol 14 and Forge is deployed (devnet sakura today), the wallet tile comes first and shows an App Connect v2 request: the wallet adds one key for this browser that works on every Forge contract, capped at 0.05 DASH of spending and expiring after 90 days (a wallet may offer other limits), so the extra approvals of the older exchange are not asked for. The phone link returns to a new `/connect/` page, and the sign-in checks the wallet again when the tab regains focus. A key a wallet granted is renewed in that wallet (**Renew in your wallet**, in the low-funds banner, the top-up sheet and Settings → This browser's key); the identity file or recovery phrase still works. If your wallet's build has no App Connect v2, **Show the older code** gives today's request. A v2 sign-in does not bring an encryption key: set up private and members-only content in Settings. We know of no released Dash Wallet that speaks App Connect v2 yet; the [wallet sign-in notes](docs/design/wallet-login.md#app-connect-v2-one-approval-for-all-of-forge) say what works today. +- **Passkeys for other devices (web app).** **Settings → Devices & keys → Passkeys for other devices** adds a passkey that holds this browser's key, encrypted to it, on Platform. On another device, **Sign in with a passkey** brings that sign-in over: the same key and budget, checked against your identity before it is used. A passkey moves a session, it doesn't recover an account: when the key expires or is disabled it stops working, and you renew with your identity file, recovery phrase or wallet (a session restored from a passkey offers both **Renew in your wallet** and **Renew with identity file**). Keys without a spending limit or an expiry stay on the device that holds them, because the encrypted copy is public on Platform for good. Your encryption key is included only if you tick it, with a warning that it can't be taken back. After signing in, the web app offers a passkey once (twice at most, never after **Not now**). Revoking or disabling a key offers to remove the passkeys that hold it. Adding one costs about 0.0005 DASH from the key's budget; signing in is free. It works at forge.dashhq.org only. **It does nothing yet:** the controls stay hidden until forge-meta on the network has the new `vaultEntry` type, which is a pending forge-meta update on devnet sakura. See [Passkeys: the threat model](docs/security/passkey-vault.md) and [identity and keys](docs/guides/identity-and-keys.md#passkeys-for-other-devices). ### Changed diff --git a/crates/forge-core/src/layout.rs b/crates/forge-core/src/layout.rs index 7e495a445..eab615e57 100644 --- a/crates/forge-core/src/layout.rs +++ b/crates/forge-core/src/layout.rs @@ -6,7 +6,8 @@ //! here instead of hard-coding one, so the map lives in exactly one place. //! //! DESIGN rev 4.1 D44 adds a fourth contract, forge-meta, registered last: `repoKey`, `ban`, -//! `label`, `topic`, `packMirror`, `profile` and `follow` ([`META_TYPES`]) move there. The +//! `label`, `topic`, `packMirror`, `profile` and `follow` ([`META_TYPES`]) move there, and +//! `vaultEntry` (UPDATE-2, the passkey vault) exists there only. The //! deployment record says which layout a network has (`v2.forgeMeta` present, //! [`ForgeIds::meta`]), so one build serves sakura's three-contract set and four-contract sets: //! [`ForgeIds::contract_of`] is the layout-aware map, [`ForgeContract::of`] the three-contract @@ -86,8 +87,10 @@ pub const COMMUNITY_TYPES: [&str; 12] = [ /// The types forge-meta holds on a four-contract set (D44). On a three-contract set they stay /// in [`CORE_TYPES`] (`label`, `topic`, `packMirror`), [`COLLAB_TYPES`] (`repoKey`, `ban`) and /// [`COMMUNITY_TYPES`] (`profile`, `follow`). None of them is read by a rule, total or derived -/// index of its old contract, so the move changes no consensus rule. -pub const META_TYPES: [&str; 7] = [ +/// index of its old contract, so the move changes no consensus rule. `vaultEntry` (UPDATE-2) is +/// the exception: `build.py` builds it with the four-contract layout only, so it has no +/// three-contract home and [`ForgeContract::of`] knows no contract for it. +pub const META_TYPES: [&str; 8] = [ "repoKey", "ban", "label", @@ -95,6 +98,7 @@ pub const META_TYPES: [&str; 7] = [ "packMirror", "profile", "follow", + "vaultEntry", ]; /// The listed types a contract build may leave out: RC2's fused star (C1, a `build.py` flag) @@ -415,7 +419,8 @@ mod tests { assert_eq!(four.contract_id_of(t), Some("META"), "{t}"); assert_eq!(four.home(t), "META", "{t}"); assert_ne!(three.contract_id_of(t), Some("META"), "{t}"); - assert!(three.contract_id_of(t).is_some(), "{t}"); + // (vaultEntry, UPDATE-2, is a four-contract type: no home in the three-contract set) + assert_eq!(three.contract_id_of(t).is_some(), t != "vaultEntry", "{t}"); } for (t, old) in [ ("repoKey", "COLLAB"), diff --git a/docs/contracts/forge-v2.md b/docs/contracts/forge-v2.md index fbb888ebf..a3a500c6a 100644 --- a/docs/contracts/forge-v2.md +++ b/docs/contracts/forge-v2.md @@ -111,7 +111,22 @@ The mainnet registration (`build.py --mainnet`, flag `layout_meta`; dash-forge-q The mainnet forge-core also gains `pushGrant` (B1, §9.1): a maintainer's grant letting a Bot member (`writer.role` 4) push to one exact members-only ref or under one public ref prefix, for at most 90 days. Clients write and read it from phase 4E (`docs/security/private-repos.md` §24): `dg bot allow --push`, `renew`, `suspend`, `resume` and `revoke --push`; a bot's push stamps `r` 4, `pp`/`pg` and `grantor`; readers mark a bot's push outside its access client-side. -Devnet sakura keeps the three-contract set, and clients take the layout from the deployment record: `v2.forgeMeta` present means four contracts, and the seven types are read and written there; absent, they stay in their old homes. One build serves both (phase M-B: `forge-core::layout` `ForgeIds::contract_of` and `home`, forge-web `lib/layout.ts` `contractKindOfType` and `lib/repo/source.ts` `contractOf`, the seed scripts' `contractOn`). The cost previews follow: a signer's first write to forge-meta pays its contract nonce even when it has written the type's old home, and a key bound to forge-meta alone is a wallet grant of its own ("labels, topics and profiles"). +**`vaultEntry` (UPDATE-2, the passkey vault).** forge-meta also holds one type that no other layout has: `vaultEntry`, a passkey-sealed bundle of a session's keys, one per (owner, WebAuthn credential), so a new device can sign in with a passkey and open the keys the signed-in session stored. `build.py` defines it in forge-community (flag `passkey_vault`, in `UPDATE2_FLAGS`) and `META_TYPES` moves it to forge-meta; it is built with the four-contract layout only, because forge-community's three-contract build would grow to 18,385 B (over the 17,832 B ceiling) with 1,989 B of room (under `ROOM_MIN`). No rule, total or reference to another type reads it, so it changes no consensus rule, and protocol 14 lets an update add it (it is a new type with its own index, §9.1). It is covered by the same group membership as the rest of forge-meta, so no key binding or group trust changes. A three-contract network has no `vaultEntry` (the clients' layout answers "no contract holds it"). + +| Property | Shape | Note | +|---|---|---| +| `credentialId` | byte array, 16 to 255 B | the WebAuthn credential id; **immutable**; in the unique index | +| `recipientKey` | `bytes`, 32 B | the HPKE recipient public key the passkey's PRF output derives; **immutable** | +| `version` | integer, 1 to 255 | the entry format | +| `authKeyId` | `u32`, `refersTo` `identityPublicKey` (`identityProperty` `$ownerId`, `keyRequirements {purpose: authentication}`) | the owner's authentication key that slot 0 of the bundle stands for; Platform checks it is one on create and on any replace that changes it | +| `enc` | `bytes`, 32 B | the HPKE encapsulated key | +| `sealed` | byte array, 32 to 256 B | the ciphertext. Forge writes one format of 256 B (240 B padded plus the 16 B tag). An update can still loosen its bounds (lower `minItems`, raise `maxItems`), but never make it fixed-length | + +`documentsMutable` and `canBeDeleted` are both true: re-sealing is a replace of `enc`, `sealed`, `version` and `authKeyId` (`credentialId` and `recipientKey` are listed under `immutable`, so a replace cannot move an entry to another passkey or recipient, and the ciphertext's AAD binds both), and removing a passkey is a delete, which refunds its storage deposit. `required`: `$createdAt`, `$updatedAt` and every property above; `additionalProperties` is false. One unique index, `byCredential [$ownerId, credentialId]`, serves the sign-in lookup (both bound) and an owner's list (the `$ownerId` prefix). The shorthand form (`mainnet_shorthand`) writes `recipientKey` and `enc` as `{"type": "bytes", "size": 32}`; `credentialId` and `sealed` vary in length and keep the long form. + +Size: forge-meta serializes to 7,684 B (6,870 B without it), its create transition to 7,790 B (6,976 B), which leaves 12,690 B of room; the fee schedule's registration fee for the contract goes from 0.36 to 0.39 DASH (one more type and one more index; the per-byte part is not in that figure). **Estimated fees** (not measured on Forge; scaled from Yappr's sakura measurements of the same document shape, to be re-measured by the live test): a first entry about 46 to 50 M credits (about 0.0005 DASH), a later entry about 28 to 31 M, a re-seal about 2 to 3 M, a delete refunds about 23 to 35 M, and a sign-in reads only, so it is free. Forge's 256 B ciphertext is 80 to 160 B larger than Yappr's, which adds about 2 to 4 M credits at 27,400 credits per byte ([economics.md](../economics.md)). All of it comes out of the signed-in key's budget. + +A devnet may run the three-contract set (devnet sakura did until it moved to the four-contract set on 2026-10-17), and clients take the layout from the deployment record: `v2.forgeMeta` present means four contracts, and the seven types are read and written there; absent, they stay in their old homes. One build serves both (phase M-B: `forge-core::layout` `ForgeIds::contract_of` and `home`, forge-web `lib/layout.ts` `contractKindOfType` and `lib/repo/source.ts` `contractOf`, the seed scripts' `contractOn`). The cost previews follow: a signer's first write to forge-meta pays its contract nonce even when it has written the type's old home, and a key bound to forge-meta alone is a wallet grant of its own ("labels, topics and profiles"). Shared shapes (`id`, `hid`, `oid`, `h32`, `refName`, `branch`, `title`, `body`, `enc`, `vis`, `member`, …) are in `schemaDefs` and referenced with `$ref`. A document type may use each `$defs` entry **once**: rs-dpp's depth walker treats a second `$ref` to the same definition in one type as a cycle (`InvalidJsonSchemaRefError`). That is why `packHash` uses `hid`, an identical copy of `id`. The same goes for the `integer` shape of a key id named by `encryptedFor` or `keyIdProperty`, which must be inline (the parser's `is_key_id_schema` resolves `$ref` against the document schema, which has no `$defs`). Repeats are inlined for these reasons. Every `enc` is at least 29 bytes (INV-11: the smallest envelope). @@ -845,6 +860,8 @@ An update may add only optional properties, `enum` values appended at the end, a **Size.** With UPDATE-1 the three contracts serialize to 17,462 / 17,633 / 17,513 B: 54, 225 and 105 B over the 17,408 B target (§7), all under the 17,832 B ceiling. The signed update transitions are about 17.5–17.7 KB of the 20,480 B limit, which leaves about 2.7 KB for any later update. +**UPDATE-2** (the passkey vault) is one more `DataContractUpdate`, of forge-meta alone: `vaultEntry` (§2, forge-meta), a new type with its own unique index and a `refersTo` to the owner's own authentication key, nothing on an existing type. It is the flag `passkey_vault` (`UPDATE2_FLAGS`, off in the registered v1 set; `stale_registered` turns it off with UPDATE-1's). On a network that is not registered yet (testnet, mainnet) it is part of the registration set and changes forge-meta's sha256, which the owner signs again; on devnet sakura, which registered forge-meta without it (`4CyD…`, source `04627b52…`), it ships as `deploy-v2.mjs --update meta` and `contract-validate --expect-update` accepts the new forge-meta as an update of the registered one (`ALLOWED (DataContractUpdate v1 -> v2)`; run by hand against `git show ec3c86f12:forge-contracts/contracts/mainnet/forge-meta.json`, the file sakura registered, since no `registered/devnet-sakura/` copy is frozen for CI). Its vectors (`vaultEntry` cases of the `U2` item: shapes, bounds, the immutable `credentialId` and `recipientKey`, the re-seal, the index) are generated for the four-contract set (`vectors.py --mainnet`), and the committed three-contract vectors only assert that the type is absent there. + **The mixed-visibility items (mainnet only).** dash-forge-qa `design/mixed-visibility/DESIGN.md` rev 4.1 §8.3 adds the layout and eleven items to `MAINNET_FLAGS`, in its order. Each is off in every devnet build and on with `build.py --mainnet`; `build.NEEDS` refuses a combination that cannot register (a `where` naming a property another item adds, or B1 without the room forge-meta leaves). Row numbers are DESIGN §8.2's. A refusal is 10422 (the first broken rule in name order), 40127 (a `where` mismatch) or 40120 (no document found), as M-C checks live. | # | Flag | Item | Contract | What consensus enforces | Until mainnet | diff --git a/docs/deploying-to-a-network.md b/docs/deploying-to-a-network.md index 5c72136b5..962a199a6 100644 --- a/docs/deploying-to-a-network.md +++ b/docs/deploying-to-a-network.md @@ -26,7 +26,7 @@ Four contracts, in one contract group (`dash-forge`) that has an owner and **no | 1 | `forge-core` | repositories, members (`writer`, `maintainer`, `consent`), packs, refs, releases, config, `pushGrant`. Its create transition also creates the contract group. | | 2 | `forge-collab` | issues, pull requests, reviews, comments, transitions | | 3 | `forge-community` | `authorEvent`, `checkRun`, `event`, `milestone`, `policy`, `runner`, `star`, `watch`, `webhook` | -| 4 | `forge-meta` | `ban`, `follow`, `label`, `packMirror`, `profile`, `repoKey`, `topic` ([forge-v2.md §2](contracts/forge-v2.md#forge-meta-mainnet-set-only)) | +| 4 | `forge-meta` | `ban`, `follow`, `label`, `packMirror`, `profile`, `repoKey`, `topic`, `vaultEntry` ([forge-v2.md §2](contracts/forge-v2.md#forge-meta-mainnet-set-only)) | The order is fixed. Each contract takes the deployer's next identity nonce, the contract and group ids derive from those nonces, and each later contract's schema names the ids of the ones registered before it. [forge-v2.md §8](contracts/forge-v2.md#8-deploying) has the details. diff --git a/docs/economics.md b/docs/economics.md index 77db15726..ce6815b40 100644 --- a/docs/economics.md +++ b/docs/economics.md @@ -93,6 +93,7 @@ All in DASH, **measured on devnets** (to be re-measured on testnet); fiat figure | Fork a repo | ~0.01 DASH for a small repository and 0.03 for a 36-pack one: one small manifest per pack and one ref update per branch; the parent's packs are referenced, never re-uploaded | same | | Push 100 KiB source delta (~30 KiB packed) | about 0.015–0.02 DASH (~$0.45–0.60): 0.33–0.36 DASH/MiB for the packed bytes plus ~0.004–0.011 for the manifests, ref update and history index. Permanent | ~0.004–0.0055 DASH (~$0.12–0.17): manifests and the ref update only | | 1,000 issues + 5,000 comments over a year | **~3.1–4.5 DASH** (~$95–135) for short bodies (issues 0.0006–0.001 each, comments 0.0005–0.0007 each; more with long bodies). Issues are permanent, comments refundable on delete | same (always on Platform) | +| Add a passkey for other devices, then sign in with it elsewhere | **~0.0005 DASH** for an identity's first (estimate: Yappr's 46–50M credits plus ~2–4M for Forge's larger 256-byte entry), ~0.0003 for each later one; re-sealing after a key change ~0.00003; removing one refunds ~0.0002–0.0003; signing in is free. Paid from the browser key's budget ([passkey vault](security/passkey-vault.md)) | same | | Remove one member from a 50-member repository with members-only content | ~0.035 DASH: the key is changed for the 49 who remain ([guides/costs.md](guides/costs.md#members-only-and-private-content)) | same | | Force-push away 10 MiB of history, then repack | nothing recovered; the repack adds a deposit for the consolidated pack | delete the old objects in your bucket | | Deployer: register the production set (once per network) | **~1.86 DASH for the four contracts** (0.5968 + 0.3963 + 0.5063 + 0.3636), measured on a Platform v5 devnet, and 1.873 DASH on testnet (2026-10-26); ~1.73 DASH for the three-contract devnet set ([Deploying Forge to a network](deploying-to-a-network.md#4-what-it-costs), [forge-v2.md §7](contracts/forge-v2.md#7-measured-size-and-cost)) | same | diff --git a/docs/guides/costs.md b/docs/guides/costs.md index 485d3c2d7..bc2247b87 100644 --- a/docs/guides/costs.md +++ b/docs/guides/costs.md @@ -244,6 +244,20 @@ Packs are git packfiles: delta-compressed and deflated, typically 20–35% of th --- +### Passkeys for other devices + +A passkey's entry is one small stored item, written with this browser's key (so it comes out of that key's budget, like any write). These are estimates from Yappr's measurements on a development network plus the extra bytes of Forge's fixed-size entry, not yet measured on testnet; the live test (`lib/auth/passkey-vault.live.test.ts`) prints what each step really cost. + +| Action | About | Notes | +|---|---|---| +| First passkey on an identity | 0.0005 DASH | builds the identity's passkey list, so it costs more than the next ones | +| Each later passkey | 0.0003 DASH | | +| Update a passkey after a key change | 0.00003 DASH | a replace of its entry | +| Remove a passkey | refunds about 0.0002–0.0003 DASH | deleting returns the deposit | +| Sign in with a passkey | free | reads only | + +At most 10 passkeys per identity. An entry is always the same size, whatever keys it holds. + ## Platform or your own bucket Pack bytes are almost all of a repository's size, so where you keep them decides the cost: diff --git a/docs/guides/identity-and-keys.md b/docs/guides/identity-and-keys.md index c72343791..ba0a85476 100644 --- a/docs/guides/identity-and-keys.md +++ b/docs/guides/identity-and-keys.md @@ -299,6 +299,18 @@ CI gets one pasteable value, `DASH_FORGE_KEY=dfk1::: only (and `localhost` for development), and only once the network's forge-meta has the passkey vault. + +- **It moves a session. It doesn't recover an account.** The keys it carries are the limited keys you already have, with their budget and expiry. When the key expires or is disabled, the passkey stops working: renew with your identity file or recovery phrase (or in the wallet that granted it). +- **Every device shares the same key and budget.** Disabling the key signs all of them out. The list says which passkey is this device's and which key each holds; **Needs update** appears when a passkey holds an older key after a renewal, and asks that passkey once to save the new one. +- **Keys without a spending limit stay on this device only.** A passkey holds a key only if it has a budget and an expiry, because the encrypted copy is public on Platform for good. A v1 wallet's unlimited per-contract key is left out; the page counts how many. +- **Your encryption key is not included unless you tick it.** Once written, it can't be taken back: removing the passkey later does not lock out anyone who has it. Replace the encryption key too ([above](#replacing-it-after-a-lost-device)). +- **Removing a passkey** deletes its entry (the deposit comes back); the key it held keeps working. Revoking or disabling a key offers to remove the passkeys that hold it first. + +Adding the first passkey costs about 0.0005 DASH from the key's budget ([costs](costs.md#passkeys-for-other-devices)). The threat model is in [passkey vault](../security/passkey-vault.md). + ## The browser vault and its limits The limited key is stored in IndexedDB, encrypted with AES-256-GCM. The data key is wrapped by a passkey's PRF output (stretched with HKDF), by Argon2id of your passphrase (64 MiB, 3 passes, 16-byte salt), or by both. Each ciphertext is bound to its network and identity. diff --git a/docs/limits.md b/docs/limits.md index cc08a22ae..52f525859 100644 --- a/docs/limits.md +++ b/docs/limits.md @@ -17,6 +17,8 @@ What Forge cannot hold or do, in numbers, with where each number comes from. Som | One `chunk` document (git pack bytes on Platform) | 3 fields, **14,700 bytes** of pack per chunk (about 14.4 KiB); a full chunk leaves at least 5 KiB for headers | `DOC_PAYLOAD_MAX` in `pack.rs` | | A pack | **1 TiB**: the cap on the size a manifest records (**frozen**). Forge's tools add no smaller cap; on Platform a pack is split over as many chunks as it needs, each costing about 0.005 DASH | [forge-v2.md §9](contracts/forge-v2.md#9-frozen-at-mainnet); [Costs](guides/costs.md) | | A contract (registration) | 20,480 bytes, and at least 2,000 bytes of headroom under that for the create transition | `deploy-v2.mjs` | +| A passkey vault entry (`vaultEntry`) | credential id 16 to 255 bytes, recipient key 32, encapsulated key 32, sealed bundle 32 to 256 (Forge writes 256). An update can loosen the sealed bundle's bounds but never make it fixed-length, and cannot take the credential id past 255 bytes or `version` past 255 (**frozen**). One entry per identity and credential. Fees are estimates until measured: about 46 to 50 million credits (about 0.0005 DASH) for an identity's first entry, 28 to 31 million for a later one, 2 to 3 million to re-seal; a delete refunds about 23 to 35 million, and a sign-in reads only | [forge-v2.md §2](contracts/forge-v2.md#forge-meta-mainnet-set-only) | +| Keys in a passkey vault entry | at most **6**: the main key (a group-bound limited key with a budget and an expiry), up to 4 per-contract wallet grants (each also with a budget and an expiry: an unlimited one stays on its device) and one encryption key (only if asked). At most **10 passkeys** per identity | [Passkey vault](security/passkey-vault.md#what-an-entry-holds) | | Pack download time | each copy gets `max(120 s, size ÷ 1 MiB/s)`; a manifest with no size allows 256 MiB | [Bring your own storage](guides/bring-your-own-storage.md) | | Read-back check after an upload | a full download and SHA-256 up to 16 MiB; larger packs get a size check and byte-exact head and tail ranges | same | | A history or flat index, inflated | 64 MiB | `MAX_INFLATED` in `crates/forge-core/src/pack/historyindex.rs` and `flatindex.rs` | diff --git a/docs/security/passkey-vault.md b/docs/security/passkey-vault.md new file mode 100644 index 000000000..7d295a93c --- /dev/null +++ b/docs/security/passkey-vault.md @@ -0,0 +1,94 @@ +# Passkeys for other devices: the passkey vault and its threat model + +Status: implemented in the web app and inert until forge-meta on a network has the `vaultEntry` type. On testnet and devnet sakura that is a pending `deploy-v2.mjs --update meta` (see [Deployment status](#deployment-status)). The contract is [forge-v2.md §2](../contracts/forge-v2.md#forge-meta-mainnet-set-only), and the user-facing guide is [identity and keys](../guides/identity-and-keys.md#passkeys-for-other-devices). + +## What it is + +A passkey added in the web app holds a copy of the browser's current session keys, encrypted to that passkey, in a public `vaultEntry` on Platform. On another device, **Sign in with a passkey** reads the entry, decrypts it with the passkey, checks every key in it against the identity, and keeps the session in that browser's own vault under the same passkey. + +**Passkeys move a session. They do not recover an account.** The keys inside are the ordinary limited keys Forge signs with: they have a budget and an expiry (a key Forge registers lasts at most a year; a wallet may ask for other limits), and they stop working when they expire, run out or are disabled. Getting a new key still takes the identity file, the recovery phrase or the wallet that granted the old one. A passkey cannot create, renew or top up anything; it only carries across the key you already have. + +## Why the entries are public + +Platform stores documents in the open. An entry's ciphertext is readable by anyone, and stays readable in the state-transition history after the entry is deleted. Everything below follows from that: the protection is the passkey (a PRF output only the authenticator can produce), never the secrecy of the entry. + +## What an entry holds + +One format, always padded to the same size (240 bytes plaintext, 256 sealed), so an entry does not show how many keys it holds or which kind of key is in it. + +| Slot | Holds | Rule | +|---|---|---| +| 0 | The session's main key | AUTHENTICATION, HIGH, secp256k1 or its hash160, **bound to the `dash-forge` contract group, with a budget and an expiry**. A Forge limited key or an App Connect v2 wallet key. | +| 1 to 4 | Live per-contract wallet grants | Only keys with **both a budget and an expiry**. A grant with no spending limit, or no expiry (a v1 wallet's one-contract key), is left out and stays on the device that holds it. Never a key held only to be disabled later. | +| 5 | The identity's usable encryption key | Only when the user ticked "Also keep my encryption key". Off by default, with a warning that it cannot be taken back. | + +Never stored: a MASTER, TRANSFER or CRITICAL key, a key with no bounds, a key bound to something other than Forge's contracts, or a key pasted into a tab ("Advanced"). The extras rule above exists because of the previous section: **a leaked passkey must never yield a key that does not expire or has no spending limit.** The same rule is applied again when an entry is opened, so an entry planted with such a key gets it dropped. + +The web app says so where it matters: the add dialog and the passkeys section read "Keys without a spending limit stay on this device only", and the section counts how many keys that is. + +## Where it works + +A passkey's relying party id is the page's host. Forge allows exactly `forge.dashhq.org` and `localhost` (development and the end-to-end suite), nothing else: + +- Never `dashhq.org`: every subdomain could then ask the browser for the same PRF output and open every entry. +- Not a shared origin (a GitHub Pages project site, an IPFS path gateway) and not an IPFS subdomain gateway (one origin per release, so the passkey would be lost with the next one). +- Not an IP address: WebAuthn does not allow one. The end-to-end suite opens `http://localhost:` for that reason, not `127.0.0.1`. + +The web app hides every passkey control (`platformPasskeyProblem`) wherever the page cannot have them, the browser has no passkeys, the network has no forge-meta, or the deployed forge-meta has no `vaultEntry`. + +## Flows and checks + +**Add** (signed-in session, key kept in the browser, whole vault unlocked in this tab, no staged renewal, fewer than 10 passkeys): make the passkey, confirm it with a second prompt limited to it, derive the recipient key from the confirmed PRF output, seal the keys and write the entry, wait until Platform shows it, then record a local marker (credential id, recipient key, key ids) in IndexedDB. A passkey made but not yet seen on Platform is kept across reloads for **Check again**, or deleted by **Discard** (the entry first, if Platform has it). Writing an entry costs about 0.0005 DASH, paid from the key's budget ([costs](../guides/costs.md#passkeys-for-other-devices)). + +**Sign in on a new device**: one discoverable prompt for any of the site's passkeys; the user handle must be a vault's (64 bytes: identity and forge-meta). A 32-byte handle is a passkey the browser made for its own vault: "This passkey only unlocks the browser that made it." The entry is read with a proof and opened only if the passkey's derived key is the entry's recipient key. Every slot is then checked against the identity read fresh with proofs: + +- slot 0 is on the identity, enabled, matches the private key, is group-bound with a budget left and an expiry still ahead; if it fails, the sign-in is refused with the reason ("disabled", "expired", "no budget left"); +- every extra must pass the same checks and have a budget and an expiry; one that fails is dropped; +- the encryption key is kept only if it is the identity's usable one and matches. + +The keys then go into the browser vault, protected by the same passkey (its local key is derived from the same PRF output under a different label than the entry's). A browser that already keeps a key for the identity stops and offers **Unlock instead**. + +**List and remove**: each passkey shows when it was added, "This device" or "Another device", the key it holds and that key's state, and **Needs update** when it holds an older key. Removing deletes the entry (the deposit comes back) and tells the passkey provider only about this device's own credentials. The key it held stays live. + +**Re-seal**: when this tab changes its keys (a renewal, a new wallet grant, an imported encryption key) the entries this device made are encrypted again, without a prompt, but only if the recipient key on Platform is the one this device recorded. A new encryption key is never added silently: an entry that held the old one shows **Needs update**, and you tick the encryption key again when you update that passkey (the usual reason to replace it is a suspected leak). Other devices' entries show **Needs update**, which asks that passkey once: the key it derives must be the entry's recipient key before anything is sealed to it. + +**Revoke and disable**: the dialogs that disable a key offer to delete the passkeys that name it first, while the key can still sign. That step is best effort: if it fails (this browser's key has no budget left, or Platform is slow) the key is still disabled and the page says which passkeys to remove in Settings. + +**Renewing a restored key**: a passkey does not say who made the key (a wallet or the master key), so a session restored from one is stored with origin `passkey`, and renewal offers both **Renew in your wallet** and **Renew with identity file**. It also follows the wallet-key rule of starting no write in the key's last minutes. A wallet only disables the key of its own earlier grant for the same browser, so renewing a passkey's key in a wallet leaves the restored key live: it is kept here never to sign, is never put into a passkey again, and the next renewal or revoke disables it. + +## Threat model + +**Planted entries.** Any live key the identity has that forge-meta accepts can write an entry for the owner, including a leaked one. HPKE authenticates nobody, so an entry proves nothing by itself. Mitigations: every opened slot is checked against the identity's keys read with proofs; and Forge only encrypts new keys to a recipient key it derived in this tab or that a passkey confirmed (or that this device recorded), so a planted entry cannot trick a user into sealing fresh keys to an attacker's passkey. + +**Stale entries.** A revoked, expired or spent key fails the check, and the sign-in says to sign in another way. Two things outlast it: + +- The encryption key inside stays readable to anyone holding the passkey, and the old ciphertexts stay public in the history for good. Removing the passkey does not lock that person out: the encryption key must be replaced too ([replacing it](../guides/identity-and-keys.md#replacing-it-after-a-lost-device)). That is why it is opt-in with a warning. +- Expiry is the limit of what a passkey can do: it moves a session between devices; it does not recover an account. + +**What is public.** The owner, how many passkeys there are, when each was written or changed, the credential id (its length can hint at the passkey provider) and the `authKeyId`, which says which of the identity's keys is the main one. The fixed size hides how many keys an entry holds and whether it holds a wallet's key or Forge's own. + +**Shared devices.** Every device uses the same key and the same budget, so one device can spend what the others would, and disabling the key signs all of them out. The passkeys section says so. Spending is capped by the key's budget whatever a leaked passkey does. + +**A leaked passkey.** Whoever holds the passkey and can read the public entry gets the keys inside: a group-bound key with a budget and an expiry, and possibly an encryption key. They cannot get a master key, a key without limits, or anything that outlives the expiry. **A top-up of the key (more budget or a later expiry) reaches every passkey that holds it**, because the passkey holds the key, not a copy of its limits: disable the key when a passkey may have leaked, rather than topping it up. Disable the key (Devices & keys, or Revoke) and delete the entry. + +**XSS.** A script injected into the page could ask the user's passkey to seal keys to an attacker without a separate prompt for the attacker's key. It could already read an unlocked key and sign with it, so the exposure is the same; the page's CSP is the defence ([hosting.md](../hosting.md#7-security-headers)). + +**Framing.** There is no `frame-ancestors` header on GitHub Pages ([hosting.md §7](../hosting.md#7-security-headers)), and an attacker's page can delegate `publickey-credentials-get` to a frame. That is one more reason to add the header at the host (Cloudflare in front of Pages can). A framed page never picks up a session, and the policy refuses a shared origin. + +**Weak spots left.** A passkey provider that syncs its passkeys (iCloud Keychain, Google Password Manager) is as safe as that account. A passkey without PRF support cannot be used; the add stops with a clear message. Pending enrolments are settled by looking for the entry on Platform (Yappr's nonce-level settling is not built). + +## Deployment status + +The `vaultEntry` type is in the committed forge-meta (`forge-contracts/contracts/mainnet/forge-meta.json`) but **not yet on devnet sakura or testnet**. On each it is one `DataContractUpdate` of forge-meta, `deploy-v2.mjs --set mainnet --update meta` signed by that network's deployer (on testnet also with `--expect-sha256` over sums the owner signed), followed by `snapshot-contracts.mjs` for the network and a rehearsal that a group-bound limited key can write `vaultEntry`. Testnet lists the flag in its `since` (`build.py` `NETWORK_REGISTRATIONS`), so `--check` still reproduces what testnet registered. None of it has been run: each update needs the owner's approval. On mainnet the type is part of the registration set. + +Until the update lands the feature is **inert**: the web app reads forge-meta from Platform (a proved fetch, which bypasses the bundled snapshot) and shows no passkey tile, no passkeys section and no offer while the contract has no `vaultEntry`. A read that fails also hides them. Nothing breaks and nothing is spent. + +If forge-meta is ever re-registered with a new id (`--force-new`), every passkey stops working: the contract id is in the PRF input and in the user handle. The new contract starts empty, and each user adds passkeys again. + +## Tests + +- The core (`platform-auth`): RFC 9180 vectors, Yappr's and govhub's formats byte for byte, Forge's vectors cross-checked by an independent Python generator, negative cases (wrong passkey, identity, contract, credential; bit flips; padding; slot rules). +- `forge-web/lib/auth/passkey-vault/*.test.ts` and `lib/auth/passkey-session.test.ts`: enrol, sign in, store locally, planted keys refused (not on the identity, disabled, expired, no budget, unbounded, foreign group, **extras without a budget or an expiry**), the "not-vault" and "other-vault" handles, the cap, re-seals that touch only this device's entries, removal that signals only this device's credentials, wiped buffers. +- Component tests for the sign-in tile, the passkeys section, the one-time offer and the revoke and disable dialogs. +- `forge-web/e2e/passkey-vault.spec.ts`: Chromium with a virtual authenticator (CDP `WebAuthn.addVirtualAuthenticator`, PRF) on `http://localhost`. The hermetic cases run anywhere; the full flow needs `E2E_WRITE=1` and a forge-meta with `vaultEntry`. +- `forge-web/lib/auth/passkey-vault.live.test.ts` (`FORGE_LIVE=1`): a fake authenticator against sakura, printing each step's fee. diff --git a/forge-contracts/contracts/mainnet/forge-meta.json b/forge-contracts/contracts/mainnet/forge-meta.json index 4c85f4b31..e5bb9c179 100644 --- a/forge-contracts/contracts/mainnet/forge-meta.json +++ b/forge-contracts/contracts/mainnet/forge-meta.json @@ -669,6 +669,85 @@ "identityId" ], "additionalProperties": false + }, + "vaultEntry": { + "type": "object", + "documentsMutable": true, + "canBeDeleted": true, + "properties": { + "credentialId": { + "type": "array", + "byteArray": true, + "minItems": 16, + "maxItems": 255, + "position": 0 + }, + "recipientKey": { + "type": "bytes", + "size": 32, + "position": 1 + }, + "version": { + "type": "integer", + "minimum": 1, + "maximum": 255, + "position": 2 + }, + "authKeyId": { + "type": "integer", + "minimum": 0, + "maximum": 4294967295, + "position": 3, + "refersTo": { + "type": "identityPublicKey", + "identityProperty": "$ownerId", + "keyRequirements": { + "purpose": "authentication" + } + } + }, + "enc": { + "type": "bytes", + "size": 32, + "position": 4 + }, + "sealed": { + "type": "array", + "byteArray": true, + "minItems": 32, + "maxItems": 256, + "position": 5 + } + }, + "immutable": [ + "credentialId", + "recipientKey" + ], + "indices": [ + { + "name": "byCredential", + "properties": [ + { + "$ownerId": "asc" + }, + { + "credentialId": "asc" + } + ], + "unique": true + } + ], + "required": [ + "$createdAt", + "$updatedAt", + "credentialId", + "recipientKey", + "version", + "authKeyId", + "enc", + "sealed" + ], + "additionalProperties": false } }, "config": { diff --git a/forge-contracts/schema/build.py b/forge-contracts/schema/build.py index ebbe953b6..a7fc4abb7 100644 --- a/forge-contracts/schema/build.py +++ b/forge-contracts/schema/build.py @@ -150,10 +150,17 @@ author_retarget=True, # authorEvent kind 8 + value: the PR author retargets (power R-STACK-1) policy_code_owners=True, # policy.requireCodeOwners: CODEOWNERS approval declared on chain repo_ban=True, # ban: a maintainer's per-repo ban list, applied by readers (TS-08 c) + # ---- UPDATE-2 (on-chain passkey vault): a new document type only, nothing on an existing type. It + # exists in the four-contract set only (it needs `layout_meta`, see below) and lands in forge-meta + # (META_TYPES): on a registered network it ships as `deploy-v2.mjs --update meta`, on one not yet + # registered it is part of the registration set. + passkey_vault=True, # vaultEntry: a passkey-sealed key bundle per (owner, credential id) ) # The UPDATE-1 items: every one off is the registered v1 set (registered/*.v1.json). UPDATE1_FLAGS = ('release_target_oid', 'config_moved_to', 'pack_mirror', 'transition_closed_by_pr', 'profile_key_proofs', 'profile_bot', 'author_retarget', 'policy_code_owners', 'repo_ban') +# The UPDATE-2 items: added after UPDATE-1, so the registered v1 set has them off too (stale_registered). +UPDATE2_FLAGS = ('passkey_vault',) # Each production network's registration (CONT-03): the committed set it registered, and the flags added after # it. `contracts/registered//.v1.json` is a byte copy of what that network registered # (`freeze-registered.mjs` writes it at the registration commit, P4) and the build with the `since` flags off @@ -164,7 +171,7 @@ # registration; a flag that was on and is later turned off cannot be expressed (--check fails loudly). NETWORK_REGISTRATIONS = { # testnet (dash-testnet-51), Platform 5.0.0-rc.8, 2026-10-26: forge-core D2ZLdgghZTKGpES35a3KVDp5necSfZqqRHLSknjRPAV9 - 'testnet': {'set': 'mainnet', 'since': ()}, + 'testnet': {'set': 'mainnet', 'since': ('passkey_vault',)}, } # ---- Mainnet-only (a fresh registration may add them; an update never can: rules, references and # required fields on existing types are frozen, forge-v2.md §9). Off in every devnet build; the mainnet @@ -301,7 +308,7 @@ GRANT_TTL_MS = 90 * 24 * 3600 * 1000 # D44: the types forge-meta takes, from the contract that holds them in the three-contract set META_TYPES = {'forge-collab': ('repoKey', 'ban'), 'forge-core': ('label', 'topic', 'packMirror'), - 'forge-community': ('profile', 'follow')} + 'forge-community': ('profile', 'follow', 'vaultEntry')} # The riders: independent of the RC2 items (other types and properties), so variants.py turns # each off only with every RC2 item on, the largest build. RIDER_FLAGS = ('close_reason', 'review_hunk') @@ -967,6 +974,48 @@ def writer_leaf(t): "unique": True}], "required": ["$createdAt", "repoId", "identityId"], "additionalProperties": False} + # ======================= UPDATE-2 (on-chain passkey vault) ======================= + # A new document type with its own index and no reference to an existing type, so protocol 14 + # lets an update add it (validate_update/v0: new types are validated as at registration). + # Built with the four-contract layout only: it is defined here, in forge-community, and split_meta + # moves it to forge-meta (META_TYPES). Left in the three-contract forge-community it would take that + # contract to 18,385 B (ceiling 17,832) and its create transition to 1,989 B of room (ROOM_MIN 2,000), + # and the three-contract set is the devnet baseline, which no network needs the type in. + if up['passkey_vault'] and f['layout_meta']: + # One passkey-sealed key bundle per (owner, WebAuthn credential). A new device looks its entry up by + # credential id (the unique index byCredential; its $ownerId prefix is an owner's list) and opens + # `sealed` (an HPKE ciphertext, 240 B padded + 16 B tag = 256 B for Forge's one format) with the + # passkey's PRF output. `recipientKey` is the HPKE recipient public key (32 B) the PRF output derives + # and `enc` the HPKE encapsulated key (32 B). The ciphertext's AAD binds `credentialId`, `recipientKey`, + # `version` and `authKeyId`; `credentialId` and `recipientKey` are immutable (which passkey, and which + # recipient, the entry is for), and a re-seal (a replace) changes `enc`, `sealed`, `version` and + # `authKeyId` only. `authKeyId` names the owner's authentication key that slot 0 of the bundle stands + # for; Platform checks it is such a key of the owner on create and on a replace that changes it. + # What an update cannot change later: `recipientKey` and `enc` stay exactly 32 B and `sealed` stays + # variable-length (a byte array's fixed/variable encoding is held), `version` stays within a u8, and + # `credentialId` within 255 B (it is indexed); `minItems` and `maxItems` of `sealed` can be loosened. + # Mutable (a re-seal) and deletable (removing a passkey; the storage deposit is refunded). No rule + # reads any of it, so no `propertyConstraints`: the bounds are the schema's. + BYTES32 = {"type": "array", "byteArray": True, "minItems": 32, "maxItems": 32} + md['vaultEntry'] = { + "type": "object", "documentsMutable": True, "canBeDeleted": True, + "properties": { + "credentialId": {"type": "array", "byteArray": True, "minItems": 16, "maxItems": 255, "position": 0}, + "recipientKey": dict(BYTES32, position=1), + "version": {"type": "integer", "minimum": 1, "maximum": 255, "position": 2}, + "authKeyId": {"type": "integer", "minimum": 0, "maximum": 4294967295, "position": 3, + "refersTo": {"type": "identityPublicKey", "identityProperty": "$ownerId", + "keyRequirements": {"purpose": "authentication"}}}, + "enc": dict(BYTES32, position=4), + "sealed": {"type": "array", "byteArray": True, "minItems": 32, "maxItems": 256, "position": 5}}, + "immutable": ["credentialId", "recipientKey"], + "indices": [ + # One entry per (owner, credential): the sign-in lookup (both bound) and an owner's + # list (the $ownerId prefix) + {"name": "byCredential", "properties": [{"$ownerId": "asc"}, {"credentialId": "asc"}], "unique": True}], + "required": ["$createdAt", "$updatedAt", "credentialId", "recipientKey", "version", "authKeyId", "enc", "sealed"], + "additionalProperties": False} + # ======================= mixed visibility (DESIGN rev 4.1 §8.3) ======================= # A fresh registration only: each adds a rule, a reference or a required field to a type that # exists, which no update can (§9). Row numbers are DESIGN §8.2's; forge-v2.md §9.1 has each. @@ -1536,11 +1585,11 @@ def stale_registered(registered_root, registrations): or an entry with no directory, is stale: what a network registered is frozen in the same commit that names it.""" stale = [] - v1 = build(flags_from(','.join(UPDATE1_FLAGS))) + v1 = build(flags_from(','.join(UPDATE1_FLAGS + UPDATE2_FLAGS))) for n in NAMES: p = os.path.join(registered_root, f'{n}.v1.json') if not os.path.exists(p) or open(p).read() != dumps(v1[n]): - stale.append((p, 'is not the build with every UPDATE-1 flag off')) + stale.append((p, 'is not the build with every UPDATE-1 and UPDATE-2 flag off')) dirs = sorted(d for d in os.listdir(registered_root) if os.path.isdir(os.path.join(registered_root, d))) \ if os.path.isdir(registered_root) else [] for d in dirs: diff --git a/forge-contracts/schema/vectors.py b/forge-contracts/schema/vectors.py index 06cfa8afa..0237f0cd8 100644 --- a/forge-contracts/schema/vectors.py +++ b/forge-contracts/schema/vectors.py @@ -891,6 +891,46 @@ def sealed_release(name): else: index('U1', 'no ban type', 'ban', None, False) +# ---------------- UPDATE-2: the passkey vault's vaultEntry ---------------- +# A new type with no rule, so only its shapes refuse. That the authKeyId names an authentication key of +# the owner is a reference, judged on chain (the live suite). +CONTRACT_OF.update(vaultEntry='forge-community') +if F['passkey_vault'] and F['layout_meta']: # (build.py builds it with the four-contract layout only) + BASE['vaultEntry'] = {"credentialId": b(1, 32), "recipientKey": b(2, 32), "version": 1, "authKeyId": 1, "enc": b(3, 32), + "sealed": b(4, 256)} + ok('base', 'vaultEntry ok', 'vaultEntry') + ok('U2', 'a credential id of 16 bytes', 'vaultEntry', credentialId=b(1, 16)) + ok('U2', 'a credential id of 255 bytes', 'vaultEntry', credentialId=b(1, 255)) + no('U2', 'a credential id of 15 bytes', 'vaultEntry', 'minItems', credentialId=b(1, 15)) + no('U2', 'a credential id of 256 bytes', 'vaultEntry', 'maxItems', credentialId=b(1, 256)) + no('U2', 'a recipient key of 31 bytes', 'vaultEntry', 'minItems', recipientKey=b(2, 31)) + no('U2', 'a recipient key of 33 bytes', 'vaultEntry', 'maxItems', recipientKey=b(2, 33)) + no('U2', 'an encapsulated key of 31 bytes', 'vaultEntry', 'minItems', enc=b(3, 31)) + no('U2', 'an encapsulated key of 33 bytes', 'vaultEntry', 'maxItems', enc=b(3, 33)) + ok('U2', 'a sealed bundle of the 32-byte minimum', 'vaultEntry', sealed=b(4, 32)) + no('U2', 'a sealed bundle of 31 bytes', 'vaultEntry', 'minItems', sealed=b(4, 31)) + no('U2', 'a sealed bundle of 257 bytes', 'vaultEntry', 'maxItems', sealed=b(4, 257)) + ok('U2', 'version 255', 'vaultEntry', version=255) + no('U2', 'version 0', 'vaultEntry', 'minimum', version=0) + no('U2', 'version 256', 'vaultEntry', 'maximum', version=256) + ok('U2', 'authKeyId 0', 'vaultEntry', authKeyId=0) + ok('U2', 'authKeyId 4294967295', 'vaultEntry', authKeyId=4294967295) + no('U2', 'authKeyId -1', 'vaultEntry', 'minimum', authKeyId=-1) + no('U2', 'authKeyId 4294967296', 'vaultEntry', 'maximum', authKeyId=4294967296) + for _p in ('credentialId', 'recipientKey', 'version', 'authKeyId', 'enc', 'sealed'): + no('U2', f'an entry without {_p}', 'vaultEntry', 'required', **{_p: DROP}) + no('U2', 'an entry with another property', 'vaultEntry', 'additionalProperties', label='phone') + # A re-seal replaces enc, sealed, version and authKeyId; which passkey and which recipient the entry is for never changes + _STORED = doc('vaultEntry') + replace('U2', 're-seal: enc, sealed, version and authKeyId change', 'vaultEntry', _STORED, None, + enc=b(7, 32), sealed=b(8, 256), version=2, authKeyId=3) + replace('U2', 'credentialId changed (immutable)', 'vaultEntry', _STORED, '40128', credentialId=b(9, 32)) + replace('U2', 'recipientKey changed (immutable)', 'vaultEntry', _STORED, '40128', recipientKey=b(9, 32)) + index('U2', 'one entry per owner and credential', 'vaultEntry', 'byCredential', True, + properties=['$ownerId', 'credentialId'], unique=True) +else: + index('U2', 'no vaultEntry type', 'vaultEntry', None, False) + # ---------------- the other mainnet-only rules (forge-v2.md §9.1) ---------------- if F['mainnet_release_target']: no('MN', 'a public publish without targetOid', 'release', 'targetOnPublish', targetOid=DROP) diff --git a/forge-contracts/scripts/lib/offline-chain.test.mjs b/forge-contracts/scripts/lib/offline-chain.test.mjs index 539aadeb1..da05b20e7 100644 --- a/forge-contracts/scripts/lib/offline-chain.test.mjs +++ b/forge-contracts/scripts/lib/offline-chain.test.mjs @@ -188,8 +188,11 @@ test('the deployment record picks the layout: forge-meta holds the moved types o const three = { core: 'C', collab: 'L', community: 'M' }; const four = { ...three, meta: 'X' }; for (const t of META_TYPES) { - assert.ok(CONTRACT_OF[t], `${t} has a three-contract home`); - assert.equal(contractOn(three, t), CONTRACT_OF[t], t); + // (vaultEntry, UPDATE-2, is a four-contract type: no home in the three-contract set) + if (t !== 'vaultEntry') { + assert.ok(CONTRACT_OF[t], `${t} has a three-contract home`); + assert.equal(contractOn(three, t), CONTRACT_OF[t], t); + } assert.equal(contractOn(four, t), 'meta', t); } for (const t of ['repo', 'issue', 'star', 'event']) assert.equal(contractOn(four, t), CONTRACT_OF[t], t); diff --git a/forge-contracts/scripts/lib/seed-io.mjs b/forge-contracts/scripts/lib/seed-io.mjs index 33408a0b6..4cf3e79ec 100644 --- a/forge-contracts/scripts/lib/seed-io.mjs +++ b/forge-contracts/scripts/lib/seed-io.mjs @@ -45,10 +45,10 @@ export const CONTRACT_OF = DEFAULT_SET.contractOf; /** * The types forge-meta holds on a four-contract set (DESIGN rev 4.1 D44); a three-contract set - * keeps them in their `CONTRACT_OF` homes. Parity: forge-core `layout::META_TYPES`, forge-web - * `lib/layout.ts`. + * keeps them in their `CONTRACT_OF` homes, except `vaultEntry` (UPDATE-2, the passkey vault), which + * only the four-contract set has. Parity: forge-core `layout::META_TYPES`, forge-web `lib/layout.ts`. */ -export const META_TYPES = new Set(['repoKey', 'ban', 'label', 'topic', 'packMirror', 'profile', 'follow']); +export const META_TYPES = new Set(['repoKey', 'ban', 'label', 'topic', 'packMirror', 'profile', 'follow', 'vaultEntry']); /** * The contract (`core`, `collab`, `community`, `meta`) that holds `type` on the network whose ids diff --git a/forge-contracts/scripts/lib/seed-io.test.mjs b/forge-contracts/scripts/lib/seed-io.test.mjs index 77fec85f3..2b01df0e9 100644 --- a/forge-contracts/scripts/lib/seed-io.test.mjs +++ b/forge-contracts/scripts/lib/seed-io.test.mjs @@ -35,7 +35,8 @@ test('the committed mainnet set is four contracts, forge-meta last', () => { test('a three-contract record keeps the moved types in their old homes', () => { const ids = { core: 'c', collab: 'l', community: 'm' }; - for (const t of META_TYPES) assert.equal(contractOn(ids, t), CONTRACT_OF[t], t); + // (vaultEntry, UPDATE-2, is a four-contract type: the three-contract set has no home for it) + for (const t of META_TYPES) if (t !== 'vaultEntry') assert.equal(contractOn(ids, t), CONTRACT_OF[t], t); }); // ---- the shape of a loaded set decides the fields a write carries (DESIGN MB1) ---- diff --git a/forge-contracts/vectors/rc1/forge-community.indices.json b/forge-contracts/vectors/rc1/forge-community.indices.json index 65a741886..418464e54 100644 --- a/forge-contracts/vectors/rc1/forge-community.indices.json +++ b/forge-contracts/vectors/rc1/forge-community.indices.json @@ -37,6 +37,12 @@ "type": "starBeat", "expect": "absent" }, + { + "item": "U2", + "name": "no vaultEntry type", + "type": "vaultEntry", + "expect": "absent" + }, { "item": "EVK", "name": "no byKind index", diff --git a/forge-web/components/app-shell.tsx b/forge-web/components/app-shell.tsx index 7f182a983..6007ac2b2 100644 --- a/forge-web/components/app-shell.tsx +++ b/forge-web/components/app-shell.tsx @@ -18,6 +18,7 @@ import { useContractsMissing } from '@/hooks/use-sdk' import { useOfflineNavigation } from '@/hooks/use-offline-navigation' import { PAGES_NOTICE } from '@/lib/pages-notice' import { LowFundsBanner } from '@/components/low-funds-banner' +import { PasskeyOffer } from '@/components/passkey-offer' import { ClockSkewBanner } from '@/components/clock-skew-banner' import { LoginModal } from '@/components/login-modal' import { PlatformBusy } from '@/components/platform-busy' @@ -54,6 +55,7 @@ export function AppShell({ +
void; onUnlock: () => void }): JSX.Element | null { + const { platformPasskeyProblem, signInWithPasskey, isLoading, step } = useAuth() + const [failure, setFailure] = useState<{ message: string; held: boolean } | null>(null) + // Anything but a clean null hides it: the check has not run, or it said no. + if (platformPasskeyProblem !== null) return null + const go = async (): Promise => { + if (isLoading) return + setFailure(null) + try { + await signInWithPasskey() + onDone() + } catch (e) { + setFailure({ message: errorMessage(e), held: e instanceof PlatformPasskeyError && e.code === 'held' }) + } + } + return ( +
+ void go()} + /> + {isLoading && step ? ( +

+ {step}… +

+ ) : null} + + {failure?.held ? ( + + ) : null} +
+ ) +} diff --git a/forge-web/components/auth/passkeys-section.test.tsx b/forge-web/components/auth/passkeys-section.test.tsx new file mode 100644 index 000000000..dfb615c67 --- /dev/null +++ b/forge-web/components/auth/passkeys-section.test.tsx @@ -0,0 +1,301 @@ +// @vitest-environment jsdom +/** + * Settings → Devices & keys → Passkeys: hidden unless passkeys are offered here and the key is + * kept in this browser; lists the identity's passkeys (this device or another, the key each holds + * and its state); adds one (the encryption key off by default, with the warning that it cannot be + * taken back); updates, removes (confirm first), finishes ("Check again") and discards one; says + * which keys stay on this device only; and asks a resumed tab to unlock before carrying on. + */ + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { UnlockNeededError } from '@/lib/auth/controller' +import { PlatformPasskeyError, type PlatformPasskeyRow } from '@/lib/auth/passkey-vault/service' + +const ID = '9r27eDsuXEqoMNymW1A2MKFrpBhzSkepVKwXrGzq9dUD' + +const row = (id: string, o: Partial = {}): PlatformPasskeyRow => ({ + id, + addedAt: Date.UTC(2026, 9, 1), + updatedAt: Date.UTC(2026, 9, 1), + thisDevice: false, + keyId: 5, + keyState: 'live', + current: true, + needsUpdate: false, + encryptionKey: false, + ...o, +}) + +const auth = { + problem: null as string | null, + storage: 'vault' as 'vault' | 'session', + holdsEncryption: false, + rows: [] as PlatformPasskeyRow[], + pending: null as { id: string } | null, + leftOut: 0, + listPlatformPasskeys: async (): Promise => auth.rows, + pendingPlatformPasskey: async () => auth.pending, + platformPasskeyLeftOut: async () => auth.leftOut, + addPlatformPasskey: vi.fn(async (_o?: unknown): Promise => undefined), + finishPlatformPasskey: vi.fn(async (): Promise => undefined), + abandonPlatformPasskey: vi.fn(async (): Promise => undefined), + removePlatformPasskey: vi.fn(async (_id: string): Promise => undefined), + resealPlatformPasskeys: vi.fn(async (_o?: unknown) => ({ resealed: 1, needUpdate: 0 })), + unlockMore: vi.fn(async (_m: unknown): Promise => undefined), +} + +vi.mock('@/contexts/auth-context', () => ({ + useAuth: () => ({ + identity: ID, + storage: auth.storage, + platformPasskeyProblem: auth.problem, + isLoading: false, + unlockScope: 'full', + locked: false, + vaults: [{ identityId: ID, keyId: 5, createdAt: 0, methods: ['passphrase'], ...(auth.holdsEncryption ? { encryptionKey: true } : {}) }], + listPlatformPasskeys: auth.listPlatformPasskeys, + pendingPlatformPasskey: auth.pendingPlatformPasskey, + platformPasskeyLeftOut: auth.platformPasskeyLeftOut, + addPlatformPasskey: auth.addPlatformPasskey, + finishPlatformPasskey: auth.finishPlatformPasskey, + abandonPlatformPasskey: auth.abandonPlatformPasskey, + removePlatformPasskey: auth.removePlatformPasskey, + resealPlatformPasskeys: auth.resealPlatformPasskeys, + controller: { unlockMore: auth.unlockMore }, + }), +})) + +const { PasskeysSection } = await import('./passkeys-section') +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +let host: HTMLDivElement +let root: Root + +const q = (sel: string): T | null => document.querySelector(sel) +const buttonIn = (scope: ParentNode, text: RegExp): HTMLButtonElement => [...scope.querySelectorAll('button')].find((b) => text.test(b.textContent ?? '')) as HTMLButtonElement +async function settle(): Promise { + await act(async () => { + await Promise.resolve() + await Promise.resolve() + await Promise.resolve() + }) +} +async function render(): Promise { + await act(async () => root.render()) + await settle() +} +async function click(el: Element | null): Promise { + expect(el).not.toBeNull() + await act(async () => (el as HTMLElement).click()) + await settle() +} + +beforeEach(() => { + auth.problem = null + auth.storage = 'vault' + auth.holdsEncryption = false + auth.rows = [] + auth.pending = null + auth.leftOut = 0 + for (const f of [auth.addPlatformPasskey, auth.finishPlatformPasskey, auth.abandonPlatformPasskey, auth.removePlatformPasskey, auth.resealPlatformPasskeys, auth.unlockMore]) f.mockClear() + host = document.createElement('div') + document.body.appendChild(host) + root = createRoot(host) +}) +afterEach(() => { + act(() => root.unmount()) + host.remove() + document.body.innerHTML = '' +}) + +describe('the passkeys section', () => { + it('is hidden while passkeys are not offered, and for a key that is not kept in this browser', async () => { + auth.problem = "Passkeys that work on your other devices aren't available on this network yet." + await render() + expect(q('[data-testid="passkeys-section"]')).toBeNull() + auth.problem = null + auth.storage = 'session' + await render() + expect(q('[data-testid="passkeys-section"]')).toBeNull() + }) + + it('says what a passkey is and is not, and that every device shares one key and budget', async () => { + await render() + expect(q('[data-testid="passkeys-explain"]')!.textContent).toMatch(/moves this sign-in to another device\. It doesn't recover an account/) + expect(q('[data-testid="passkeys-shared"]')!.textContent).toMatch(/Every device shares the same key and budget, so disabling the key signs them all out/) + expect(q('[data-testid="passkeys-empty"]')).not.toBeNull() + }) + + it('lists each passkey: this device or another, when, and the key it holds', async () => { + auth.rows = [ + row('mine', { thisDevice: true, encryptionKey: true }), + row('old', { keyId: 3, keyState: 'disabled', current: false, needsUpdate: true }), + row('gone', { keyId: 2, keyState: 'missing', current: false, needsUpdate: true }), + ] + await render() + const rows = [...document.querySelectorAll('[data-testid="passkey-row"]')] + expect(rows.map((r) => r.getAttribute('data-passkey-id'))).toEqual(['mine', 'old', 'gone']) + expect(rows[0]!.textContent).toMatch(/This device/) + expect(rows[0]!.textContent).toMatch(/Holds your encryption key/) + expect(rows[0]!.textContent).toMatch(/Holds this browser's key, #5/) + expect(rows[0]!.textContent).not.toMatch(/Needs update/) + expect(rows[1]!.textContent).toMatch(/Another device/) + expect(rows[1]!.textContent).toMatch(/Needs update/) + expect(rows[1]!.textContent).toMatch(/key #3, which was disabled/) + expect(rows[2]!.textContent).toMatch(/key #2, which your identity no longer shows/) + }) + + it('says which keys stay on this device only', async () => { + auth.leftOut = 2 + await render() + expect(q('[data-testid="passkeys-left-out"]')!.textContent).toMatch(/Keys without a spending limit stay on this device only\. 2 keys here have no limit or no expiry/) + // Read again on a fresh mount. + auth.leftOut = 0 + act(() => root.unmount()) + root = createRoot(host) + await render() + expect(q('[data-testid="passkeys-left-out"]')).toBeNull() + }) +}) + +describe('adding a passkey', () => { + const open = async (): Promise => { + await render() + await click(q('[data-testid="passkey-add"]')) + } + + it('adds one without the encryption key by default', async () => { + await open() + expect(q('[data-testid="passkey-add-dialog"]')!.textContent).toMatch(/You approve twice/) + expect(q('[data-testid="cost-preview"]')).not.toBeNull() + expect(q('[data-testid="passkey-encryption-warning"]')).toBeNull() + await click(q('[data-testid="passkey-add-confirm"]')) + expect(auth.addPlatformPasskey).toHaveBeenCalledWith({ includeEncryptionKey: false }) + // Done: the dialog is gone and the list was read again. + expect(q('[data-testid="passkey-add-dialog"]')).toBeNull() + }) + + it('cannot add the encryption key a browser does not hold, and says where to get it', async () => { + await open() + expect(q('[data-testid="passkey-include-encryption"]')!.disabled).toBe(true) + expect(q('[data-testid="passkey-add-dialog"]')!.textContent).toMatch(/doesn't hold your encryption key/) + }) + + it('warns that the encryption key cannot be taken back, and sends the choice', async () => { + auth.holdsEncryption = true + await open() + await click(q('[data-testid="passkey-include-encryption"]')) + expect(q('[data-testid="passkey-encryption-warning"]')!.textContent).toMatch(/Removing the passkey later can't take the encryption key back/) + await click(q('[data-testid="passkey-add-confirm"]')) + expect(auth.addPlatformPasskey).toHaveBeenCalledWith({ includeEncryptionKey: true }) + }) + + it('explains when some keys are left out', async () => { + auth.leftOut = 1 + await open() + expect(q('[data-testid="passkey-add-left-out"]')!.textContent).toBe('Keys without a spending limit stay on this device only.') + }) + + it('shows a refusal in the dialog (a key a passkey may not hold)', async () => { + auth.addPlatformPasskey.mockRejectedValueOnce(new PlatformPasskeyError("This sign-in's key has no spending limit or expiry, so it can't be kept with a passkey.", 'ineligible')) + await open() + await click(q('[data-testid="passkey-add-confirm"]')) + expect(q('[data-testid="passkey-add-dialog"] [role="alert"]')!.textContent).toMatch(/no spending limit or expiry/) + expect(q('[data-testid="passkey-add-dialog"]')).not.toBeNull() + }) + + it('a passkey made but not yet seen on Platform closes the dialog and offers "Check again"', async () => { + auth.addPlatformPasskey.mockImplementationOnce(async () => { + auth.pending = { id: 'new' } + throw new PlatformPasskeyError("The passkey was added, but Platform doesn't show it yet. Check again in a minute.", 'pending') + }) + await open() + await click(q('[data-testid="passkey-add-confirm"]')) + expect(q('[data-testid="passkey-add-dialog"]')).toBeNull() + expect(q('[data-testid="passkey-pending"]')!.textContent).toMatch(/isn't on Platform yet/) + // One unfinished passkey at a time. + expect(q('[data-testid="passkey-add"]')!.disabled).toBe(true) + }) + + it('a resumed tab unlocks first, then adds', async () => { + auth.addPlatformPasskey.mockRejectedValueOnce(new UnlockNeededError('unlock first')) + await open() + await click(q('[data-testid="passkey-add-confirm"]')) + expect(q('[data-testid="passkey-add-unlock"]')).not.toBeNull() + // The unlock is no form inside the add's form (its button would submit the add instead). + expect(document.querySelector('form form')).toBeNull() + expect(q('[data-testid="passkey-add-confirm"]')!.disabled).toBe(true) + const pass = q('#passkey-add-unlock-passphrase')! + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(pass, 'fake-passphrase-not-real-123') + act(() => pass.dispatchEvent(new Event('input', { bubbles: true }))) + await click(buttonIn(q('[data-testid="passkey-add-unlock"]')!, /^Unlock$/)) + expect(auth.unlockMore).toHaveBeenCalledWith({ passphrase: 'fake-passphrase-not-real-123' }) + expect(auth.addPlatformPasskey).toHaveBeenCalledTimes(2) + }) +}) + +describe('managing passkeys', () => { + it('"Needs update" asks that passkey once and re-saves the current keys into it', async () => { + auth.rows = [row('old', { keyId: 3, current: false, needsUpdate: true }), row('fine')] + await render() + expect(document.querySelectorAll('[data-testid="passkey-update"]')).toHaveLength(1) + await click(q('[data-testid="passkey-update"]')) + expect(auth.resealPlatformPasskeys).toHaveBeenCalledWith({ id: 'old' }) + }) + + it('removes a passkey only after a confirm that says the key keeps working', async () => { + auth.rows = [row('mine', { thisDevice: true })] + await render() + await click(q('[data-testid="passkey-remove"]')) + expect(auth.removePlatformPasskey).not.toHaveBeenCalled() + expect(q('[role="dialog"]')!.textContent).toMatch(/The key it held keeps working/) + await click(q('[data-testid="confirm-action"]')) + expect(auth.removePlatformPasskey).toHaveBeenCalledWith('mine') + }) + + it('keeps it when the confirm is cancelled', async () => { + auth.rows = [row('mine', { thisDevice: true })] + await render() + await click(q('[data-testid="passkey-remove"]')) + await click(buttonIn(document, /^Cancel$/)) + expect(auth.removePlatformPasskey).not.toHaveBeenCalled() + }) + + it('"Check again" finishes an unfinished passkey; "Discard" gives it up after a confirm', async () => { + auth.pending = { id: 'new' } + await render() + await click(q('[data-testid="passkey-check-again"]')) + expect(auth.finishPlatformPasskey).toHaveBeenCalledTimes(1) + await click(q('[data-testid="passkey-discard"]')) + expect(auth.abandonPlatformPasskey).not.toHaveBeenCalled() + expect(q('[role="dialog"]')!.textContent).toMatch(/entry is deleted first/) + await click(q('[data-testid="confirm-action"]')) + expect(auth.abandonPlatformPasskey).toHaveBeenCalledTimes(1) + }) + + it('shows what went wrong, in the controller’s words', async () => { + auth.rows = [row('old', { needsUpdate: true, current: false })] + auth.resealPlatformPasskeys.mockRejectedValueOnce(new PlatformPasskeyError("This passkey doesn't open its entry on Platform. Sign in another way (your identity file, recovery phrase or wallet), then add the passkey again.", 'refused')) + await render() + await click(q('[data-testid="passkey-update"]')) + expect(q('[role="alert"]')!.textContent).toMatch(/doesn't open its entry on Platform/) + }) + + it('a resumed tab unlocks, then runs the update again', async () => { + auth.rows = [row('old', { needsUpdate: true, current: false })] + auth.resealPlatformPasskeys.mockRejectedValueOnce(new UnlockNeededError('unlock first')) + await render() + await click(q('[data-testid="passkey-update"]')) + expect(q('[data-testid="passkeys-unlock"]')).not.toBeNull() + const pass = q('#passkeys-unlock-passphrase')! + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(pass, 'fake-passphrase-not-real-123') + act(() => pass.dispatchEvent(new Event('input', { bubbles: true }))) + await click(buttonIn(q('[data-testid="passkeys-unlock"]')!, /^Unlock$/)) + expect(auth.resealPlatformPasskeys).toHaveBeenCalledTimes(2) + expect(q('[data-testid="passkeys-unlock"]')).toBeNull() + }) +}) + diff --git a/forge-web/components/auth/passkeys-section.tsx b/forge-web/components/auth/passkeys-section.tsx new file mode 100644 index 000000000..a9d4e9995 --- /dev/null +++ b/forge-web/components/auth/passkeys-section.tsx @@ -0,0 +1,352 @@ +'use client' + +/** + * Settings → Devices & keys → Passkeys: the passkeys that hold this browser's key on Platform, so + * another device signs in with one. List them (this device or another, the key each holds and its + * state), add one (two prompts), update one that holds an older key, remove one, and finish or + * discard one that was made but not yet seen on Platform ("Check again"). + * + * Every device shares the same key and budget: disabling the key signs all of them out. A passkey + * moves a session. It does not recover an account: when the key expires, the identity file or + * recovery phrase renews it. Entries stay public on Platform for good, so a passkey holds only keys + * with a spending limit and an expiry, and the encryption key only when asked. + * + * Hidden while `platformPasskeyProblem` is not null, and for a key that is not kept in this + * browser. A resumed tab asks for an unlock (`UnlockNeededError`), then carries on. + */ + +import { useCallback, useEffect, useState } from 'react' +import { Fingerprint, Plus, RefreshCw, Trash2 } from 'lucide-react' +import { useAuth } from '@/contexts/auth-context' +import { Dialog } from '@/components/ui/dialog' +import { Button } from '@/components/ui/button' +import { CostPreview } from '@/components/ui/cost-preview' +import { useConfirmAction } from '@/components/ui/confirm-action' +import { ErrorBox } from '@/components/auth/protection-fields' +import { UnlockMore } from '@/components/auth/unlock-more' +import { Spinner } from '@/components/ui/states' +import { UnlockNeededError } from '@/lib/auth/controller' +import { PlatformPasskeyError, type PlatformPasskeyRow } from '@/lib/auth/passkey-vault/service' +import { DOCS } from '@/lib/docs-links' +import { previewCreate, previewDelete } from '@/lib/sdk/cost' +import { formatDate } from '@/lib/view/format' +import { cn, errorMessage } from '@/lib/utils' + +/** The anchor the one-time offer links to. */ +export const PASSKEYS_ANCHOR = 'passkeys' + +export function PasskeysSection(): JSX.Element | null { + const { identity, storage, platformPasskeyProblem } = useAuth() + if (identity === null || storage !== 'vault' || platformPasskeyProblem !== null) return null + // Keyed by identity: another identity's passkeys never show under this one's. + return +} + +/** Words for the key a passkey holds and its state. */ +function keyWords(row: PlatformPasskeyRow): string { + switch (row.keyState) { + case 'disabled': + return `key #${row.keyId}, which was disabled` + case 'expired': + return `key #${row.keyId}, which has expired` + case 'missing': + return `key #${row.keyId}, which your identity no longer shows` + default: + return row.current ? `this browser's key, #${row.keyId}` : `key #${row.keyId}` + } +} + +function PasskeysPanel(): JSX.Element { + const { listPlatformPasskeys, pendingPlatformPasskey, platformPasskeyLeftOut, removePlatformPasskey, resealPlatformPasskeys, finishPlatformPasskey, abandonPlatformPasskey } = useAuth() + const [rows, setRows] = useState(null) + const [loadError, setLoadError] = useState(null) + const [pending, setPending] = useState(null) + const [leftOut, setLeftOut] = useState(0) + const [busy, setBusy] = useState(null) + const [error, setError] = useState(null) + const [adding, setAdding] = useState(false) + // A passkey action that found this tab holding only its signing key: unlock, then run it again. + const [unlockThen, setUnlockThen] = useState<(() => void) | null>(null) + const [confirm, confirmDialog] = useConfirmAction() + + const load = useCallback(() => { + setLoadError(null) + listPlatformPasskeys().then(setRows, (e: unknown) => setLoadError(errorMessage(e))) + pendingPlatformPasskey().then((p) => setPending(p?.id ?? null), () => undefined) + platformPasskeyLeftOut().then(setLeftOut, () => undefined) + }, [listPlatformPasskeys, pendingPlatformPasskey, platformPasskeyLeftOut]) + useEffect(load, [load]) + + /** Run one passkey action; true when it finished. */ + const attempt = async (key: string, run: () => Promise): Promise => { + setBusy(key) + setError(null) + try { + await run() + return true + } catch (e) { + if (e instanceof UnlockNeededError) setUnlockThen(() => () => void attempt(key, run)) + else setError(errorMessage(e)) + return false + } finally { + setBusy(null) + load() + } + } + + const remove = async (row: PlatformPasskeyRow): Promise => { + const ok = await confirm({ + title: 'Remove this passkey?', + body: 'It stops signing anyone in on new devices. The key it held keeps working, and so does anything already copied from it. Its deposit comes back.', + confirmLabel: 'Remove passkey', + }) + if (ok) await attempt(`remove:${row.id}`, () => removePlatformPasskey(row.id)) + } + + const discard = async (): Promise => { + const ok = await confirm({ + title: 'Discard the unfinished passkey?', + body: "If Platform already has its entry, that entry is deleted first. The passkey then stays in your passkey provider's list until you delete it there.", + confirmLabel: 'Discard', + }) + if (ok) await attempt('discard', () => abandonPlatformPasskey()) + } + + return ( +
+

+ Passkeys for other devices +

+

+ A passkey moves this sign-in to another device. It doesn't recover an account: when the key expires, renew it with your identity file or recovery phrase. +

+

+ Every device shares the same key and budget, so disabling the key signs them all out. Renewing it replaces the key for every device too.{' '} + + How passkeys work → + +

+ {leftOut > 0 ? ( +

+ Keys without a spending limit stay on this device only. {leftOut === 1 ? '1 key here has' : `${leftOut} keys here have`} no limit or no expiry, so no passkey holds {leftOut === 1 ? 'it' : 'them'}. +

+ ) : null} + + {loadError !== null ? : null} + {rows === null && loadError === null ? : null} + {rows !== null && rows.length === 0 && pending === null ? ( +

+ No passkeys yet. +

+ ) : null} + + {pending !== null ? ( +
+

A passkey you added isn't on Platform yet. Check again in a minute, or discard it.

+
+ + +
+
+ ) : null} + + {rows !== null && rows.length > 0 ? ( +
    + {rows.map((row) => ( +
  • +
    + {row.thisDevice ? 'This device' : 'Another device'} + {row.needsUpdate ? Needs update : null} + {row.encryptionKey ? Holds your encryption key : null} +
    +

    + {row.addedAt !== null ? `Added ${formatDate(row.addedAt)}. ` : ''}Holds {keyWords(row)}. +

    +
    + {row.needsUpdate ? ( + + ) : null} + +
    +
  • + ))} +
+ ) : null} + {rows?.some((r) => r.needsUpdate) ? ( +

+ Update asks for that passkey once, then saves this browser's current keys into it. +

+ ) : null} + + {unlockThen !== null ? ( + { + const again = unlockThen + setUnlockThen(null) + again() + }} + /> + ) : null} + + + + {pending !== null ?

Finish or discard the passkey above first.

: null} + + {adding ? ( + { + setAdding(false) + load() + }} + /> + ) : null} + {confirmDialog} +
+ ) +} + +function Chip({ tone, children }: { tone: 'caution' | 'muted'; children: React.ReactNode }): JSX.Element { + return ( + + {children} + + ) +} + +/** + * Add a passkey: what it holds, the choice of the encryption key (off, with the warning that a + * written entry cannot be taken back), what it costs, then the two prompts. A resumed tab unlocks + * first and carries on; a passkey made but not yet seen on Platform closes the dialog and shows + * "Check again" in the section. + */ +function AddPasskeyDialog({ leftOut, onClose }: { leftOut: number; onClose: () => void }): JSX.Element { + const { identity, vaults, addPlatformPasskey, isLoading } = useAuth() + const holdsEncryption = vaults.find((v) => v.identityId === identity)?.encryptionKey === true + const [withEncryption, setWithEncryption] = useState(false) + const [error, setError] = useState(null) + const [working, setWorking] = useState(false) + const [needsUnlock, setNeedsUnlock] = useState(false) + + const add = async (): Promise => { + if (working) return + setWorking(true) + setError(null) + try { + await addPlatformPasskey({ includeEncryptionKey: withEncryption }) + onClose() + } catch (e) { + if (e instanceof UnlockNeededError) setNeedsUnlock(true) + else if (e instanceof PlatformPasskeyError && e.code === 'pending') { + // Made, not seen yet: the section offers "Check again". + onClose() + return + } else setError(errorMessage(e)) + } finally { + setWorking(false) + } + } + + return ( + +
+ {/* Outside the form: nested in it, the unlock's button would submit the add instead. */} + {needsUnlock ? ( + { + setNeedsUnlock(false) + void add() + }} + /> + ) : null} +
{ + e.preventDefault() + void add() + }} + > +

You approve twice: once to make the passkey, once to confirm it. It works only on Forge's own address.

+ + {withEncryption ? ( +

+ Removing the passkey later can't take the encryption key back. Anyone who has the passkey keeps it until you replace that key. +

+ ) : null} + {leftOut > 0 ? ( +

+ Keys without a spending limit stay on this device only. +

+ ) : null} +
+ +

+ Paid from this browser's key budget. Removing the passkey refunds about {Math.abs(previewDelete('vaultEntry').dash).toFixed(4)} DASH. +

+
+ +
+ + +
+ +
+
+ ) +} diff --git a/forge-web/components/auth/remove-passkeys-option.tsx b/forge-web/components/auth/remove-passkeys-option.tsx new file mode 100644 index 000000000..c28fb41cf --- /dev/null +++ b/forge-web/components/auth/remove-passkeys-option.tsx @@ -0,0 +1,77 @@ +'use client' + +/** + * "Also remove the passkeys that hold this key": offered in the dialogs that disable a key (revoke + * this browser's key, disable one in Devices & keys) when at least one passkey's entry on Platform + * names it. The controller deletes those entries first, signed by the key while it is still live + * (`revokeStored` and `disableIdentityKey`, `removePasskeys`). A passkey left behind would only + * fail its sign-in, but its entry would stay public with a dead key in it. + * + * Removing a passkey does not lock anyone out of an encryption key it held: that needs a new + * encryption key, which the note says when it applies. + */ + +import { useEffect, useState } from 'react' +import { useAuth } from '@/contexts/auth-context' +import { DOCS } from '@/lib/docs-links' + +/** The identity's passkeys that hold one of `keyIds`, once read; null while reading, none, or hidden. */ +export function usePasskeysHolding(keyIds: readonly number[]): { readonly count: number; readonly encryption: boolean } | null { + const { identity, storage, platformPasskeyProblem, listPlatformPasskeys } = useAuth() + const [found, setFound] = useState<{ count: number; encryption: boolean } | null>(null) + const wanted = keyIds.join(',') + useEffect(() => { + if (identity === null || storage !== 'vault' || platformPasskeyProblem !== null) return + const ids = wanted === '' ? [] : wanted.split(',').map(Number) + // Other keys than the ones last read: nothing to offer until this read answers. + setFound(null) + let live = true + // A read that fails offers nothing: the key is still disabled, and its passkeys can be removed in Settings. + listPlatformPasskeys().then( + (rows) => { + const holding = rows.filter((r) => ids.includes(r.keyId)) + if (live) setFound(holding.length === 0 ? null : { count: holding.length, encryption: holding.some((r) => r.encryptionKey) }) + }, + () => undefined, + ) + return () => { + live = false + } + }, [identity, storage, platformPasskeyProblem, listPlatformPasskeys, wanted]) + return found +} + +export function RemovePasskeysOption({ + holding, + checked, + onChange, +}: { + holding: { readonly count: number; readonly encryption: boolean } + checked: boolean + onChange: (checked: boolean) => void +}): JSX.Element { + return ( +
+ + {holding.encryption ? ( +

+ A passkey that holds your encryption key still opens it for anyone who has the passkey. Removing it doesn't change that: replace the{' '} + + encryption key + {' '} + too. +

+ ) : null} +
+ ) +} diff --git a/forge-web/components/auth/sign-in-tile.tsx b/forge-web/components/auth/sign-in-tile.tsx new file mode 100644 index 000000000..66f755b88 --- /dev/null +++ b/forge-web/components/auth/sign-in-tile.tsx @@ -0,0 +1,58 @@ +'use client' + +/** + * One option on the sign-in sheet's list (`login-modal.tsx`): an icon, a title and a line of help, + * as a button. Shared with the passkey sign-in, which keeps its progress and errors beside it. + */ + +import type { LucideIcon } from 'lucide-react' +import { cn } from '@/lib/utils' + +export function Tile({ + icon: Icon, + title, + body, + onClick, + testId, + muted = false, + highlight = false, + pausedReason = null, +}: { + icon: LucideIcon + title: string + body: string + onClick: () => void + testId: string + /** + * An option most people cannot use here: dashed, with a grey icon, still reachable (L-62). + * Not faded: it is an enabled button, so its text keeps the 4.5:1 contrast (QW4-041: the + * opacity took its helper text to 3.36:1). + */ + muted?: boolean + /** Something this browser has in progress: outlined in the accent colour. */ + highlight?: boolean + /** Why this option cannot be used now (the devnet is moving): disabled, with the reason as its text. */ + pausedReason?: string | null +}): JSX.Element { + return ( + + ) +} diff --git a/forge-web/components/auth/wallet-connect-flow.tsx b/forge-web/components/auth/wallet-connect-flow.tsx index e0d7a949c..9d428d97d 100644 --- a/forge-web/components/auth/wallet-connect-flow.tsx +++ b/forge-web/components/auth/wallet-connect-flow.tsx @@ -194,7 +194,7 @@ export function WalletConnectFlow({ /** Open the sheet's Unlock view (a v2 sign-in that must wait for a locked wallet key to be opened). */ onUnlock?: () => void }): JSX.Element { - const { adoptWalletKeys, addWalletGrant, identity, isLoading, vaults, unlockScope, controller } = useAuth() + const { adoptWalletKeys, addWalletGrant, identity, isLoading, vaults, unlockScope, controller, origin } = useAuth() // Read when the request starts (a scope change must not restart a running request). const scopeRef = useRef(unlockScope) scopeRef.current = unlockScope @@ -537,8 +537,9 @@ export function WalletConnectFlow({ return (

- Your wallet gave this browser its key. A new request goes to the same wallet: when you approve, it adds a new key and disables the - current one. + {origin === 'passkey' + ? 'A passkey brought this key here. If a wallet made it, approve a new request in that wallet: it adds a new key, and this one stays live until you disable it in Devices & keys.' + : 'Your wallet gave this browser its key. A new request goes to the same wallet: when you approve, it adds a new key and disables the current one.'}

@@ -619,7 +620,7 @@ export function WalletConnectFlow({ if (step?.kind === 'renew-store') { return (

-

Your wallet gave this browser a new key and disabled the old one. Forge has not stored the new key yet.

+

{origin === 'passkey' ? 'Your wallet gave this browser a new key. Forge has not stored the new key yet.' : 'Your wallet gave this browser a new key and disabled the old one. Forge has not stored the new key yet.'}

{pendingRenewalUi} {unlockFirst ? : null} diff --git a/forge-web/components/devices-keys.test.tsx b/forge-web/components/devices-keys.test.tsx index 61883d127..df5155b38 100644 --- a/forge-web/components/devices-keys.test.tsx +++ b/forge-web/components/devices-keys.test.tsx @@ -42,7 +42,9 @@ const rows: KeyRow[] = [ row(14, 'other', { kind: 'other', bounds: 'contract group X' }), ] +const passkeys = vi.hoisted(() => ({ problem: 'Checking whether passkeys work on this page.' as string | null, rows: [] as { id: string; keyId: number; encryptionKey: boolean }[] })) const auth = { + disableIdentityKey: vi.fn(async (_input: unknown, _keyId: number, _o?: unknown): Promise => true), identityKeys: vi.fn(async (): Promise => rows), disableOtherKeys: vi.fn(async (_input: unknown, onProgress?: (done: number, total: number) => void): Promise => { onProgress?.(4, 4) @@ -51,11 +53,21 @@ const auth = { } // One object for every render: the page reloads its keys whenever the controller changes. +const listPlatformPasskeys = async () => passkeys.rows +const none = async () => null const session = { identity: ID, isLoading: false, newKeys: [], - controller: { identityKeys: auth.identityKeys, disableOtherKeys: auth.disableOtherKeys }, + storage: 'vault' as const, + get platformPasskeyProblem() { + return passkeys.problem + }, + vaults: [], + listPlatformPasskeys, + pendingPlatformPasskey: none, + platformPasskeyLeftOut: async () => 0, + controller: { identityKeys: auth.identityKeys, disableOtherKeys: auth.disableOtherKeys, disableIdentityKey: auth.disableIdentityKey }, } vi.mock('@/contexts/auth-context', () => ({ useAuth: () => session })) @@ -75,6 +87,9 @@ const render = async (): Promise => { } beforeEach(() => { + passkeys.problem = 'Checking whether passkeys work on this page.' + passkeys.rows = [] + auth.disableIdentityKey.mockClear() resetMemoryStores() localStorage.clear() auth.identityKeys.mockClear() @@ -137,3 +152,51 @@ describe('Disable all other keys', () => { expect(host.querySelector('[data-testid="disable-others"]')).toBeNull() }) }) + +describe('Disable one key, and the passkeys that hold it', () => { + const settle = async (): Promise => { + await act(async () => { + await Promise.resolve() + await Promise.resolve() + }) + } + const disableRow = async (keyId: number): Promise => { + await render() + await act(async () => host.querySelector(`[data-key-id="${keyId}"] [data-testid="key-disable"]`)!.click()) + await settle() + } + const sign = async (): Promise => { + act(() => button(/^Recovery phrase$/).click()) + act(() => type(document.querySelector('[data-testid="disable-key-dialog"] textarea')!, WORDS)) + await act(async () => button(/Sign once & disable/).click()) + } + + it('shows the passkeys section only where passkeys are offered', async () => { + await render() + expect(host.querySelector('[data-testid="passkeys-section"]')).toBeNull() + passkeys.problem = null + act(() => root.unmount()) + root = createRoot(host) + await render() + await settle() + expect(host.querySelector('[data-testid="passkeys-section"]')).not.toBeNull() + }) + + it('offers to remove the passkeys that hold the key, and sends the choice with the disable', async () => { + passkeys.problem = null + passkeys.rows = [{ id: 'a', keyId: 10, encryptionKey: false }, { id: 'b', keyId: 9, encryptionKey: false }] + await disableRow(10) + expect(document.querySelector('[data-testid="remove-passkeys-option"]')!.textContent).toMatch(/Also remove the passkey that holds this key/) + await sign() + expect(auth.disableIdentityKey).toHaveBeenCalledWith({ mnemonic: WORDS }, 10, { removePasskeys: true }) + }) + + it('disables as before when no passkey holds the key', async () => { + passkeys.problem = null + passkeys.rows = [{ id: 'b', keyId: 9, encryptionKey: false }] + await disableRow(10) + expect(document.querySelector('[data-testid="remove-passkeys-option"]')).toBeNull() + await sign() + expect(auth.disableIdentityKey).toHaveBeenCalledWith({ mnemonic: WORDS }, 10) + }) +}) diff --git a/forge-web/components/devices-keys.tsx b/forge-web/components/devices-keys.tsx index 98235e3f8..c83a6bf06 100644 --- a/forge-web/components/devices-keys.tsx +++ b/forge-web/components/devices-keys.tsx @@ -17,6 +17,8 @@ import { CostPreview } from '@/components/ui/cost-preview' import { ErrorBox } from '@/components/auth/protection-fields' import { useMasterKeyInput } from '@/components/auth/master-key-input' import { StepFailed } from '@/components/auth/step-status' +import { PasskeysSection } from '@/components/auth/passkeys-section' +import { RemovePasskeysOption, usePasskeysHolding } from '@/components/auth/remove-passkeys-option' import { Spinner } from '@/components/ui/states' import { ACTIVE_NETWORK } from '@/lib/constants' import { DOCS } from '@/lib/docs-links' @@ -81,6 +83,7 @@ export function DevicesKeys(): JSX.Element {
) : null} + {disablingOthers ? ( @@ -211,11 +214,15 @@ function DisableKeyDialog({ row, label, onClose, onDone }: { row: KeyRow; label: const [submitError, setError] = useState(null) const error = master.error ?? submitError const name = label ? `key #${row.keyId} (${label})` : `key #${row.keyId}` + // Passkeys on Platform that hold this key: removed first, while the key still signs. + const holding = usePasskeysHolding([row.keyId]) + const [removePasskeys, setRemovePasskeys] = useState(true) const submit = async (): Promise => { if (!master.ready || isLoading) return setError(null) try { - await controller.disableIdentityKey(master.take({ keep: true }), row.keyId) + const input = master.take({ keep: true }) + await (holding !== null && removePasskeys ? controller.disableIdentityKey(input, row.keyId, { removePasskeys: true }) : controller.disableIdentityKey(input, row.keyId)) master.clear() onDone() } catch (e) { @@ -237,6 +244,7 @@ function DisableKeyDialog({ row, label, onClose, onDone }: { row: KeyRow; label: Your master key signs one identity update that disables this key on Platform. The device that held it can no longer write as you. The master key is used once and is not stored.

+ {holding !== null ? : null} {master.element} diff --git a/forge-web/components/encryption-key-panel.test.tsx b/forge-web/components/encryption-key-panel.test.tsx new file mode 100644 index 000000000..3a7f711f2 --- /dev/null +++ b/forge-web/components/encryption-key-panel.test.tsx @@ -0,0 +1,93 @@ +// @vitest-environment jsdom +/** + * Importing the identity's encryption key in Settings is a key change for the passkeys that hold + * the old one: this device's are encrypted again right after (`resealPlatformPasskeys`, no prompt), + * and a failure of that never fails the import. + */ + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const ID = '9r27eDsuXEqoMNymW1A2MKFrpBhzSkepVKwXrGzq9dUD' +const CORE = 'CoreContractIdForTestsOnly1111111111111111111' + +const m = vi.hoisted(() => ({ + reseal: undefined as unknown as ReturnType, + importKey: undefined as unknown as ReturnType, +})) + +vi.mock('@/contexts/auth-context', () => ({ + useAuth: () => ({ identity: ID, storage: 'vault', unlockScope: 'full', controller: { resealPlatformPasskeys: m.reseal } }), +})) +vi.mock('@/hooks/use-sdk', () => ({ useSdk: () => ({ sdk: {}, ready: true, network: 'devnet' }) })) +vi.mock('@/lib/constants', async (orig) => { + const real = await orig() + return { ...real, NETWORKS: { ...real.NETWORKS, devnet: { ...real.NETWORKS.devnet, v2: { ...(real.NETWORKS.devnet.v2 ?? {}), core: CORE } } } } +}) +vi.mock('@/lib/auth/vault', async (orig) => ({ + ...(await orig()), + storedEncryptionKeyIds: async () => [], + onEncryptionKeyChange: () => () => undefined, +})) +vi.mock('@/lib/auth/encryption-key', async (orig) => ({ + ...(await orig()), + importEncryptionKey: (...args: unknown[]) => m.importKey(...args), +})) + +const { EncryptionKeyPanel } = await import('./encryption-key-panel') +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +let host: HTMLDivElement +let root: Root + +async function importFromPhrase(): Promise { + await act(async () => root.render()) + await act(async () => { + await Promise.resolve() + }) + const words = host.querySelector('#enc-phrase')! + words.value = Array(12).fill('abandon').join(' ') + const use = [...host.querySelectorAll('button')].find((b) => /Use my encryption key/.test(b.textContent ?? ''))! + await act(async () => use.click()) + await act(async () => { + await Promise.resolve() + await Promise.resolve() + }) +} + +beforeEach(() => { + m.reseal = vi.fn(async () => ({ resealed: 1, needUpdate: 0 })) + m.importKey = vi.fn(async () => 7) + host = document.createElement('div') + document.body.appendChild(host) + root = createRoot(host) +}) +afterEach(() => { + act(() => root.unmount()) + host.remove() +}) + +describe('importing an encryption key in Settings', () => { + it('encrypts this device’s passkeys again with it, without asking for a passkey', async () => { + await importFromPhrase() + expect(m.importKey).toHaveBeenCalledTimes(1) + expect(host.textContent).toMatch(/encryption key 7 is stored in this browser/) + // No id: this device's own passkeys, no prompt. + expect(m.reseal).toHaveBeenCalledTimes(1) + expect(m.reseal).toHaveBeenCalledWith() + }) + + it('a re-seal that fails does not fail the import', async () => { + m.reseal.mockRejectedValueOnce(new Error('Platform is busy')) + await importFromPhrase() + expect(host.textContent).toMatch(/encryption key 7 is stored in this browser/) + expect(host.querySelector('[role="alert"]')).toBeNull() + }) + + it('does not re-seal when no key was found to import', async () => { + m.importKey.mockResolvedValueOnce(null) + await importFromPhrase() + expect(m.reseal).not.toHaveBeenCalled() + }) +}) diff --git a/forge-web/components/encryption-key-panel.tsx b/forge-web/components/encryption-key-panel.tsx index e93219314..fae480306 100644 --- a/forge-web/components/encryption-key-panel.tsx +++ b/forge-web/components/encryption-key-panel.tsx @@ -111,6 +111,9 @@ export function EncryptionKeyPanel(): JSX.Element | null { setError('This identity has no encryption key that opens with that. Register one (Register a new key), or run `dg auth keys add --encryption`.') } else { setNote(`Members-only and private content can be read and written here: encryption key ${id} is stored in this browser.`) + // A new encryption key: this device's passkeys that held the old one are encrypted again + // (no prompt, no spend when there are none). A failure only leaves them at "Needs update". + void controller.resealPlatformPasskeys().catch(() => undefined) } } catch (e) { setError(errorMessage(e)) diff --git a/forge-web/components/key-revoke-dialog.test.tsx b/forge-web/components/key-revoke-dialog.test.tsx index 2d3b9eced..6ba971077 100644 --- a/forge-web/components/key-revoke-dialog.test.tsx +++ b/forge-web/components/key-revoke-dialog.test.tsx @@ -24,6 +24,11 @@ const PASS = 'fake-passphrase-not-real-123' const auth = { scope: 'signing' as 'signing' | 'full', + /** Why passkeys are hidden (null: offered), and the identity's passkeys as the controller lists them. */ + passkeyProblem: 'Checking whether passkeys work on this page.' as string | null, + passkeys: [] as { id: string; keyId: number; encryptionKey: boolean }[], + // One function for every render, as the context's is. + listPlatformPasskeys: async () => auth.passkeys, revokeStored: vi.fn(async (_id: string, _input: unknown): Promise => undefined), unlockMore: vi.fn(async (_m: unknown): Promise => { auth.scope = 'full' @@ -37,6 +42,10 @@ vi.mock('@/contexts/auth-context', () => ({ isLoading: false, unlockScope: auth.scope, revokeStored: auth.revokeStored, + storage: 'vault', + heldOnly: [] as number[], + platformPasskeyProblem: auth.passkeyProblem, + listPlatformPasskeys: auth.listPlatformPasskeys, vaults: [{ identityId: ID, keyId: 6, createdAt: 0, methods: ['passphrase'] }], controller: { unlockMore: auth.unlockMore }, }), @@ -68,6 +77,8 @@ async function giveWords(): Promise { beforeEach(() => { auth.scope = 'signing' + auth.passkeyProblem = 'Checking whether passkeys work on this page.' + auth.passkeys = [] auth.revokeStored.mockReset() auth.unlockMore.mockClear() onClose.mockClear() @@ -161,3 +172,62 @@ describe('KeyRevokeDialog', () => { expect(host.querySelector('[data-testid="cost-preview"]')!.textContent).toMatch(/~0\.000023 DASH/) }) }) + +describe('KeyRevokeDialog and the passkeys that hold the key', () => { + const settle = async (): Promise => { + await act(async () => { + await Promise.resolve() + await Promise.resolve() + }) + } + const option = (): HTMLInputElement | null => host.querySelector('[data-testid="remove-passkeys"]') + + it('offers to remove them first, ticked, and passes the choice on', async () => { + auth.scope = 'full' + auth.passkeyProblem = null + auth.passkeys = [ + { id: 'a', keyId: 6, encryptionKey: false }, + { id: 'b', keyId: 4, encryptionKey: false }, + { id: 'c', keyId: 6, encryptionKey: true }, + ] + render() + await settle() + expect(option()!.checked).toBe(true) + // Only the two that hold this browser's key (#6) count. + expect(host.querySelector('[data-testid="remove-passkeys-option"]')!.textContent).toMatch(/Also remove the 2 passkeys that hold this key/) + // One of them holds the encryption key: removal does not take that back. + expect(host.querySelector('[data-testid="remove-passkeys-encryption"]')!.textContent).toMatch(/still opens it for anyone who has the passkey/) + await giveWords() + await act(async () => button(/Sign once & revoke/).click()) + expect(auth.revokeStored).toHaveBeenCalledWith(ID, { mnemonic: WORDS }, { removePasskeys: true }) + }) + + it('leaves them alone when unticked', async () => { + auth.scope = 'full' + auth.passkeyProblem = null + auth.passkeys = [{ id: 'a', keyId: 6, encryptionKey: false }] + render() + await settle() + expect(host.querySelector('[data-testid="remove-passkeys-encryption"]')).toBeNull() + act(() => option()!.click()) + await giveWords() + await act(async () => button(/Sign once & revoke/).click()) + expect(auth.revokeStored).toHaveBeenCalledWith(ID, { mnemonic: WORDS }) + }) + + it('offers nothing when no passkey holds the key, or passkeys are hidden here', async () => { + auth.scope = 'full' + auth.passkeyProblem = null + auth.passkeys = [{ id: 'b', keyId: 4, encryptionKey: false }] + render() + await settle() + expect(option()).toBeNull() + auth.passkeyProblem = "Passkeys that work on your other devices aren't available on this network yet." + auth.passkeys = [{ id: 'a', keyId: 6, encryptionKey: false }] + act(() => root.unmount()) + root = createRoot(host) + render() + await settle() + expect(option()).toBeNull() + }) +}) diff --git a/forge-web/components/key-revoke-dialog.tsx b/forge-web/components/key-revoke-dialog.tsx index 8599022a1..dd3b6158a 100644 --- a/forge-web/components/key-revoke-dialog.tsx +++ b/forge-web/components/key-revoke-dialog.tsx @@ -24,6 +24,7 @@ import { CostPreview } from '@/components/ui/cost-preview' import { ErrorBox } from '@/components/auth/protection-fields' import { useMasterKeyInput } from '@/components/auth/master-key-input' import { UnlockMore } from '@/components/auth/unlock-more' +import { RemovePasskeysOption, usePasskeysHolding } from '@/components/auth/remove-passkeys-option' import { FORGET_DELETES, topUpStays } from '@/components/top-up-stays' import { UnlockNeededError } from '@/lib/auth/controller' import { IdentityUpdateNotSentError, WrongMasterKeyError } from '@/lib/auth/limited-key' @@ -31,7 +32,7 @@ import { KEY_DISABLE_CREDITS, previewCredits } from '@/lib/sdk' import { errorMessage } from '@/lib/utils' export function KeyRevokeDialog({ unlimited, onClose }: { unlimited: boolean; onClose: () => void }): JSX.Element { - const { identity, keyId, revokeStored, isLoading, unlockScope } = useAuth() + const { identity, keyId, heldOnly, revokeStored, isLoading, unlockScope } = useAuth() const master = useMasterKeyInput(identity, { id: 'revoke', fileLabel: 'Identity file to revoke with' }) const [submitError, setError] = useState(null) const error = master.error ?? submitError @@ -39,6 +40,9 @@ export function KeyRevokeDialog({ unlimited, onClose }: { unlimited: boolean; on // dialog): unlock, then it runs again with the master key still in the field. const [unlockAsked, setUnlockAsked] = useState(false) const needsUnlock = unlockScope === 'signing' || unlockAsked + // Passkeys on Platform that hold the key being disabled (or one held only to disable with it). + const holding = usePasskeysHolding(keyId === null ? (heldOnly ?? []) : [keyId, ...(heldOnly ?? [])]) + const [removePasskeys, setRemovePasskeys] = useState(true) const noun = unlimited ? 'the keys this browser holds' : "this browser's key" // What this browser keeps about the identity's top-ups after the revoke forgets the key (QW3-034). const [stays, setStays] = useState(null) @@ -55,7 +59,8 @@ export function KeyRevokeDialog({ unlimited, onClose }: { unlimited: boolean; on if (identity === null || !master.ready || isLoading) return setError(null) try { - await revokeStored(identity, master.take({ keep: true })) + const input = master.take({ keep: true }) + await (holding !== null && removePasskeys ? revokeStored(identity, input, { removePasskeys: true }) : revokeStored(identity, input)) master.clear() onClose() } catch (e) { @@ -107,6 +112,7 @@ export function KeyRevokeDialog({ unlimited, onClose }: { unlimited: boolean; on void revoke() }} > + {holding !== null ? : null} {master.element} diff --git a/forge-web/components/keys-panel.tsx b/forge-web/components/keys-panel.tsx index 320e5b9a9..ee7487718 100644 --- a/forge-web/components/keys-panel.tsx +++ b/forge-web/components/keys-panel.tsx @@ -21,7 +21,7 @@ import { useUiStore } from '@/hooks/use-ui-store' import { Button } from '@/components/ui/button' import { Field, Input } from '@/components/ui/input' import { creditsAsDash, formatDate } from '@/lib/view/format' -import { keyBudgetWords } from '@/lib/view/funds' +import { keyBudgetWords, renewableInWallet } from '@/lib/view/funds' import { INSIGHT_OVERRIDE_KEY, coreEndpoints } from '@/lib/auth/asset-lock' import { FORGET_DELETES, topUpStays } from '@/components/top-up-stays' import { KeyTopUpDialog } from '@/components/key-top-up-dialog' @@ -64,8 +64,9 @@ export function KeysPanel(): JSX.Element { // A pasted key is not Forge's to renew (it may be a wallet's, and has no Forge limits): the // offer is a limited key from the identity file or phrase instead, and signing out forgets it. const pasted = storage === 'session' - // A key a wallet granted through App Connect is renewed in that wallet. - const inWallet = storage === 'vault' && origin === 'app-connect' + // A key a wallet granted through App Connect is renewed in that wallet; one a passkey restored + // may be a wallet's too, so the wallet renewal is offered beside the identity file's. + const inWallet = storage === 'vault' && renewableInWallet(origin) return (
diff --git a/forge-web/components/login-modal.test.tsx b/forge-web/components/login-modal.test.tsx index 7503436ce..ca237a3fd 100644 --- a/forge-web/components/login-modal.test.tsx +++ b/forge-web/components/login-modal.test.tsx @@ -21,6 +21,7 @@ import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { AlreadyStoredError } from '@/lib/auth/controller' +import { PlatformPasskeyError } from '@/lib/auth/passkey-vault/service' import type { VaultInfo } from '@/lib/auth/vault' import { useUiStore } from '@/hooks/use-ui-store' @@ -39,6 +40,11 @@ const auth = { importIdentity: vi.fn(), forget: vi.fn(async () => undefined), unlock: vi.fn(), + /** Why passkeys for other devices are hidden; null shows the tile (the default is hidden). */ + passkeyProblem: 'Checking whether passkeys work on this page.' as string | null, + signInWithPasskey: vi.fn(), + isLoading: false, + step: null as string | null, } /** The unfinished identity creation this browser holds, if any. */ @@ -82,8 +88,10 @@ vi.mock('@/contexts/auth-context', () => ({ importIdentity: auth.importIdentity, unlock: auth.unlock, forget: auth.forget, - isLoading: false, - step: null, + isLoading: auth.isLoading, + step: auth.step, + platformPasskeyProblem: auth.passkeyProblem, + signInWithPasskey: auth.signInWithPasskey, identity: auth.identity, keyId: auth.keyId, unlockScope: auth.unlockScope, @@ -154,6 +162,10 @@ beforeEach(() => { v2Available = false auth.importIdentity.mockReset() auth.forget.mockClear() + auth.passkeyProblem = 'Checking whether passkeys work on this page.' + auth.signInWithPasskey.mockReset() + auth.isLoading = false + auth.step = null Element.prototype.scrollIntoView = vi.fn() host = document.createElement('div') document.body.appendChild(host) @@ -487,3 +499,68 @@ describe('App Connect v2 in the sheet', () => { expect(host.ownerDocument.body.textContent).toMatch(/Disables key #6 and registers/) }) }) + +describe('Sign in with a passkey (passkeys that hold a key on Platform)', () => { + const openChooser = async (): Promise => { + auth.vaults = [] + act(() => useUiStore.getState().openLogin()) + await flush() + } + + it('is hidden while passkeys are not offered here (not checked, another host, no vault deployed yet)', async () => { + await openChooser() + expect(q('[data-testid="tile-passkey"]')).toBeNull() + // The rest of the list is there. + expect(q('[data-testid="tile-create"]')).not.toBeNull() + }) + + it('shows once passkeys are offered, after the wallet and before create, and says what it does not do', async () => { + auth.passkeyProblem = null + walletSupported = true + await openChooser() + for (let i = 0; i < 20 && q('[data-testid="tile-wallet"]') === null; i++) await flush() + const order = [...host.ownerDocument.querySelectorAll('button[data-testid^="tile-"]')].map((b) => b.dataset.testid) + expect(order.slice(0, 3)).toEqual(['tile-wallet', 'tile-passkey', 'tile-create']) + expect(q('[data-testid="tile-passkey"]')!.textContent).toMatch(/Sign in with a passkey/) + expect(q('[data-testid="tile-passkey"]')!.textContent).toMatch(/It doesn't recover an account/) + }) + + it('signs in with one prompt and closes the sheet', async () => { + auth.passkeyProblem = null + auth.signInWithPasskey.mockResolvedValueOnce(undefined) + await openChooser() + await click(q('[data-testid="tile-passkey"]')) + expect(auth.signInWithPasskey).toHaveBeenCalledTimes(1) + expect(useUiStore.getState().loginOpen).toBe(false) + }) + + it('shows the step while it works', async () => { + auth.passkeyProblem = null + auth.isLoading = true + auth.step = 'Waiting for your passkey' + await openChooser() + expect(q('[data-testid="passkey-sign-in-step"]')!.textContent).toBe('Waiting for your passkey…') + }) + + it('says a browser-only passkey only unlocks the browser that made it', async () => { + auth.passkeyProblem = null + auth.signInWithPasskey.mockRejectedValueOnce(new PlatformPasskeyError('This passkey only unlocks the browser that made it. Use it there, or sign in another way.', 'not-vault')) + await openChooser() + await click(q('[data-testid="tile-passkey"]')) + expect(q('[role="alert"]')!.textContent).toMatch(/only unlocks the browser that made it/) + expect(q('[data-testid="passkey-unlock-instead"]')).toBeNull() + expect(useUiStore.getState().loginOpen).toBe(true) + }) + + it('offers "Unlock instead" when this browser already keeps a key', async () => { + auth.passkeyProblem = null + auth.signInWithPasskey.mockRejectedValueOnce(new PlatformPasskeyError('This browser already keeps this key. Unlock it instead.', 'held')) + await openChooser() + auth.vaults = [{ identityId: ID, keyId: 6, createdAt: 1_700_000_000_000, methods: ['passphrase'] }] + await click(q('[data-testid="tile-passkey"]')) + expect(q('[role="alert"]')!.textContent).toMatch(/already keeps this key/) + await click(q('[data-testid="passkey-unlock-instead"]')) + // The Unlock view, for the key this browser holds. + expect(q('#unlock-passphrase')).not.toBeNull() + }) +}) diff --git a/forge-web/components/login-modal.tsx b/forge-web/components/login-modal.tsx index e8b90227d..25b8ce09f 100644 --- a/forge-web/components/login-modal.tsx +++ b/forge-web/components/login-modal.tsx @@ -36,6 +36,8 @@ import { Field, Input, Textarea } from '@/components/ui/input' import { ErrorBox, GroupNotice, useProtection } from '@/components/auth/protection-fields' import { CreateIdentityFlow } from '@/components/auth/create-identity-flow' import { WalletConnectFlow } from '@/components/auth/wallet-connect-flow' +import { Tile } from '@/components/auth/sign-in-tile' +import { PasskeySignIn } from '@/components/auth/passkey-sign-in' import { DgHandoffFlow, type HandoffTarget } from '@/components/auth/dg-handoff-flow' import { KeyLifetimeSelect } from '@/components/auth/key-lifetime' import { PhraseWarning } from '@/components/auth/phrase-warning' @@ -73,7 +75,7 @@ export function LoginModal(): JSX.Element { const requestedGrant = useUiStore((s) => s.loginGrantFor) ?? 'collab' const intent = useUiStore((s) => s.loginIntent) const close = useUiStore((s) => s.closeLogin) - const { vaults, vaultsLoaded, vaultsError, reloadVaults, limitedKeys, grants } = useAuth() + const { vaults, vaultsLoaded, vaultsError, reloadVaults, limitedKeys, grants, origin } = useAuth() const [view, setView] = useState(null) // The guided grants after a wallet sign-in (FEAT-04): `walletDone` waits for the new session's // grants to land, `guide` is the sequence once it runs. Neither outlives the sheet. @@ -150,7 +152,7 @@ export function LoginModal(): JSX.Element { const back = view === null || view === 'choose' || view === 'unlock' || view === 'grant' || view === 'renew' || view === 'wallet-renew' ? null : () => setView('choose') // Before the stored-key list is read (a few ms, or storage blocked): the Unlock line, the // likelier view for someone opening the sheet on a device that holds a key. - const description = view === null ? 'Checking this browser for a stored key…' : describeView(view, limitedKeys) + const description = view === null ? 'Checking this browser for a stored key…' : describeView(view, limitedKeys, origin === 'passkey') const title = titleFor(view, grantTitle, intent?.action) return ( @@ -190,6 +192,7 @@ export function LoginModal(): JSX.Element { ) : null} {view === 'choose' ? ( { setDgReplace(null) setView(v) @@ -275,10 +278,15 @@ function GuidedSkip({ step, onSkip, onSkipAll }: { step: { readonly step: number } /** The sheet's description line for a view. */ -function describeView(view: View, limitedKeys: boolean): ReactNode { +function describeView(view: View, limitedKeys: boolean, fromPasskey = false): ReactNode { if (view === 'advanced') return 'A pasted key signs for this tab only, with whatever power it has.' if (view === 'wallet' || view === 'grant') return 'Your wallet gives this browser a key for Dash Forge. Your recovery phrase and master key stay on the phone.' - if (view === 'wallet-renew') return 'Your wallet adds a new key for this browser and disables the current one. Your recovery phrase and master key stay on the phone.' + if (view === 'wallet-renew') { + // A key a passkey brought here is not this browser's own wallet grant: the wallet adds a new one and leaves it. + return fromPasskey + ? 'Your wallet adds a new key for this browser. The current key stays live until you disable it in Devices & keys. Your recovery phrase and master key stay on the phone.' + : 'Your wallet adds a new key for this browser and disables the current one. Your recovery phrase and master key stay on the phone.' + } if (!limitedKeys) return `Dash Forge isn't available on ${networkName()} yet, so there's nothing to sign in to here.` const base = <>at most {BROWSER_KEY_DEFAULTS.budgetDash} DASH, only on Forge // Import, renew and dg offer a lifetime picker; creating an identity does not. @@ -294,56 +302,7 @@ function describeView(view: View, limitedKeys: boolean): ReactNode { return <>A new or imported identity gives this browser a limited key: {base}, for {BROWSER_KEY_DEFAULTS.days} days by default. An import can pick up to a year; a new identity's key can be renewed for up to a year later. } -function Tile({ - icon: Icon, - title, - body, - onClick, - testId, - muted = false, - highlight = false, - pausedReason = null, -}: { - icon: typeof Wallet - title: string - body: string - onClick: () => void - testId: string - /** - * An option most people cannot use here: dashed, with a grey icon, still reachable (L-62). - * Not faded: it is an enabled button, so its text keeps the 4.5:1 contrast (QW4-041: the - * opacity took its helper text to 3.36:1). - */ - muted?: boolean - /** Something this browser has in progress: outlined in the accent colour. */ - highlight?: boolean - /** Why this option cannot be used now (the devnet is moving): disabled, with the reason as its text. */ - pausedReason?: string | null -}): JSX.Element { - return ( - - ) -} - -function ChooseView({ onPick }: { onPick: (v: View) => void }): JSX.Element { +function ChooseView({ onPick, onDone }: { onPick: (v: View) => void; onDone: () => void }): JSX.Element { const { limitedKeys } = useAuth() const closeLogin = useUiStore((s) => s.closeLogin) const { available: walletAvailable, v2: walletV2 } = useWalletAvailability(limitedKeys) @@ -395,6 +354,8 @@ function ChooseView({ onPick }: { onPick: (v: View) => void }): JSX.Element { /> ) : null} {walletFirst ? walletTile : null} + {/* A passkey added on another device: reads only, so it is offered even while writes are paused. */} + onPick('unlock')} /> onPick('create')} pausedReason={pausedReason} />

About {creditsAsDash(typicalIssueCredits())} DASH per issue, .

({ origin: null as 'app-connect' | null, reason: 'key-expiry' as 'key-expiry' | 'key-budget' | 'balance', level: 'low' as 'low' | 'empty' })) +const session = vi.hoisted(() => ({ origin: null as 'app-connect' | 'passkey' | null, reason: 'key-expiry' as 'key-expiry' | 'key-budget' | 'balance', level: 'low' as 'low' | 'empty' })) vi.mock('@/contexts/auth-context', () => ({ useAuth: () => ({ @@ -58,6 +58,24 @@ describe('the low-funds banner', () => { expect(useUiStore.getState().loginView).toBe('wallet-renew') }) + it('offers both renewals for a key a passkey restored (its maker is unknown)', async () => { + session.origin = 'passkey' + await show() + expect(main().textContent).toBe('Renew in your wallet') + const withFile = host.querySelector('[data-testid="low-funds-renew-with-file"]')! + expect(withFile.textContent).toBe('Renew with identity file') + act(() => main().click()) + expect(useUiStore.getState().loginView).toBe('wallet-renew') + act(() => withFile.click()) + expect(useUiStore.getState().loginView).toBe('import') + }) + + it('a wallet-granted key shows no second button', async () => { + session.origin = 'app-connect' + await show() + expect(host.querySelector('[data-testid="low-funds-renew-with-file"]')).toBeNull() + }) + it('also for an empty budget', async () => { session.origin = 'app-connect' session.reason = 'key-budget' diff --git a/forge-web/components/low-funds-banner.tsx b/forge-web/components/low-funds-banner.tsx index 63206bdb1..0c0d40c61 100644 --- a/forge-web/components/low-funds-banner.tsx +++ b/forge-web/components/low-funds-banner.tsx @@ -46,8 +46,10 @@ export function LowFundsBanner(): JSX.Element | null { if (!identity || !funds || !notice || dismissed?.identity !== identity || dismissed.keys.includes(notice.key)) return null const empty = funds.level === 'empty' const topUp = notice.fix === 'top-up' - // A key a wallet granted is renewed in that wallet; the identity file stays the other way. - const inWallet = notice.fix === 'renew-in-wallet' + // A key a wallet granted is renewed in that wallet; the identity file stays the other way. A key + // a passkey restored may be either's: both are offered. + const either = notice.fix === 'renew-either' + const inWallet = notice.fix === 'renew-in-wallet' || either const dismiss = (): void => { const keys = [...dismissed.keys, notice.key] try { @@ -78,6 +80,11 @@ export function LowFundsBanner(): JSX.Element | null { > {topUp ? 'Top up' : inWallet ? 'Renew in your wallet' : 'Renew key'} + {either ? ( + + ) : null} diff --git a/forge-web/components/passkey-offer.test.tsx b/forge-web/components/passkey-offer.test.tsx new file mode 100644 index 000000000..37d03a9d2 --- /dev/null +++ b/forge-web/components/passkey-offer.test.tsx @@ -0,0 +1,135 @@ +// @vitest-environment jsdom +/** + * The one-time passkey offer under the header: shown once after an interactive sign-in or unlock, + * only where a passkey could hold this key, never again after "Not now" or once a passkey exists + * here, and not at all for a reloaded tab. + */ + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { ACTIVE_NETWORK } from '@/lib/constants' +import { putMarker } from '@/lib/auth/passkey-vault/markers' +import { resetMemoryStores } from '@/lib/idb' +import { MAX_OFFERS } from '@/lib/auth/passkey-vault/offer' + +const ID = '9r27eDsuXEqoMNymW1A2MKFrpBhzSkepVKwXrGzq9dUD' +const session = vi.hoisted(() => ({ + problem: null as string | null, + scope: 'full' as 'full' | 'signing' | null, + storage: 'vault' as 'vault' | 'session' | null, + unlimited: false, + keyLimits: { remaining: 4n, total: 5n, expiresAt: Date.now() + 86_400_000 } as { remaining: bigint; total: bigint; expiresAt: number | null } | null, +})) + +vi.mock('@/contexts/auth-context', () => ({ + useAuth: () => ({ + identity: ID, + storage: session.storage, + unlockScope: session.scope, + platformPasskeyProblem: session.problem, + unlimitedKey: session.unlimited, + unboundedKey: false, + keyLimits: session.keyLimits, + }), +})) + +const { PasskeyOffer } = await import('./passkey-offer') +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +let host: HTMLDivElement +let root: Root +const offer = (): HTMLElement | null => host.querySelector('[data-testid="passkey-offer"]') +async function mount(): Promise { + await act(async () => root.render()) + await act(async () => { + await Promise.resolve() + await Promise.resolve() + await Promise.resolve() + }) +} +/** A new page load: the component mounts again (its once-per-load memory is gone). */ +async function reload(): Promise { + act(() => root.unmount()) + root = createRoot(host) + await mount() +} + +beforeEach(() => { + resetMemoryStores() + localStorage.clear() + session.problem = null + session.scope = 'full' + session.storage = 'vault' + session.unlimited = false + session.keyLimits = { remaining: 4n, total: 5n, expiresAt: Date.now() + 86_400_000 } + host = document.createElement('div') + document.body.appendChild(host) + root = createRoot(host) +}) +afterEach(() => { + act(() => root.unmount()) + host.remove() +}) + +describe('the passkey offer', () => { + it('shows after an interactive sign-in, and says what a passkey is not', async () => { + await mount() + expect(offer()!.textContent).toMatch(/Sign in on your other devices with a passkey/) + expect(offer()!.textContent).toMatch(/It doesn't recover an account/) + expect(host.querySelector('[data-testid="passkey-offer-setup"]')!.getAttribute('href')).toMatch(/^\/settings\/keys\/?#passkeys$/) + }) + + it.each([ + ['passkeys are hidden here', () => (session.problem = 'Checking whether passkeys work on this page.')], + ['the tab was reloaded (it holds only the signing key)', () => (session.scope = 'signing')], + ['the key is a pasted one', () => (session.storage = 'session')], + ['the key has no limits', () => (session.unlimited = true)], + ['the key has no budget', () => (session.keyLimits = null)], + ['the key never expires', () => (session.keyLimits = { remaining: 4n, total: 5n, expiresAt: null })], + ['the key has expired', () => (session.keyLimits = { remaining: 4n, total: 5n, expiresAt: Date.now() - 1 })], + ['the key has no budget left', () => (session.keyLimits = { remaining: 0n, total: 5n, expiresAt: Date.now() + 86_400_000 })], + ])('does not show when %s', async (_why, change) => { + change() + await mount() + expect(offer()).toBeNull() + }) + + it('"Not now" ends it for good', async () => { + await mount() + await act(async () => host.querySelector('[data-testid="passkey-offer-dismiss"]')!.click()) + expect(offer()).toBeNull() + await reload() + expect(offer()).toBeNull() + }) + + it('"Set up a passkey" ends it too: Settings has the rest', async () => { + await mount() + // No page loads in jsdom: the click is handled by the app, the navigation is not carried out. + const stop = (e: Event): void => e.preventDefault() + document.addEventListener('click', stop) + await act(async () => host.querySelector('[data-testid="passkey-offer-setup"]')!.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }))) + document.removeEventListener('click', stop) + await reload() + expect(offer()).toBeNull() + }) + + it('is made at most twice when ignored, once per page load', async () => { + for (let i = 0; i < MAX_OFFERS; i++) { + await reload() + expect(offer()).not.toBeNull() + } + await reload() + expect(offer()).toBeNull() + }) + + it('is not made where a passkey already exists on this device', async () => { + await putMarker(ACTIVE_NETWORK.network, ID, { credentialId: new Uint8Array(16).fill(1), recipientKey: new Uint8Array(32).fill(2), keyIds: [5], addedAt: 1 }) + await mount() + expect(offer()).toBeNull() + session.scope = 'full' + await reload() + expect(offer()).toBeNull() + }) +}) diff --git a/forge-web/components/passkey-offer.tsx b/forge-web/components/passkey-offer.tsx new file mode 100644 index 000000000..8496d0774 --- /dev/null +++ b/forge-web/components/passkey-offer.tsx @@ -0,0 +1,82 @@ +'use client' + +/** + * The one-time offer to add a passkey, in a slim bar under the header after an interactive + * sign-in or unlock. A passkey moves this sign-in to another device; it does not recover an + * account. It never nags (`lib/auth/passkey-vault/offer.ts`): at most twice per identity on this + * browser, once per page load, never after "Not now" or a click on "Set up a passkey", never for a + * reloaded tab (which holds only the signing key), and never where a passkey could not hold this + * key (a pasted key, or one with no budget or no expiry) or the feature is hidden. + */ + +import { useEffect, useRef, useState } from 'react' +import Link from 'next/link' +import { Fingerprint, X } from 'lucide-react' +import { useAuth } from '@/contexts/auth-context' +import { Button, buttonClass } from '@/components/ui/button' +import { readMarkers } from '@/lib/auth/passkey-vault/markers' +import { dismissOffer, noteOffered, shouldOffer } from '@/lib/auth/passkey-vault/offer' +import { ACTIVE_NETWORK } from '@/lib/constants' + +export function PasskeyOffer(): JSX.Element | null { + const { identity, storage, unlockScope, platformPasskeyProblem, keyLimits, unlimitedKey, unboundedKey } = useAuth() + const [showing, setShowing] = useState(null) + // The identity already asked about in this page load: one question per page load. + const asked = useRef(null) + const alive = useRef(true) + useEffect(() => { + alive.current = true + return () => { + alive.current = false + } + }, []) + const eligible = + identity !== null && + storage === 'vault' && + unlockScope === 'full' && + platformPasskeyProblem === null && + !unlimitedKey && + !unboundedKey && + keyLimits?.total != null && + keyLimits.expiresAt !== null && + // A spent or expired key would be refused when added: no offer for it. + keyLimits.expiresAt > Date.now() && + (keyLimits.remaining === null || keyLimits.remaining > 0n) + useEffect(() => { + if (!eligible || identity === null || asked.current === identity) return + asked.current = identity + const network = ACTIVE_NETWORK.network + void (async () => { + if (!shouldOffer(network, identity)) return + // A passkey made or used here already answers the question. + const mine = await readMarkers(network, identity).catch(() => []) + if (mine.length > 0) return dismissOffer(network, identity) + if (noteOffered(network, identity) && alive.current) setShowing(identity) + })() + }, [eligible, identity]) + + if (!eligible || showing !== identity || identity === null) return null + const done = (): void => { + dismissOffer(ACTIVE_NETWORK.network, identity) + setShowing(null) + } + return ( +
+
+ +

Sign in on your other devices with a passkey. It moves this sign-in over. It doesn't recover an account.

+
+ + Set up a passkey + + + +
+
+
+ ) +} diff --git a/forge-web/components/top-up-sheet.test.tsx b/forge-web/components/top-up-sheet.test.tsx index f3b4ac5b6..0a84fd346 100644 --- a/forge-web/components/top-up-sheet.test.tsx +++ b/forge-web/components/top-up-sheet.test.tsx @@ -19,7 +19,7 @@ const ID = '9r27eDsuXEqoMNymW1A2MKFrpBhzSkepVKwXrGzq9dUD' const EXPIRES = Date.UTC(2026, 11, 29) /** Where the signed-in key came from: `app-connect` for a wallet's grant. */ -const session = vi.hoisted(() => ({ origin: null as 'app-connect' | null })) +const session = vi.hoisted(() => ({ origin: null as 'app-connect' | 'passkey' | null })) vi.mock('@/contexts/auth-context', () => ({ useAuth: () => ({ @@ -173,3 +173,19 @@ describe('the top-up sheet for a key a wallet granted (App Connect)', () => { expect(byText('Renew in your wallet')).toBeNull() }) }) + +describe('the top-up sheet for a key a passkey restored (unknown origin)', () => { + const byText = (text: string): HTMLElement | null => [...document.querySelectorAll('button')].find((b) => b.textContent?.trim() === text) ?? null + + it('offers the wallet and the identity file side by side, and says why', () => { + session.origin = 'passkey' + act(() => root.render(<>)) + act(() => useUiStore.getState().openTopUp({ blocker: 'key-expiry' })) + expect(document.querySelector('[data-testid="top-up-sheet"]')!.textContent).toMatch(/passkey brought this key here, so Forge can't tell who made it/) + expect(byText('Renew in your wallet')).not.toBeNull() + expect(byText('Renew with identity file')).not.toBeNull() + expect(byText('Renew key')).toBeNull() + act(() => byText('Renew in your wallet')!.click()) + expect(useUiStore.getState().loginView).toBe('wallet-renew') + }) +}) diff --git a/forge-web/components/top-up-sheet.tsx b/forge-web/components/top-up-sheet.tsx index ae278937c..9b42a51ad 100644 --- a/forge-web/components/top-up-sheet.tsx +++ b/forge-web/components/top-up-sheet.tsx @@ -24,7 +24,7 @@ import { IdentityTopUpFlow } from '@/components/identity-top-up-flow' import { KeyBudgetText, KeyFundsLine } from '@/components/funds-summary' import { faucetUrls } from '@/lib/faucets' import { typicalIssueCredits } from '@/lib/sdk' -import { issueCoverageParts, type KeyLimits } from '@/lib/view/funds' +import { issueCoverageParts, renewableInWallet, type KeyLimits } from '@/lib/view/funds' import { creditsAsDash, formatDate } from '@/lib/view/format' import { creditsToDash } from '@/lib/sdk/cost' import { FiatNote } from '@/components/ui/fiat-note' @@ -85,7 +85,9 @@ export function TopUpSheet(): JSX.Element | null { const canTopUpKey = reason.blocker === 'key-budget' && storage === 'vault' && keyLimits?.total != null // A key a wallet granted through App Connect is renewed in that wallet; the identity file or // recovery phrase still works (the master key can renew any Forge browser key). - const inWallet = origin === 'app-connect' && storage === 'vault' + const inWallet = renewableInWallet(origin) && storage === 'vault' + // A key a passkey restored: the wallet may have made it, or the master key did. Said so. + const fromPasskey = origin === 'passkey' && storage === 'vault' const renewVia = (view: 'import' | 'wallet-renew'): void => { close() openLogin(view) @@ -107,7 +109,9 @@ export function TopUpSheet(): JSX.Element | null { <> {inWallet ? (

- Your wallet gave this browser its key, so renew it there: the wallet adds a new key and disables this one. + {fromPasskey + ? "A passkey brought this key here, so Forge can't tell who made it. If a wallet did, renew it there. It adds a new key, and this one stays live until you disable it in Devices & keys." + : 'Your wallet gave this browser its key, so renew it there: the wallet adds a new key and disables this one.'} {canTopUpKey ? ' You can also add budget to this key with your identity file or recovery phrase.' : ' Your identity file or recovery phrase works too.'}

) : canTopUpKey ? ( diff --git a/forge-web/contexts/auth-context.test.tsx b/forge-web/contexts/auth-context.test.tsx new file mode 100644 index 000000000..46d04f80d --- /dev/null +++ b/forge-web/contexts/auth-context.test.tsx @@ -0,0 +1,135 @@ +// @vitest-environment jsdom +/** + * `platformPasskeyProblem`, the one flag every passkey control hides behind. It starts hidden, and + * stays hidden on a page or network that cannot have passkeys. Where it can, it is lifted only + * once the forge-meta Platform serves is read and has the vault's entry type: that read waits for + * someone who could use passkeys (signed in, or the sign-in sheet open), so a page that never + * connects to Platform does not start to for this. + */ + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { useUiStore } from '@/hooks/use-ui-store' + +const NOT_YET = 'Checking whether passkeys work on this page.' +const NO_VAULT = "Passkeys that work on your other devices aren't available on this network yet." + +const fake = vi.hoisted(() => ({ + sync: null as string | null, + checked: null as string | null, + check: undefined as unknown as ReturnType, + session: null as { identityId: string; balance: string } | null, +})) + +vi.mock('../lib/auth', () => { + class AuthController { + constructor() { + // Every controller action the provider binds that this test does not care about. + return new Proxy(this, { get: (target, key, receiver) => (key in target ? Reflect.get(target, key, receiver) : () => undefined) }) + } + getState() { + return { session: fake.session, isLoading: false, error: null, resuming: false } + } + subscribe() { + return () => undefined + } + attach() { + return () => undefined + } + async resume() {} + async storedVaults() { + return [] + } + setSpendListener() {} + supportsLimitedKeys() { + return true + } + platformPasskeyProblem() { + return fake.sync + } + checkPlatformPasskeys() { + return fake.check() + } + get writeAuth() { + return null + } + } + return { AuthController } +}) + +const { AuthProvider, useAuth } = await import('./auth-context') +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +let host: HTMLDivElement +let root: Root +let seen: string | null | undefined + +function Probe(): null { + seen = useAuth().platformPasskeyProblem + return null +} +async function mount(): Promise { + await act(async () => root.render()) + await act(async () => { + await Promise.resolve() + await Promise.resolve() + }) +} + +beforeEach(() => { + fake.sync = null + fake.session = null + fake.check = vi.fn(async () => fake.checked) + fake.checked = null + seen = undefined + useUiStore.getState().closeLogin() + host = document.createElement('div') + document.body.appendChild(host) + root = createRoot(host) +}) +afterEach(() => { + act(() => useUiStore.getState().closeLogin()) + act(() => root.unmount()) + host.remove() +}) + +describe('platformPasskeyProblem in the auth context', () => { + it('stays hidden, and reads nothing, while nobody could use passkeys', async () => { + await mount() + expect(seen).toBe(NOT_YET) + expect(fake.check).not.toHaveBeenCalled() + }) + + it('a page or network that cannot have passkeys says why, without reading anything', async () => { + fake.sync = 'This browser can’t use passkeys on this page.' + act(() => useUiStore.getState().openLogin()) + await mount() + expect(seen).toBe(fake.sync) + expect(fake.check).not.toHaveBeenCalled() + }) + + it('opening the sign-in sheet reads forge-meta; a vault that is not deployed keeps the controls hidden', async () => { + fake.checked = NO_VAULT + await mount() + await act(async () => useUiStore.getState().openLogin()) + expect(fake.check).toHaveBeenCalledTimes(1) + expect(seen).toBe(NO_VAULT) + }) + + it('a deployed vault lifts the flag', async () => { + fake.checked = null + await mount() + await act(async () => useUiStore.getState().openLogin()) + expect(seen).toBeNull() + }) + + it('a signed-in page reads it too', async () => { + fake.session = { identityId: '9r27eDsuXEqoMNymW1A2MKFrpBhzSkepVKwXrGzq9dUD', balance: '1' } + fake.checked = NO_VAULT + await mount() + expect(fake.check).toHaveBeenCalledTimes(1) + expect(seen).toBe(NO_VAULT) + }) +}) diff --git a/forge-web/contexts/auth-context.tsx b/forge-web/contexts/auth-context.tsx index 76a9d388d..e25d740ec 100644 --- a/forge-web/contexts/auth-context.tsx +++ b/forge-web/contexts/auth-context.tsx @@ -137,14 +137,37 @@ interface AuthContextValue { logout: () => void /** Delete the stored key of `identityId` from this device (does not revoke it on chain). */ forget: (identityId: string) => Promise - /** Disable this device's key on chain with the master key (file or phrase), then forget it. */ - revokeStored: (identityId: string, input: MasterInput) => Promise + /** + * Disable this device's key on chain with the master key (file or phrase), then forget it. + * `removePasskeys`: first delete the passkeys that hold it (offer it when any does). + */ + revokeStored: (identityId: string, input: MasterInput, options?: { readonly removePasskeys?: boolean }) => Promise /** Raise this browser key's budget / expiry in place (the master key signs once). */ topUpKey: (input: MasterInput, request: TopUpRequest) => Promise /** Register a CI runner key (not stored here; shown once). The master key signs once. */ createRunnerKey: (input: MasterInput, request: LimitedKeyRequest) => Promise /** Register the DPNS username `label` (#452): the identity's own key (file or phrase) signs once. Resolves `label.dash`. */ registerUsername: (input: MasterInput, label: string) => Promise + /** + * Why passkeys that work on the user's other devices are not offered on this page, or null when + * they are. Hide the passkey sign-in and the passkeys section while it is not null. + */ + readonly platformPasskeyProblem: string | null + /** Sign in on a new device with a passkey that holds a key on Platform. */ + signInWithPasskey: () => Promise + /** Add a passkey holding this session's key (two prompts). See {@link AuthController.addPlatformPasskey}. */ + addPlatformPasskey: AuthController['addPlatformPasskey'] + /** The passkey an add left unfinished here ("Check again"), or null. */ + pendingPlatformPasskey: AuthController['pendingPlatformPasskey'] + finishPlatformPasskey: AuthController['finishPlatformPasskey'] + abandonPlatformPasskey: AuthController['abandonPlatformPasskey'] + /** The identity's passkeys for Devices & keys. */ + listPlatformPasskeys: AuthController['listPlatformPasskeys'] + removePlatformPasskey: AuthController['removePlatformPasskey'] + /** How many of this browser's wallet keys a passkey leaves out (no spending limit or expiry). */ + platformPasskeyLeftOut: AuthController['platformPasskeyLeftOut'] + /** Re-seal this device's passkeys (no prompt), or one passkey by id (one prompt): "Needs update". */ + resealPlatformPasskeys: AuthController['resealPlatformPasskeys'] reloadVaults: () => void /** The headless controller (identity creation stores its key before registering it). */ readonly controller: AuthController @@ -152,6 +175,9 @@ interface AuthContextValue { const NO_KEYS: readonly WatchedKey[] = [] +/** Before the page's address is read: passkeys that hold a key on Platform stay hidden. */ +const PASSKEYS_NOT_CHECKED = 'Checking whether passkeys work on this page.' + const AuthContext = createContext(undefined) /** The grant a refused write asks for: the contract it was signed for (undefined: the sheet's default). */ @@ -253,6 +279,15 @@ export function AuthProvider({ topUpKey: (input: MasterInput, request: TopUpRequest) => controller.topUpKey(input, request), createRunnerKey: (input: MasterInput, request: LimitedKeyRequest) => controller.createRunnerKey(input, request), registerUsername: (input: MasterInput, label: string) => controller.registerUsername(input, label), + signInWithPasskey: withReload(controller.signInWithPasskey.bind(controller)), + addPlatformPasskey: controller.addPlatformPasskey.bind(controller), + pendingPlatformPasskey: controller.pendingPlatformPasskey.bind(controller), + finishPlatformPasskey: controller.finishPlatformPasskey.bind(controller), + abandonPlatformPasskey: controller.abandonPlatformPasskey.bind(controller), + listPlatformPasskeys: controller.listPlatformPasskeys.bind(controller), + removePlatformPasskey: controller.removePlatformPasskey.bind(controller), + platformPasskeyLeftOut: controller.platformPasskeyLeftOut.bind(controller), + resealPlatformPasskeys: controller.resealPlatformPasskeys.bind(controller), }), [controller, withReload], ) @@ -319,6 +354,27 @@ export function AuthProvider({ setLastIdentity(readLastIdentity(network)) }, [network, sessionIdentity, vaults]) + // Read in the browser only (it depends on the page's address): hidden until then. Where the + // page allows passkeys, the forge-meta Platform serves is read once, and only while someone + // could use them (signed in, or the sign-in sheet open), so a page that never connects to + // Platform does not start to for this. Hidden until that read says the vault is deployed. + const loginOpen = useUiStore((s) => s.loginOpen) + const passkeysWanted = sessionIdentity !== null || loginOpen + const [platformPasskeyProblem, setPlatformPasskeyProblem] = useState(PASSKEYS_NOT_CHECKED) + useEffect(() => { + const sync = controller.platformPasskeyProblem() + if (sync !== null) { + setPlatformPasskeyProblem(sync) + return + } + if (!passkeysWanted) return + let live = true + void controller.checkPlatformPasskeys().then((problem) => live && setPlatformPasskeyProblem(problem)) + return () => { + live = false + } + }, [controller, passkeysWanted]) + const locked = session === null && !resuming && vaults.length > 0 const value = useMemo( () => ({ @@ -348,11 +404,12 @@ export function AuthProvider({ lockedIdentity: locked ? lockedIdentityOf(vaults, lastIdentity) : null, unlockScope: session === null ? null : state.scope ?? null, newKeys: session === null ? NO_KEYS : state.newKeys ?? NO_KEYS, + platformPasskeyProblem, reloadVaults, controller, ...actions, }), - [actions, controller, funds, keyLimits, lastIdentity, locked, reloadVaults, resuming, session, signer, state.error, state.isLoading, state.newKeys, state.scope, state.step, vaults, vaultsError, vaultsLoaded], + [actions, controller, funds, keyLimits, lastIdentity, locked, platformPasskeyProblem, reloadVaults, resuming, session, signer, state.error, state.isLoading, state.newKeys, state.scope, state.step, vaults, vaultsError, vaultsLoaded], ) return {children} diff --git a/forge-web/e2e/passkey-vault.spec.ts b/forge-web/e2e/passkey-vault.spec.ts new file mode 100644 index 000000000..087e995fb --- /dev/null +++ b/forge-web/e2e/passkey-vault.spec.ts @@ -0,0 +1,274 @@ +import { test, expect, type Browser, type BrowserContext, type Page, type Route } from '@playwright/test' +import { existsSync, readFileSync } from 'node:fs' +import { E2E_NETWORK, PASSPHRASE, idFile, importIdentity, shot, unlock } from './helpers' + +/** + * Passkeys that hold a key on Platform (docs/security/passkey-vault.md): the sign-in sheet's + * "Sign in with a passkey", and Settings → Devices & keys → "Passkeys for other devices". + * Chromium's virtual authenticator (CDP `WebAuthn.addVirtualAuthenticator`, with PRF) stands in for + * Face ID, Touch ID or a phone. + * + * A WebAuthn relying party id cannot be an IP address, and Forge allows exactly `forge.dashhq.org` + * and `localhost`. The suite's default base URL is http://127.0.0.1:, so the specs that need + * a passkey open http://localhost: instead (the same local static server). + * + * The passkeys are inert until forge-meta has the `vaultEntry` type (a pending `--update meta` on + * sakura): the sign-in sheet shows no passkey tile and Settings no section until then. + * + * No network or spend (hermetic): + * + * E2E_DEVNET=sakura E2E_SKIP_BUILD=1 pnpm exec playwright test passkey-vault.spec.ts --project chromium + * + * h1. On http://127.0.0.1 (an address, never a relying party) the sheet offers no passkey sign-in. + * h2. On http://localhost, with Platform answering that no contract exists, it stays hidden too. + * + * Reads only (the devnet's nodes answer; skips itself when none accepts a connection, and when + * forge-meta has no `vaultEntry` yet): + * + * r1. A passkey that only unlocks the browser that made it (a random 32-byte user handle) says + * so, and nothing is stored. + * + * Live (real spend on a devnet with the RELAY test identity; `E2E_WRITE=1`; needs `vaultEntry` in + * the deployed forge-meta): + * + * E2E_DEVNET=sakura E2E_WRITE=1 pnpm exec playwright test passkey-vault.spec.ts --project chromium + * + * w1. Import the identity (one limited key) → the one-time offer → Settings → add a passkey + * (two prompts) → "Forget this browser" → "Sign in with a passkey" lands on the same key → + * renew the key with the identity file, which re-seals this device's passkey (no "Needs + * update") → remove the passkey. + */ + +test.skip(E2E_NETWORK === 'testnet', 'testnet has no forge-v2 deployment, so no forge-meta to hold passkey entries') + +const PORT = Number(process.env['E2E_PORT'] ?? 4321) +const LOCALHOST = `http://localhost:${PORT}` +const QUORUMS = /^https:\/\/quorums\.[a-z0-9-]+\.networks\.dash\.org\// +const DAPI = /\/org\.dash\.platform\.dapi\.v0\.Platform\/\w+$/ +const DRIVE_MESSAGE = 'contract not found error: contract not found when querying from value with contract info' + +/** A platform authenticator with PRF, user verification and resident keys, that approves every prompt. */ +async function addAuthenticator(page: Page): Promise<{ credentialCount(): Promise }> { + const cdp = await page.context().newCDPSession(page) + await cdp.send('WebAuthn.enable', { enableUI: false }) + const { authenticatorId } = await cdp.send('WebAuthn.addVirtualAuthenticator', { + options: { + protocol: 'ctap2', + ctap2Version: 'ctap2_1', + transport: 'internal', + hasResidentKey: true, + hasUserVerification: true, + isUserVerified: true, + hasPrf: true, + automaticPresenceSimulation: true, + }, + }) + return { credentialCount: async () => (await cdp.send('WebAuthn.getCredentials', { authenticatorId })).credentials.length } +} + +async function cors(route: Route): Promise> { + return { + 'access-control-allow-origin': (await route.request().headerValue('origin')) ?? '*', + 'access-control-expose-headers': 'grpc-status,grpc-message', + } +} + +/** Platform answers every read that no contract exists (as contracts-missing.spec.ts does). */ +async function platformHasNoContracts(context: BrowserContext): Promise<{ requests: number }> { + const stats = { requests: 0 } + await context.route(QUORUMS, async (route) => { + const previous = new URL(route.request().url()).pathname.endsWith('/previous') + await route.fulfill({ + status: 200, + contentType: 'application/json', + headers: await cors(route), + body: JSON.stringify(previous ? { success: true, data: { height: 10, quorums: [] } } : { success: true, data: [] }), + }) + }) + await context.route(DAPI, async (route) => { + if (route.request().method() === 'OPTIONS') { + return route.fulfill({ status: 204, headers: { ...(await cors(route)), 'access-control-allow-headers': '*', 'access-control-allow-methods': 'POST' } }) + } + stats.requests++ + return route.fulfill({ + status: 200, + body: '', + headers: { ...(await cors(route)), 'content-type': 'application/grpc-web+proto', 'grpc-status': '3', 'grpc-message': encodeURIComponent(DRIVE_MESSAGE) }, + }) + }) + return stats +} + +async function openSheet(page: Page): Promise { + await page.getByRole('banner').getByRole('button', { name: /^sign in$/i }).first().click() + await expect(page.getByTestId('tile-create')).toBeVisible({ timeout: 60_000 }) +} + +test.describe('hermetic: the sheet hides passkeys where they cannot work', () => { + test('h1. on 127.0.0.1 (an address is never a relying party) there is no passkey sign-in', async ({ page }) => { + await page.goto('/', { waitUntil: 'domcontentloaded' }) + await openSheet(page) + // The other options are there: only the passkey tile is not. + await expect(page.getByTestId('tile-import')).toBeVisible() + await page.waitForTimeout(1_500) + await expect(page.getByTestId('tile-passkey')).toHaveCount(0) + await shot(page, 'passkey-vault-01-no-tile-on-ip') + }) + + test('h2. on localhost, a network whose forge-meta cannot be read as having the vault keeps it hidden', async ({ browser }) => { + const context = await browser.newContext({ baseURL: LOCALHOST }) + const page = await context.newPage() + await addAuthenticator(page) + const stats = await platformHasNoContracts(context) + await page.goto('/', { waitUntil: 'domcontentloaded' }) + await openSheet(page) + // The sheet asked Platform (the check reads forge-meta once the sheet is open); it said no. + await expect.poll(() => stats.requests, { timeout: 60_000 }).toBeGreaterThan(0) + await page.waitForTimeout(3_000) + await expect(page.getByTestId('tile-passkey')).toHaveCount(0) + await expect(page.getByTestId('tile-import')).toBeVisible() + await context.close() + }) +}) + +/** Whether the first DAPI node of the devnet under test accepts a TCP connection (5 s). */ +async function devnetReachable(): Promise { + const { connect } = await import('node:net') + const { resolve } = await import('node:path') + const { deploymentFilePath } = await import('./network') + try { + const dep = JSON.parse(readFileSync(deploymentFilePath(undefined, resolve(__dirname, '../..')), 'utf8')) as { dapiAddresses?: string[]; v2?: { devnet?: { addresses?: string[] } } } + const address = (dep.dapiAddresses ?? dep.v2?.devnet?.addresses ?? [])[0] + if (!address) return false + const url = new URL(address) + return await new Promise((done) => { + const socket = connect({ host: url.hostname, port: Number(url.port || 443) }) + const end = (ok: boolean): void => { + socket.destroy() + done(ok) + } + socket.setTimeout(5000, () => end(false)) + socket.once('connect', () => end(true)) + socket.once('error', () => end(false)) + }) + } catch { + return false + } +} + +test.describe('reads only: a passkey this browser made for itself', () => { + test.beforeAll(async () => { + test.skip(!(await devnetReachable()), 'the devnet nodes are not reachable from this machine (the sheet needs Platform reads)') + }) + + test('r1. says it only unlocks the browser that made it', async ({ browser }) => { + const page = await (await browser.newContext({ baseURL: LOCALHOST })).newPage() + await addAuthenticator(page) + await page.goto('/', { waitUntil: 'domcontentloaded' }) + await openSheet(page) + const tile = page.getByTestId('tile-passkey') + // Shown only when forge-meta has `vaultEntry`: the update is pending on sakura. + const offered = await tile.waitFor({ state: 'visible', timeout: 60_000 }).then(() => true, () => false) + test.skip(!offered, 'forge-meta on this devnet has no vaultEntry yet (deploy-v2.mjs --update meta is pending), so the tile is correctly hidden') + + // A passkey with a random 32-byte user handle, as the browser vault's own passkeys have. + await page.evaluate(async () => { + await navigator.credentials.create({ + publicKey: { + rp: { id: 'localhost', name: 'Dash Forge' }, + user: { id: crypto.getRandomValues(new Uint8Array(32)), name: 'browser only', displayName: 'browser only' }, + challenge: crypto.getRandomValues(new Uint8Array(32)), + pubKeyCredParams: [{ type: 'public-key', alg: -7 }], + authenticatorSelection: { residentKey: 'required', userVerification: 'required' }, + extensions: { prf: {} } as AuthenticationExtensionsClientInputs, + }, + }) + }) + await tile.click() + await expect(page.getByRole('alert').filter({ hasText: /only unlocks the browser that made it/i })).toBeVisible({ timeout: 60_000 }) + // Nothing was stored: still signed out. + await expect(page.getByTestId('funds-pill')).toHaveCount(0) + await shot(page, 'passkey-vault-02-not-vault') + }) +}) + +test.describe('live (real spend)', () => { + test.skip(process.env['E2E_WRITE'] !== '1', 'live writes: set E2E_DEVNET=sakura E2E_WRITE=1 (and deploy vaultEntry to forge-meta first)') + test.skip(!existsSync(idFile('RELAY')), 'devnet test identities not found (RELAY)') + test.describe.configure({ mode: 'serial', timeout: 15 * 60_000 }) + + async function freshLocalhost(browser: Browser): Promise { + return (await browser.newContext({ baseURL: LOCALHOST })).newPage() + } + + test('w1. add a passkey, forget this browser, sign in with the passkey, renew (re-seal), remove it', async ({ browser }) => { + const page = await freshLocalhost(browser) + const authenticator = await addAuthenticator(page) + await page.goto('/', { waitUntil: 'domcontentloaded' }) + await importIdentity(page, 'RELAY') + + // The one-time offer, once, with what a passkey is not. + const offer = page.getByTestId('passkey-offer') + await expect(offer).toBeVisible({ timeout: 60_000 }) + await expect(offer).toContainText(/doesn't recover an account/i) + await page.getByTestId('passkey-offer-setup').click() + await expect(page.getByTestId('passkeys-section')).toBeVisible({ timeout: 60_000 }) + await expect(offer).toHaveCount(0) + + // Add: two prompts (make, then confirm), the encryption key off. + await page.getByTestId('passkey-add').click() + await expect(page.getByTestId('passkey-encryption-warning')).toHaveCount(0) + await page.getByTestId('passkey-add-confirm').click() + const mine = page.locator('[data-testid="passkey-row"][data-this-device="true"]') + await expect(mine).toHaveCount(1, { timeout: 180_000 }) + await expect(mine).not.toContainText(/needs update/i) + expect(await authenticator.credentialCount()).toBe(1) + await shot(page, 'passkey-vault-03-added') + + // The key this browser signs with, to compare after the passkey brings it back. + await page.goto('/settings/', { waitUntil: 'domcontentloaded' }) + await unlock(page) + const keyId = await page.getByTestId('key-id').getAttribute('data-key-id') + expect(keyId).not.toBeNull() + + // Forget this browser: nothing of the key is left here. + await page.getByRole('button', { name: /sign out & forget key/i }).click() + await page.getByTestId('confirm-action').click() + await expect(page.getByRole('banner').getByRole('button', { name: /^sign in$/i }).first()).toBeVisible({ timeout: 60_000 }) + + // Sign in with the passkey alone: one prompt, the same key. + await openSheet(page) + await page.getByTestId('tile-passkey').click() + await expect(page.getByTestId('funds-pill')).toBeVisible({ timeout: 120_000 }) + await page.goto('/settings/', { waitUntil: 'domcontentloaded' }) + await expect(page.getByTestId('key-id')).toHaveAttribute('data-key-id', keyId!, { timeout: 60_000 }) + await shot(page, 'passkey-vault-04-signed-in-with-passkey') + + // Renew with the identity file: the key changes, and this device's passkey is re-sealed to it. + await page.getByRole('button', { name: /^renew key$|renew with identity file/i }).first().click() + await page.setInputFiles('input[type="file"]', idFile('RELAY')) + await page.getByLabel('Passphrase', { exact: true }).fill(PASSPHRASE) + await page.getByLabel('Repeat passphrase').fill(PASSPHRASE) + await page.getByRole('button', { name: /renew this browser's key/i }).click() + // The reload above left this tab holding only the signing key: a renewal asks it to unlock + // first (one passkey gesture, which the virtual authenticator approves), then carries on. + const unlockFirst = page.getByTestId('renew-unlock') + if (await unlockFirst.waitFor({ state: 'visible', timeout: 20_000 }).then(() => true, () => false)) { + await unlockFirst.getByRole('button', { name: /unlock with passkey/i }).click() + } + await expect(page.getByTestId('key-id')).not.toHaveAttribute('data-key-id', keyId!, { timeout: 180_000 }) + // Client-side, not a reload: the re-seal runs in this tab after the renewal and a reload could cut it off. + await page.getByTestId('devices-keys-link').click() + await expect(page.getByTestId('passkeys-section')).toBeVisible({ timeout: 60_000 }) + await expect(mine).toHaveCount(1, { timeout: 60_000 }) + await expect(mine).not.toContainText(/needs update/i, { timeout: 120_000 }) + await shot(page, 'passkey-vault-05-resealed') + + // Remove it: the entry goes from Platform, and the list is empty. + await mine.getByTestId('passkey-remove').click() + await page.getByTestId('confirm-action').click() + // Passkeys an earlier run left behind (rows of "Another device") are not this test's to count. + await expect(mine).toHaveCount(0, { timeout: 180_000 }) + await shot(page, 'passkey-vault-06-removed') + }) +}) diff --git a/forge-web/e2e/wallet-login-v2.spec.ts b/forge-web/e2e/wallet-login-v2.spec.ts index e9229d27c..acd4d884c 100644 --- a/forge-web/e2e/wallet-login-v2.spec.ts +++ b/forge-web/e2e/wallet-login-v2.spec.ts @@ -93,7 +93,8 @@ test.describe('v2 request (read-only)', () => { await page.getByRole('banner').getByRole('button', { name: /^sign in$/i }).first().click() await expect(page.getByTestId('tile-wallet')).toBeVisible({ timeout: 60_000 }) // Wallet first where v2 is on offer; the buttons only (a cost line shares the testid prefix). - const order = await page.locator('button[data-testid^="tile-"]').evaluateAll((els) => els.map((e) => e.getAttribute('data-testid'))) + // The passkey tile (once forge-meta has the passkey vault) sits right after the wallet's; it is not under test here. + const order = (await page.locator('button[data-testid^="tile-"]').evaluateAll((els) => els.map((e) => e.getAttribute('data-testid')))).filter((id) => id !== 'tile-passkey') expect(order.slice(0, 4)).toEqual(['tile-wallet', 'tile-create', 'tile-import', 'tile-dg']) await expect(page.getByTestId('tile-wallet')).toContainText(/approve once for all of Forge/i) diff --git a/forge-web/lib/auth/controller.ts b/forge-web/lib/auth/controller.ts index 2ae8b2e79..e40f37352 100644 --- a/forge-web/lib/auth/controller.ts +++ b/forge-web/lib/auth/controller.ts @@ -36,17 +36,17 @@ import { errorMessage, shortId } from '../utils' import { stepClock, timed } from '../step-timing' import { DEPLOYMENTS, FORGE_CONTRACT_KINDS, contractKind, groupTrust, type ForgeIds, type GroupTrust } from '../deployments' import { assertGroupHolds, type GroupCheck } from './group-trust' -import { KeyUnusableError, SECURITY_LEVEL, WriteAuthError, assertWritesAllowed, balanceBeforeWrite, findSigningKey, measureActual, readIdentityBalance, serialized, type SpendEvent, type WriteAuth } from '../sdk/write' +import { ConsensusRefusal, KeyUnusableError, SECURITY_LEVEL, UnconfirmedWriteError, WriteAuthError, assertWritesAllowed, balanceBeforeWrite, findSigningKey, measureActual, readIdentityBalance, serialized, type SpendEvent, type WriteAuth } from '../sdk/write' import { APP_CONNECT_SIGNING_EXPIRY_MARGIN_MS } from '../vendor/platform-auth/app-connect' import { newV2LoginRequest, readChainClock, type V2LoginRequest } from './app-connect-v2' import { clearWalletRenewal, connectionId, markWalletRenewal, walletRenewalInFlight } from './connection-id' import { KEY_ADD_FLOOR_CREDITS, KEY_DISABLE_CREDITS, KEY_LIMITS_UPDATE_CREDITS, KEY_REGISTER_CREDITS, KEY_RENEW_CREDITS, NAME_REGISTER_CREDITS, NAME_REGISTER_FLOOR_CREDITS } from '../sdk/cost' import { authSdk, type WasmIdentity, type WasmKey } from '../sdk/facade' import type { HeldBrowserKey } from './create-identity' -import type { KeyLimits } from '../view/funds' +import { renewableInWallet, type KeyLimits } from '../view/funds' import { controlsKey, normalizeToWif } from './wif' -import { decodeIdentifier } from './base58' -import { retryWhileMissing } from '../view/retry' +import { base58Encode, decodeIdentifier } from './base58' +import { retryUntil, retryWhileMissing } from '../view/retry' import { authKeysFromFile, identityFileMatchesNetwork, masterMaterialFromFile } from './identity-file' import { NoUsernameKeyError, registerUsername, usernameKeysFromPhrase } from './username-register' import { dpnsLabelHolder, noteRegisteredDpnsName } from '../view/dpns' @@ -66,6 +66,42 @@ import { openHandoffReply, parseHandoffPayload, type HandoffRequest } from './ke import { acknowledgeKeys, checkKeys, forgetKeySnapshot, type WatchedKey } from './key-watch' import { DISABLEABLE, chunkKeyIds, keyRole, keyRows, otherKeysToDisable, type KeyRow } from './devices' import { hexToBytes } from '@noble/hashes/utils.js' +import { + KeyPurpose, + VaultError, + browserPasskeyAdapter, + recipientFromPrf, + bytesEqual, + wipe, + type ConfirmTarget, + type ConfirmedPasskey, + type OnChainKey, + type PasskeyAdapter, + type VaultEntryRecord, + type VaultPort, +} from '../vendor/platform-auth/passkey-vault' +import { clearPending, dropMarker, forgetPasskeyRecords, markerFor, ownMarkerFor, putMarker, readMarkers, readPending, writePending, type PasskeyMarker } from './passkey-vault/markers' +import { vaultEntryDeployed } from './passkey-vault/deployed' +import { PASSKEYS_NOT_DEPLOYED, passkeyVaultProblem, passkeyVaultRpId } from './passkey-vault/policy' +import { credentialBytes, credentialName, forgeVaultPort } from './passkey-vault/port' +import { + PlatformPasskeyError, + forgePasskeyVault, + needsReseal, + passkeyIsUseless, + passkeyRows, + platformPasskeyError, + sealableSession, + usableEncryptionKeyOf, + vaultPasskeyFailure, + wipeOpened, + wipeSession, + type ForgePasskeyVault, + type OpenedKeys, + type PlatformPasskeyRow, + type SealableSession, + type VaultForgeIds, +} from './passkey-vault/service' import { WrongMasterKeyError, disableHeldKeys, @@ -83,8 +119,11 @@ import { type TopUpRequest, } from './limited-key' import { + EncryptionKeyNotHeldError, + PASSKEY_TIMEOUT_MS, VaultLockedError, addExtraKey, + withEncryptionKey, forgetVault, hasExtraKeys, holdForSession, @@ -168,8 +207,9 @@ export interface AuthSession { readonly storage: 'vault' | 'session' /** * Where the stored key came from when this browser did not register it: `app-connect` (a - * wallet's App Connect grant: renew it in the wallet, {@link AuthController.walletRenewalRequest}) - * or `dg`. Absent for a key registered here with the master key. + * wallet's App Connect grant: renew it in the wallet, {@link AuthController.walletRenewalRequest}), + * `dg`, or `passkey` (restored from a passkey: it may be a wallet's or the master key's, so + * either renewal is offered). Absent for a key registered here with the master key. */ readonly origin?: KeyOrigin /** Which Forge contracts this session's keys can sign on. */ @@ -282,6 +322,20 @@ export type MasterInput = { fileText: string } | { mnemonic: string } /** How the SDK is obtained — injected so the controller stays testable and SSR-safe. */ export type SdkProvider = () => Promise +/** What passkeys that hold a key on Platform run on (`./passkey-vault`); tests replace them. */ +export interface PasskeyDeps { + /** The vault's chain port. Default: proved reads and Forge's write helpers over the SDK. */ + readonly port?: (sdk: EvoSDK, contractId: string, auth: WriteAuth | null) => VaultPort + /** WebAuthn. Default: the browser's, with the vault's timeout and Forge's prompt messages. */ + readonly adapter?: () => PasskeyAdapter + /** The page's address. Default: `window.location`. */ + readonly location?: () => { readonly hostname: string; readonly pathname: string } | null + /** Whether the browser can do WebAuthn here. Default: `passkeysAvailable`. */ + readonly available?: () => boolean + /** Whether the deployed forge-meta has the vault's entry type. Default: a proved contract fetch. */ + readonly deployed?: (sdk: EvoSDK, metaId: string) => Promise +} + /** Delete keys an earlier build left in plain localStorage. */ export function purgeLegacyKeystore(): void { if (typeof window === 'undefined') return @@ -340,6 +394,7 @@ export class AuthController { constructor( private readonly getSdk: SdkProvider, private readonly network: Network = DEFAULT_NETWORK, + private readonly passkeyDeps: PasskeyDeps = {}, ) { purgeLegacyKeystore() } @@ -561,7 +616,7 @@ export class AuthController { // A wallet's App Connect key starts no write in its last minutes: one signed now could // reach a block after it expired (APP_CONNECT_PROFILE.md). Renew it in the wallet. const expiresAt = current.keyLimits?.expiresAt - if (current.origin === 'app-connect' && expiresAt != null && expiresAt - Date.now() <= APP_CONNECT_SIGNING_EXPIRY_MARGIN_MS) { + if (renewableInWallet(current.origin) && expiresAt != null && expiresAt - Date.now() <= APP_CONNECT_SIGNING_EXPIRY_MARGIN_MS) { throw new KeyUnusableError('expired') } noteSessionUse(network) @@ -996,7 +1051,7 @@ export class AuthController { this.step('Setting up members-only content') await this.enableEncryption(identityId, material) } - return session + return this.keyChanged(session) } finally { if (material !== null && 'keys' in material) wipeMaterial(material) } @@ -1116,7 +1171,7 @@ export class AuthController { } // Kept: the request is spent. Until then a failed check can be retried with the same reply. request.wipe() - return session + return this.keyChanged(session) }) } @@ -1223,8 +1278,15 @@ export class AuthController { // unlock a key that no longer opens anything. const fresh = new Set([main.keyId, ...rest.map((k) => k.keyId)]) const disabled = appConnect ? await this.disabledKeyIds(identityId) : new Set() + // A key a passkey brought here is not this browser's wallet grant, so the wallet does not + // disable it with the renewal (it only replaces this browser's own connection): it stays live + // for the device that made it, held here never to sign, so the next renewal or revoke disables + // it and no passkey keeps it. + const replacedPasskeyKey = appConnect && previousKeyId !== null && (await storedOrigin(this.network, identityId, previousKeyId).catch(() => null)) === 'passkey' ? previousKeyId : null const held: ExtraKey[] = this.heldKeys(identityId).map((h) => ('contractId' in h ? h : { contractId: forge.core, keyId: h.keyId, wif: h.wif })) - const kept = [...held, ...(given ? [given] : [])].filter((h, i, all) => !fresh.has(h.keyId) && !disabled.has(h.keyId) && all.findIndex((x) => x.keyId === h.keyId) === i) + const kept = [...held, ...(given ? [given] : [])] + .filter((h, i, all) => !fresh.has(h.keyId) && !disabled.has(h.keyId) && all.findIndex((x) => x.keyId === h.keyId) === i) + .map((h) => (h.keyId === replacedPasskeyKey ? { ...h, holdOnly: true as const } : h)) const extra = [...rest.map((k) => toExtraKey(k, forge)), ...kept] const secret: VaultSecret = { identityId, keyId: main.keyId, wif: main.wif, ...(extra.length ? { extra } : {}) } let stored: StoreOutcome @@ -1256,7 +1318,7 @@ export class AuthController { // A shipped wallet registers an encryption key right after each auth key; a v2 grant does not. const walletKeys = appConnect ? [] : [main.keyId, ...rest.map((k) => k.keyId)] try { - return await this.open(secret, 'vault', main.limits ?? undefined, true, walletKeys) + return this.keyChanged(await this.open(secret, 'vault', main.limits ?? undefined, true, walletKeys)) } catch (e) { throw new Error(`Key saved on this device, but signing in did not finish (${errorMessage(e)}). Unlock to continue.`) } @@ -1306,7 +1368,7 @@ export class AuthController { */ async walletRenewalRequest(options: { readonly callbackUrl?: (requestHash: Uint8Array) => string | null } = {}): Promise { const session = this.state.session - if (!session || session.storage !== 'vault' || session.origin !== 'app-connect' || session.keyId === undefined) { + if (!session || session.storage !== 'vault' || !renewableInWallet(session.origin) || session.keyId === undefined) { throw new Error('Only a key your wallet granted can be renewed in your wallet. Renew it with your identity file or recovery phrase instead.') } const { identityId, keyId } = session @@ -1417,7 +1479,7 @@ export class AuthController { if (!secret) throw new VaultLockedError('unlock to continue') if (method !== null) { const { secret: finished } = await this.finishStagedRenewal(identityId, method) - if (finished) return this.open(finished, 'vault') + if (finished) return this.keyChanged(await this.open(finished, 'vault')) } return this.open(secret, 'vault', limits) }) @@ -1437,7 +1499,7 @@ export class AuthController { ? await unlockWithPasskey(this.network, identityId, (why) => this.step(why)) : await unlockWithPassphrase(this.network, identityId, method.passphrase) const { secret: finished, status } = await this.finishStagedRenewal(identityId, method) - if (finished) return this.open(finished, 'vault') + if (finished) return this.keyChanged(await this.open(finished, 'vault')) const main = (await listVaults(this.network)).find((v) => v.identityId === identityId && v.staged !== true) if (main === undefined || secret.keyId !== main.keyId) { // What opened is the staged key, not adopted: no session to open with it. Say why. (Only @@ -1649,8 +1711,10 @@ export class AuthController { /** * Disable this device's key for `identityId` on chain (the identity file or phrase supplies * the master key, used once), then forget it here. Forgetting alone does not revoke. + * `removePasskeys`: first delete the passkeys that hold the keys being disabled, signed by this + * key while it is still live (a stale passkey would only fail its sign-in, but its entry stays). */ - async revokeStored(identityId: string, input: MasterInput): Promise { + async revokeStored(identityId: string, input: MasterInput, options: { readonly removePasskeys?: boolean } = {}): Promise { return this.run(async () => { const stored = (await listVaults(this.network)).find((v) => v.identityId === identityId) if (!stored) throw new Error('no key for this identity is stored here') @@ -1659,6 +1723,9 @@ export class AuthController { await this.assertUnlockedIfWalletKeys(sdk, identityId, stored.keyId) const masterWif = await this.masterWifFor(identityId, input) const held = this.heldKeys(identityId) + // The passkeys holding these keys are deleted first, signed by this key while it is live. A + // delete that fails never stops the key from being disabled: a lost device's key comes first. + const notRemoved = options.removePasskeys === true ? await this.removePasskeysBeforeDisable(identityId, [stored.keyId, ...held.map((k) => k.keyId)]) : null await this.wordedMasterError(identityId, 'mnemonic' in input ? input.mnemonic : null, 'signed-in', () => this.charged(identityId, 'key:revoke', () => stored.keyId, () => held.length > 1 || (held.length === 1 && this.state.session?.unlimited) @@ -1668,6 +1735,7 @@ export class AuthController { ), ) await this.forget(identityId) + if (notRemoved !== null) this.setState({ notice: notRemoved }) }) } @@ -1886,9 +1954,10 @@ export class AuthController { /** * Disable one of the identity's keys (a lost device's, a key nobody here added) with the master * key, from the identity file or the recovery phrase. This browser's own key goes through - * {@link revokeStored}, which also forgets it here. + * {@link revokeStored}, which also forgets it here. `removePasskeys`: first delete the passkeys + * that hold that key (signed by this browser's key; {@link listPlatformPasskeys} says which). */ - async disableIdentityKey(input: MasterInput, keyId: number): Promise { + async disableIdentityKey(input: MasterInput, keyId: number, options: { readonly removePasskeys?: boolean } = {}): Promise { return this.run(async () => { const session = this.state.session if (session === null) throw new Error('sign in first') @@ -1897,11 +1966,13 @@ export class AuthController { if (!forge) throw new Error(`Dash Forge is not deployed on ${NETWORKS[this.network].key}`) const { identityId } = session const masterWif = await this.masterWifFor(identityId, input) + const notRemoved = options.removePasskeys === true ? await this.removePasskeysBeforeDisable(identityId, [keyId]) : null const sdk = await this.getSdk() const sent = await this.wordedMasterError(identityId, 'mnemonic' in input ? input.mnemonic : null, 'signed-in', () => this.charged(identityId, 'key:revoke', () => keyId, () => disableIdentityKeys(sdk, { network: this.network, identityId, masterWif, keyIds: [keyId], allowed: (k) => DISABLEABLE.has(keyRole(k, forge)) })), ) if (this.state.newKeys?.some((k) => k.keyId === keyId)) this.setState({ newKeys: this.state.newKeys.filter((k) => k.keyId !== keyId) }) + if (notRemoved !== null) this.setState({ notice: notRemoved }) return sent }) } @@ -1968,21 +2039,611 @@ export class AuthController { /** * Delete the stored key of `identityId` from this device (ending its session if open), and * what this browser recorded for the identity: its spend ledger, its notifications inbox, its - * comment drafts and the last-used marker (QW2-028). Write journals stay: they finish an interrupted write. So do + * comment drafts, its passkey markers and the last-used marker (QW2-028). Write journals stay: they finish an interrupted write. So do * the top-up records (`topUpRecords`, QW3-034: an unfinished top-up, and where the next one * starts), which the forget and revoke confirmations name. */ async forget(identityId: string): Promise { + // A background re-seal still running would write a passkey marker back after it is cleared. + await this.passkeyReseal if (this.state.session?.identityId === identityId) this.logout() forgetKeySnapshot(this.network, identityId) // The connection id stays (APP_CONNECT_PROFILE.md): a fresh one would leave the wallet's key // for this browser live. A renewal mark has nothing left to protect. clearWalletRenewal(this.networkKey, identityId) + // This device's passkey markers go too: nothing here vouches for a passkey any more. + await forgetPasskeyRecords(this.network, identityId) await forgetVault(this.network, identityId) forgetLastIdentity(this.network, identityId) clearDrafts(identityId) await Promise.allSettled([clearLedger(this.network, identityId), clearInbox(this.network, identityId)]) } + + // --------------------------------------------------------------------------- + // Passkeys that hold a key on Platform (`./passkey-vault`, PLAN-passkey-vault.md §3) + // --------------------------------------------------------------------------- + + /** The background re-seal the last key change started (it never rejects). */ + private passkeyReseal: Promise = Promise.resolve() + + private pageLocation(): { readonly hostname: string; readonly pathname: string } | null { + if (this.passkeyDeps.location) return this.passkeyDeps.location() + return typeof window === 'undefined' ? null : window.location + } + + /** + * Why passkeys that work on the user's other devices are not offered here (a sentence), or null. + * The UI hides the feature while it is not null. + */ + platformPasskeyProblem(): string | null { + const problem = passkeyVaultProblem(NETWORKS[this.network].v2, this.pageLocation(), this.passkeyDeps.available) + // The page and network allow it; the deployed forge-meta may not have the vault yet. + return problem ?? (this.vaultDeployed === false ? PASSKEYS_NOT_DEPLOYED : null) + } + + /** Whether the deployed forge-meta declares the vault's entry type: null until read (never cached when a read fails). */ + private vaultDeployed: boolean | null = null + private vaultDeployedRead: Promise | null = null + + /** + * {@link platformPasskeyProblem}, after reading the forge-meta Platform serves for the vault's + * entry type (once; a read that fails is not remembered). The UI shows passkey controls only + * when this is null: the sign-in and the Settings section stay hidden, not broken, until the + * deployed contract has the type. A failed read is a problem too, so nothing shows unverified. + */ + async checkPlatformPasskeys(): Promise { + const problem = this.platformPasskeyProblem() + if (problem !== null || this.vaultDeployed === true) return problem + const meta = NETWORKS[this.network].v2?.meta + if (meta === undefined) return PASSKEYS_NOT_DEPLOYED + this.vaultDeployedRead ??= (async () => { + const sdk = await this.getSdk() + this.vaultDeployed = await (this.passkeyDeps.deployed ?? vaultEntryDeployed)(sdk, meta) + })().finally(() => { + this.vaultDeployedRead = null + }) + try { + await this.vaultDeployedRead + } catch { + return "Couldn't check whether passkeys that work on your other devices are available. Reload to try again." + } + return this.platformPasskeyProblem() + } + + /** forge-meta, where the vault's entries live; throws when this network has none. */ + private vaultForge(): VaultForgeIds { + const forge = NETWORKS[this.network].v2 + if (forge?.meta === undefined) throw unavailable(passkeyVaultProblem(forge)) + return { ...forge, meta: forge.meta } + } + + /** The vault's chain port: reads with proofs, and writes signed by `auth` when given. */ + private passkeyPort(sdk: EvoSDK, forge: VaultForgeIds, auth: WriteAuth | null): VaultPort { + return this.passkeyDeps.port?.(sdk, forge.meta, auth) ?? forgeVaultPort({ sdk, contractId: forge.meta, auth }) + } + + /** The passkey vault on this page; throws {@link PlatformPasskeyError} 'unavailable' where it is not offered. */ + private passkeyVault(sdk: EvoSDK, auth: WriteAuth | null): { readonly vault: ForgePasskeyVault; readonly port: VaultPort; readonly forge: VaultForgeIds } { + const forge = this.vaultForge() + const problem = this.platformPasskeyProblem() + const rpId = passkeyVaultRpId(this.pageLocation()) + if (problem !== null || rpId === null) throw unavailable(problem) + const port = this.passkeyPort(sdk, forge, auth) + const adapter = this.passkeyDeps.adapter?.() ?? browserPasskeyAdapter({ timeoutMs: PASSKEY_TIMEOUT_MS, mapError: vaultPasskeyFailure }) + return { vault: forgePasskeyVault({ port, adapter, rpId, forge, network: this.network }), port, forge } + } + + /** The session's signer for the vault's writes; their cost reaches the ledger like any charge. */ + private passkeyWriter(identityId: string): WriteAuth { + const auth = this.writeAuth + if (auth === null || auth.identityId !== identityId) throw new WriteAuthError('this browser is signed out — sign in to sign') + return { ...auth, onSpend: (e) => this.spendListener?.(e) } + } + + /** The vault and its port, signing as `identityId`'s session. */ + private async writableVault(identityId: string): Promise<{ readonly vault: ForgePasskeyVault; readonly port: VaultPort; readonly forge: VaultForgeIds }> { + return this.passkeyVault(await this.getSdk(), this.passkeyWriter(identityId)) + } + + /** The vault's port for reads only (needs no relying party: it never prompts). */ + private async readPort(): Promise { + return this.passkeyPort(await this.getSdk(), this.vaultForge(), null) + } + + /** The session of a key this browser keeps: what every passkey action acts for. */ + private vaultSession(): AuthSession { + const session = this.state.session + if (session === null || session.storage !== 'vault') throw new PlatformPasskeyError('Sign in with a key this browser keeps first.', 'ineligible') + return session + } + + /** + * The identity whose passkeys an add or re-seal manages: a stored key's session with the whole + * vault open in this tab (wallet grants and the encryption key are sealed too). A resumed tab + * throws {@link UnlockNeededError}: `unlockMore`, then try again. + */ + private passkeyOwner(): string { + const session = this.vaultSession() + this.requireFullUnlock(session.identityId) + if (this.unlockedVaultSecret(session.identityId) === null) throw new VaultLockedError("unlock this browser's key first") + return session.identityId + } + + /** + * A copy of the identity's usable encryption key from this browser's vault, for a passkey the + * user chose to add it to (it cannot be taken back from an entry once written). The caller wipes it. + */ + private async encryptionForPasskey(identityId: string, keys: readonly OnChainKey[], forge: VaultForgeIds): Promise<{ keyId: number; secret: Uint8Array }> { + const usable = usableEncryptionKeyOf(keys, forge) + const missing = new PlatformPasskeyError( + "This browser doesn't hold your identity's current encryption key. Import it in Settings → Members-only and private content first, or add the passkey without it.", + 'ineligible', + ) + if (usable === null) throw missing + try { + return await withEncryptionKey(this.network, identityId, async (keyId, secret) => ({ keyId, secret: secret.slice() }), usable.id) + } catch (e) { + if (e instanceof EncryptionKeyNotHeldError || e instanceof VaultLockedError) throw missing + throw e + } + } + + /** + * What this session seals, against the identity's keys read now with proofs (`sealableSession`). + * The caller wipes `session`. + */ + private async sealable(identityId: string, port: VaultPort, forge: VaultForgeIds, withEncryption: boolean): Promise<{ session: SealableSession; keys: OnChainKey[] }> { + const secret = this.unlockedVaultSecret(identityId) + if (secret === null) throw new VaultLockedError("unlock this browser's key first") + const ownerId = decodeIdentifier(identityId) + // Right after a renewal a node may not show the new key yet: read again a few times. + const keys = await retryUntil(() => port.identityKeys(ownerId), (k) => k === null || k.some((x) => x.id === secret.keyId), 3) + if (keys === null) throw new PlatformPasskeyError(`Platform doesn't show identity ${shortId(identityId)}.`, 'failed') + const encryption = withEncryption ? await this.encryptionForPasskey(identityId, keys, forge) : null + try { + return { session: sealableSession({ ownerId, secret, keys, forge, now: Date.now(), encryption }), keys } + } finally { + if (encryption) wipe(encryption.secret) + } + } + + /** + * Add a passkey that holds this session's key on Platform, so another device signs in with it + * (PLAN-passkey-vault.md §3 "Enrolment"). Two prompts: make the passkey, then confirm it. Its + * entry holds the main key, the live wallet grants and, with `includeEncryptionKey`, the + * encryption key (default off: an entry once written can't be taken back, so removing the passkey + * doesn't lock its holder out of private content). Needs the whole vault open in this tab, no + * unfinished key renewal, a budgeted Forge key, and fewer than 10 passkeys. Its write is paid + * from the key's budget. A passkey made but not yet seen on Platform is kept for + * {@link finishPlatformPasskey} ("Check again"), across reloads. + */ + async addPlatformPasskey(options: { readonly includeEncryptionKey?: boolean; readonly userName?: string } = {}): Promise { + const identityId = this.passkeyOwner() + if ((await stagedInfo(this.network, identityId)) !== null) { + throw new PlatformPasskeyError("Finish or discard this device's unfinished key renewal first (Settings → This browser's key).", 'ineligible') + } + // One unfinished passkey at a time: its first write may have landed, and only its record says so. + if ((await readPending(this.network, identityId)) !== null) { + throw new PlatformPasskeyError('Finish adding the passkey you started (Check again), or discard it, first.', 'pending') + } + const { vault, port, forge } = await this.writableVault(identityId) + // Before any prompt: this session's keys must be ones a passkey may hold. + wipeSession((await this.sealable(identityId, port, forge, options.includeEncryptionKey === true)).session) + const ownerId = decodeIdentifier(identityId) + const pending: ConfirmTarget = await inForgeWords(vault.enroll({ ownerId, keys: [] }, { userName: options.userName ?? shortId(identityId) })) + try { + await writePending(this.network, identityId, pending) + } catch (e) { + await vault.abandon({ credentialId: pending.credentialId, createPrf: pending.createPrf ?? null }).catch(() => undefined) + throw e + } + await this.storePasskey(identityId, vault, port, forge, pending, options.includeEncryptionKey === true) + } + + /** The passkey an add left unfinished on this device (made, not yet seen on Platform), or null. */ + async pendingPlatformPasskey(): Promise<{ readonly id: string } | null> { + const identityId = this.state.session?.identityId + if (identityId === undefined) return null + const pending = await readPending(this.network, identityId) + return pending === null ? null : { id: credentialName(pending.credentialId) } + } + + /** + * "Check again" for {@link pendingPlatformPasskey}: confirm the passkey (one prompt), seal this + * session to it (or re-seal its entry, if the first write landed) and wait until Platform shows it. + */ + async finishPlatformPasskey(options: { readonly includeEncryptionKey?: boolean } = {}): Promise { + const identityId = this.passkeyOwner() + const pending = await readPending(this.network, identityId) + if (pending === null || !bytesEqual(pending.ownerId, decodeIdentifier(identityId))) throw new PlatformPasskeyError('No passkey is waiting to be added here.', 'no-entry') + const { vault, port, forge } = await this.writableVault(identityId) + await this.storePasskey(identityId, vault, port, forge, { ownerId: pending.ownerId, credentialId: pending.credentialId }, options.includeEncryptionKey === true) + } + + /** + * Give up {@link pendingPlatformPasskey}. Its first write may have landed: an entry Platform shows + * is deleted first (a paid delete, refunded), so none is left that no passkey opens. Then the + * passkey provider is told the passkey is unused, and it is forgotten here. + */ + async abandonPlatformPasskey(): Promise { + const { identityId } = this.vaultSession() + const pending = await readPending(this.network, identityId) + if (pending === null) return + const { port, vault } = await this.offeredVault(identityId) + // A read that fails throws: nothing is given up while its entry may be there. + const entry = await port.byCredential(pending.ownerId, pending.credentialId) + if (entry !== null) await port.remove({ ownerId: pending.ownerId, entry }) + await vault?.abandon({ credentialId: pending.credentialId, createPrf: null }) + await clearPending(this.network, identityId, pending.credentialId) + } + + /** + * The port signing as `identityId`'s session, and the vault when it is offered on this page: + * where it is not (no relying party here), entries are still deleted, but no provider is told. + */ + private async offeredVault(identityId: string): Promise<{ readonly port: VaultPort; readonly vault: ForgePasskeyVault | null }> { + const sdk = await this.getSdk() + const writer = this.passkeyWriter(identityId) + if (this.platformPasskeyProblem() === null) return this.passkeyVault(sdk, writer) + return { port: this.passkeyPort(sdk, this.vaultForge(), writer), vault: null } + } + + /** + * Forget an unfinished passkey and tell its provider it is unused, but only when Platform proves + * no entry of it exists: an entry there (or a read that failed) keeps it pending, for "Check + * again" or {@link abandonPlatformPasskey}, which deletes the entry first. + */ + private async dropPendingPasskey(identityId: string, vault: ForgePasskeyVault, port: VaultPort, target: ConfirmTarget): Promise { + const entry = await port.byCredential(target.ownerId, target.credentialId).catch(() => undefined) + if (entry !== null) return + await vault.abandon({ credentialId: target.credentialId, createPrf: target.createPrf ?? null }).catch(() => undefined) + await clearPending(this.network, identityId, target.credentialId).catch(() => undefined) + } + + /** + * Confirm `target` (a prompt limited to it), seal this session to it, write, wait until Platform + * shows it, then mark it this device's. A closed prompt or a write not seen yet keeps it pending; + * a passkey that can never hold the key (no PRF, another identity's, refused) is dropped. + */ + private async storePasskey(identityId: string, vault: ForgePasskeyVault, port: VaultPort, forge: VaultForgeIds, target: ConfirmTarget, withEncryption: boolean): Promise { + let confirmed: ConfirmedPasskey + try { + confirmed = await vault.confirm(target) + } catch (e) { + if (passkeyIsUseless(e)) await this.dropPendingPasskey(identityId, vault, port, target) + throw platformPasskeyError(e) + } finally { + // Not needed again: "Check again" confirms against the entry, without it. + wipe(target.createPrf) + } + let facts: Pick + try { + const { session } = await this.sealable(identityId, port, forge, withEncryption) + facts = sealedFacts(session) + try { + await vault.store(session, confirmed) + } finally { + wipeSession(session) + } + } catch (e) { + // Refused, over the cap, or keys a passkey may not hold: trying again would not change that + // (dropped once Platform shows no entry of it). Anything else (a read that failed, a write + // not seen) may still land: kept for "Check again". + if (e instanceof ConsensusRefusal || e instanceof PlatformPasskeyError || (e instanceof VaultError && e.code === 'too-many')) await this.dropPendingPasskey(identityId, vault, port, target) + throw platformPasskeyError(e instanceof UnconfirmedWriteError ? new VaultError(e.message, 'not-visible') : e) + } + await inForgeWords(vault.waitForEntry(target.ownerId, target.credentialId, confirmed.recipientKey)) + await putMarker(this.network, identityId, { credentialId: target.credentialId.slice(), recipientKey: confirmed.recipientKey.slice(), ...facts, addedAt: Date.now() }) + await clearPending(this.network, identityId, target.credentialId) + } + + /** + * Sign in on a new device with a passkey that holds a key on Platform (PLAN-passkey-vault.md §3): + * one prompt for any of this site's passkeys, the entry it names opened with its PRF output and + * every key checked against the identity read with proofs, then kept in this browser's vault + * protected by the same passkey (its local key is HKDF-derived from that PRF output under the + * vault's own label). Refuses ({@link PlatformPasskeyError} 'held') when this browser already + * keeps a key for the identity: unlock that one instead. A passkey this browser made for its own + * vault only is 'not-vault'. + */ + async signInWithPasskey(): Promise { + return this.run(async () => { + this.step('Connecting to Dash Platform') + const sdk = await this.getSdk() + const { vault } = this.passkeyVault(sdk, null) + this.step('Waiting for your passkey') + const opened = await inForgeWords(vault.open({ keepPrfOutput: true })) + const keys: OpenedKeys = opened.result + const prfOutput = opened.prfOutput + try { + if (prfOutput === null) throw new PlatformPasskeyError('The passkey gave no key.', 'failed') + const identityId = base58Encode(opened.ownerId) + const held = (await listVaults(this.network)).find((v) => v.identityId === identityId && v.staged !== true) + if (held !== undefined) { + throw new PlatformPasskeyError( + held.keyId === keys.keyId ? 'This browser already keeps this key. Unlock it instead.' : 'This browser already keeps another key for this identity. Unlock it instead.', + 'held', + ) + } + const secret: VaultSecret = { identityId, keyId: keys.keyId, wif: keys.wif, ...(keys.extra.length > 0 ? { extra: keys.extra } : {}) } + // The same credential protects the browser vault: its PRF input is the salt. + const protection: Protection = { passkey: { credentialId: opened.credentialId, prfSalt: vault.prfInput, output: prfOutput } } + this.step('Saving the key with your passkey') + let committed: StoreOutcome + try { + committed = await this.commitKey(secret, protection, { expectHeldKeyId: null, origin: 'passkey' }) + } catch (e) { + if (e instanceof VaultChangedError) throw new PlatformPasskeyError('Another tab saved a key for this identity meanwhile. Unlock it instead.', 'held') + throw e + } + if (committed.readBackFailed) { + this.setState({ notice: "Signed in, but this browser may not keep the key after it closes (its storage did not read back). Keep your identity file or recovery phrase handy." }) + } + // This device's passkey from now on. Its recipient key is derived from the PRF output here, + // not taken from the entry read back (opening already refused any other). + const recipient = recipientFromPrf(prfOutput) + wipe(recipient.privateKey) + await putMarker(this.network, identityId, { + credentialId: opened.credentialId.slice(), + recipientKey: recipient.publicKey, + keyIds: keys.keyIds, + ...(keys.encryption !== null ? { encryptionKeyId: keys.encryption.keyId } : {}), + addedAt: Date.now(), + }).catch(() => undefined) + const core = NETWORKS[this.network].v2?.core + if (keys.encryption !== null && core !== undefined) { + this.step('Setting up members-only content') + // Checked against the identity again and sealed into the vault; wipes its copy. + await adoptEncryptionKey(sdk, this.network, identityId, core, keys.encryption.secret.slice()).catch((e: unknown) => { + this.setState({ notice: `Signed in, but private repos could not be enabled: ${errorMessage(e)}.` }) + }) + } + try { + return await this.open(secret, 'vault') + } catch (e) { + throw new Error(`Key saved on this device, but signing in did not finish (${errorMessage(e)}). Unlock to continue.`) + } + } finally { + wipe(prfOutput) + wipeOpened(keys) + } + }) + } + + /** The key ids this session would seal now (slot 0 first), or just its main key's when the rest is locked. */ + private sessionAuthIds(session: AuthSession, keys: readonly OnChainKey[], forge: VaultForgeIds): { readonly ids: readonly number[]; readonly mainOnly: boolean } { + const secret = this.unlockedVaultSecret(session.identityId) + if (secret !== null) { + try { + const s = sealableSession({ ownerId: decodeIdentifier(session.identityId), secret, keys, forge, now: Date.now() }) + const ids = s.keys.map((k) => k.keyId) + wipeSession(s) + return { ids, mainOnly: false } + } catch { + /* a key no passkey may hold: only its id is compared */ + } + } + return { ids: session.keyId !== undefined ? [session.keyId] : [], mainOnly: true } + } + + /** + * The signed-in identity's passkeys, for Settings → Devices & keys: when each was added, whether + * it is this device's, the key it holds and that key's state, and whether it needs an update + * (it holds an older key or other grants than this session's). Reads only, with proofs. + */ + async listPlatformPasskeys(): Promise { + const session = this.vaultSession() + const forge = this.vaultForge() + const port = await this.readPort() + const ownerId = decodeIdentifier(session.identityId) + const [entries, keys, markers] = await Promise.all([port.list(ownerId), port.identityKeys(ownerId), readMarkers(this.network, session.identityId)]) + const onChain = keys ?? [] + const auth = this.sessionAuthIds(session, onChain, forge) + return passkeyRows({ entries, markers, keys: onChain, authIds: auth.ids, mainOnly: auth.mainOnly, usableEncryptionId: usableEncryptionKeyOf(onChain, forge)?.id ?? null, now: Date.now() }) + } + + /** + * How many of this browser's wallet keys a passkey leaves out because they have no spending + * limit or no expiry (an entry's ciphertext is public for good, so a leaked passkey never yields + * such a key): they work on this device only. 0 when nothing is left out, or it cannot be told + * (a locked or resumed tab, Platform unreachable). Reads only. + */ + async platformPasskeyLeftOut(): Promise { + try { + const session = this.vaultSession() + const secret = this.unlockedVaultSecret(session.identityId) + if (secret === null || (secret.extra?.length ?? 0) === 0) return 0 + const ownerId = decodeIdentifier(session.identityId) + const keys = await (await this.readPort()).identityKeys(ownerId) + if (keys === null) return 0 + const sealed = sealableSession({ ownerId, secret, keys, forge: this.vaultForge(), now: Date.now() }) + wipeSession(sealed) + return sealed.leftOut ?? 0 + } catch { + return 0 + } + } + + /** + * Delete one of the identity's passkeys (`id` from {@link listPlatformPasskeys}); its deposit is + * refunded. Only a passkey this device made or signed in with is reported to its provider as + * unused: another device's credential id is not this browser's to judge. The key it held stays + * live, and so does anything already copied from it: removing a passkey revokes nothing. + */ + async removePlatformPasskey(id: string): Promise { + const { identityId } = this.vaultSession() + const credentialId = credentialBytes(id) + const entry = await (await this.readPort()).byCredential(decodeIdentifier(identityId), credentialId) + if (entry !== null) await this.removePasskeyEntries(identityId, [entry]) + else await dropMarker(this.network, identityId, credentialId) + } + + /** Delete `entries` as `identityId`'s session, signalling this device's own credentials only. */ + private async removePasskeyEntries(identityId: string, entries: readonly VaultEntryRecord[]): Promise { + // A background re-seal still running would write a marker back after this drops it. + await this.passkeyReseal + const { port, vault } = await this.offeredVault(identityId) + const markers = await readMarkers(this.network, identityId) + for (const entry of entries) { + const thisDevice = markerFor(markers, entry.credentialId) !== null + if (vault !== null) await vault.remove(entry, { thisDevice }) + else await port.remove({ ownerId: entry.ownerId, entry }) + await dropMarker(this.network, identityId, entry.credentialId) + } + } + + /** + * {@link removePasskeysNaming} before a key is disabled, where a failure must not stop the + * disable (this browser's own key may be spent or about to expire, Platform may be slow): it + * returns what to tell the user once the key is disabled, or null. A locked tab still throws, + * as the disable needs the whole vault too. + */ + private async removePasskeysBeforeDisable(identityId: string, keyIds: readonly number[]): Promise { + try { + await this.removePasskeysNaming(identityId, keyIds) + return null + } catch (e) { + if (e instanceof UnlockNeededError || e instanceof VaultLockedError) throw e + return `The key was disabled, but the passkeys that hold it could not be removed: ${errorMessage(e)}. Remove them in Settings → Devices & keys.` + } + } + + /** Delete the identity's passkeys whose entries name one of `keyIds` (before those keys are disabled). */ + private async removePasskeysNaming(identityId: string, keyIds: readonly number[]): Promise { + if (this.state.session?.identityId !== identityId || this.state.session.storage !== 'vault') { + throw new PlatformPasskeyError('Sign in first: removing the passkeys that hold this key needs it to sign.', 'ineligible') + } + const naming = (await (await this.readPort()).list(decodeIdentifier(identityId))).filter((e) => keyIds.includes(e.authKeyId)) + await this.removePasskeyEntries(identityId, naming) + } + + /** + * Seal this session's keys again into the identity's passkeys (after a key change: a renewal, a + * new wallet grant, a new encryption key). + * - Without `id`: every passkey this device made or signed in with whose entry is still sealed to + * the recipient key this device recorded for it, and needs it (no prompt). Entries of other + * devices are only counted (`needUpdate`): they show "Needs update". + * - With `id` (from {@link listPlatformPasskeys}): one prompt limited to that passkey, whose + * derived key must be its entry's, then a re-seal. `includeEncryptionKey` says whether it holds + * the encryption key; by default, whether it did (this device's), else not. + * Each re-seal is a paid replace of the entry. Needs the whole vault open in this tab. + */ + async resealPlatformPasskeys(options: { readonly id?: string; readonly includeEncryptionKey?: boolean } = {}): Promise<{ readonly resealed: number; readonly needUpdate: number }> { + const session = this.vaultSession() + const markers = await readMarkers(this.network, session.identityId) + // Nothing this device made: no read, no write (a key change on a device without passkeys). + if (options.id === undefined && markers.length === 0) return { resealed: 0, needUpdate: 0 } + const identityId = this.passkeyOwner() + const { vault, port, forge } = await this.writableVault(identityId) + const ownerId = decodeIdentifier(identityId) + const entries = await port.list(ownerId) + if (options.id !== undefined) { + const credentialId = credentialBytes(options.id) + const entry = entries.find((e) => bytesEqual(e.credentialId, credentialId)) + if (entry === undefined) throw new PlatformPasskeyError('That passkey is not on Platform any more.', 'no-entry') + const own = ownMarkerFor(markers, entry) + const confirmed = await inForgeWords(vault.confirm({ ownerId, credentialId, recipientKey: entry.recipientKey })) + // This device's passkey keeps the encryption key it held unless told otherwise. + const { session: sealed } = await this.sealable(identityId, port, forge, options.includeEncryptionKey ?? own?.encryptionKeyId !== undefined) + try { + await vault.reseal(entry, sealed, { trustedRecipient: confirmed }) + if (own !== null) await putMarker(this.network, identityId, resealedMarker(own, sealed)) + } catch (e) { + throw platformPasskeyError(e) + } finally { + wipeSession(sealed) + } + return { resealed: 1, needUpdate: 0 } + } + const plain = await this.sealable(identityId, port, forge, false) + const authIds = plain.session.keys.map((k) => k.keyId) + const usableEncryptionId = usableEncryptionKeyOf(plain.keys, forge)?.id ?? null + let withEncryption: SealableSession | null | undefined + let resealed = 0 + let needUpdate = 0 + try { + for (const entry of entries) { + const marker = ownMarkerFor(markers, entry) + if (!needsReseal(entry, marker, authIds, usableEncryptionId)) continue + // Another device's (or a replaced) entry: only a prompt for that passkey may re-seal it. + if (marker === null) { + needUpdate += 1 + continue + } + // The encryption key changed (often because a passkey may have leaked): the new one goes + // into an entry only when the user updates that passkey, never silently. + if (marker.encryptionKeyId !== undefined && marker.encryptionKeyId !== usableEncryptionId) { + needUpdate += 1 + continue + } + // An entry that held the encryption key gets the current one; when this browser doesn't + // hold it, the entry is left as it is ("Needs update") rather than re-sealed without it. + if (marker.encryptionKeyId !== undefined && withEncryption === undefined) { + withEncryption = await this.sealable(identityId, port, forge, true).then((r) => r.session, () => null) + } + const sealed = marker.encryptionKeyId === undefined ? plain.session : withEncryption + // Signed out, or another identity, meanwhile: no marker is written for it any more. + if (!sealed || this.state.session?.identityId !== identityId) { + needUpdate += 1 + continue + } + try { + // Only this device's own record vouches for the recipient key, never the entry read back. + const trusted = vault.trustMarker({ ownerId, credentialId: marker.credentialId, recipientKey: marker.recipientKey }) + await vault.reseal(entry, sealed, { trustedRecipient: trusted }) + if (this.state.session?.identityId === identityId) await putMarker(this.network, identityId, resealedMarker(marker, sealed)) + resealed += 1 + } catch { + // One entry that fails (changed meanwhile, a write refused) leaves the others to try. + needUpdate += 1 + } + } + } finally { + wipeSession(plain.session) + if (withEncryption) wipeSession(withEncryption) + } + return { resealed, needUpdate } + } + + /** + * A key change in this tab (a renewal, a new grant, a finished staged renewal): re-seal this + * device's own passkeys in the background. Never fails the step that changed the key; an entry + * left behind shows "Needs update". + */ + private keyChanged(session: AuthSession): AuthSession { + try { + if (session.storage === 'vault' && this.platformPasskeyProblem() === null) { + this.passkeyReseal = this.passkeyReseal.then(() => this.resealPlatformPasskeys()).then( + () => undefined, + () => undefined, + ) + } + } catch { + /* never fails the step that changed the key */ + } + return session + } +} + +const unavailable = (problem: string | null): PlatformPasskeyError => new PlatformPasskeyError(problem ?? 'Passkeys are not available here.', 'unavailable') + +/** `p`, its rejection in Forge's words (`platformPasskeyError`). */ +function inForgeWords(p: Promise): Promise { + return p.catch((e: unknown) => { + throw platformPasskeyError(e) + }) +} + +/** What a marker records of a sealed session: its key ids in slot order, and its encryption key. */ +function sealedFacts(session: SealableSession): Pick { + const enc = session.keys.find((k) => k.purpose === KeyPurpose.ENCRYPTION) + return { keyIds: session.keys.map((k) => k.keyId), ...(enc ? { encryptionKeyId: enc.keyId } : {}) } +} + +/** `marker` after a re-seal of `session` to it: what it holds now. */ +function resealedMarker(marker: PasskeyMarker, session: SealableSession): PasskeyMarker { + const { encryptionKeyId: _before, keyIds: _was, ...kept } = marker + return { ...kept, ...sealedFacts(session) } } /** An identity file for another identity than the one signed in here (QW3-028). */ diff --git a/forge-web/lib/auth/forget-local.test.ts b/forge-web/lib/auth/forget-local.test.ts index 2e6b71e32..3ac83f9aa 100644 --- a/forge-web/lib/auth/forget-local.test.ts +++ b/forge-web/lib/auth/forget-local.test.ts @@ -3,14 +3,18 @@ * What this browser keeps about an identity beyond its key (QA wave 2): * - QW2-025: the identity signed in last, which Unlock preselects among several stored keys; * - QW2-028: "Sign out & forget key" removes the spend ledger, the notifications inbox and the - * last-used marker too, so a shared computer keeps no trace of the identity. + * last-used marker too, so a shared computer keeps no trace of the identity; + * - the passkey vault: this device's passkey markers and an unfinished enrolment go with it, so + * nothing here vouches for a passkey of a forgotten identity (no re-seal without a prompt). */ import { afterEach, describe, expect, it } from 'vitest' import { idbEntries, idbPut, resetMemoryStores } from '../idb' import { clearLedger, readBaseline, readLedger, recordSpend } from '../spend' import { clearInbox } from '../view/inbox' +import { AuthController } from './controller' import { forgetLastIdentity, lockedIdentityOf, readLastIdentity, rememberLastIdentity } from './last-identity' +import { putMarker, readMarkers, readPending, writePending } from './passkey-vault/markers' const A = 'JCuebezAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' const B = 'BWv9Ku1BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB' @@ -62,4 +66,19 @@ describe('forgetting an identity here', () => { await clearInbox('devnet', A) expect((await idbEntries('inbox')).map(([k]) => k)).toEqual([`devnet:${B}:subs`]) }) + + it("clears this device's passkey markers and unfinished enrolment, and leaves other identities' alone", async () => { + const marker = { credentialId: new Uint8Array(16).fill(1), recipientKey: new Uint8Array(32).fill(2), keyIds: [5], addedAt: 1 } + for (const id of [A, B]) { + await putMarker('devnet', id, marker) + await writePending('devnet', id, { ownerId: new Uint8Array(32).fill(3), credentialId: new Uint8Array(16).fill(4) }) + } + await new AuthController(async () => { + throw new Error('no network in this test') + }, 'devnet').forget(A) + expect(await readMarkers('devnet', A)).toEqual([]) + expect(await readPending('devnet', A)).toBeNull() + expect(await readMarkers('devnet', B)).toHaveLength(1) + expect(await readPending('devnet', B)).not.toBeNull() + }) }) diff --git a/forge-web/lib/auth/passkey-session.test.ts b/forge-web/lib/auth/passkey-session.test.ts new file mode 100644 index 000000000..a4b35841b --- /dev/null +++ b/forge-web/lib/auth/passkey-session.test.ts @@ -0,0 +1,590 @@ +/** + * Passkeys that hold a key on Platform, through the controller (PLAN-passkey-vault.md §3, §5): add + * one on a signed-in device, sign in with it on a new one (kept in the browser vault under the same + * passkey, its PRF input as the salt), the refusals (a browser-only passkey, a planted entry, a + * browser that already keeps a key, the cap), re-seals that touch only this device's own entries, + * removal that signals only this device's credentials, the revoke hook, and the wipes. + * + * The chain is a fake whose keys both the session checks and the vault's port read; the port's + * storage is the core's in-memory one; WebAuthn is the core's software authenticator. The browser + * vault is the real one (in-memory IndexedDB, a fake window). + */ + +import { secp256k1 } from '@noble/curves/secp256k1.js' +import { bytesToHex } from '@noble/hashes/utils.js' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { EvoSDK } from '@dashevo/evo-sdk' + +import { NETWORKS } from '../constants' +import { idbGet, resetMemoryStores } from '../idb' +import type { WasmKey } from '../sdk/facade' +import { UnconfirmedWriteError } from '../sdk/write' +import { + PasskeyError, + prfInput, + recipientFromPrf, + sealEntry, + userHandleFor, + type OnChainKey, + type PasskeyAssertion, +} from '../vendor/platform-auth/passkey-vault' +import { fakePasskeyAdapter, type FakePasskeyAdapter } from '../vendor/platform-auth/passkey-vault/__fixtures__/fake-passkey' +import { MemoryVaultPort } from '../vendor/platform-auth/passkey-vault/__fixtures__/memory-port' +import { decodeIdentifier } from './base58' +import { AuthController } from './controller' +import type { WalletKey } from './key-registration' +import { readMarkers, readPending } from './passkey-vault/markers' +import { FORGE_BUNDLE_CODEC, FORGE_BUNDLE_FORMAT, FORGE_VAULT_PROFILE } from './passkey-vault/profile' +import { credentialName, onChainKeyOf } from './passkey-vault/port' +import { vaultPasskeyFailure } from './passkey-vault/service' +import { listVaults, releaseUnlocked, storeEncryptionKey } from './vault' +import { encodeWif } from './wif' + +vi.mock('../sdk/write', async (orig) => { + const real = await orig() + return { + ...real, + findSigningKey: async (identity: { publicKeys: FakeKey[] }, wif: string) => { + const k = identity.publicKeys.find((x) => x.wif === wif && x.disabledAt === undefined) + return k ? { publicKey: {}, keyId: k.keyId, securityLevel: 2 } : null + }, + } +}) +vi.mock('../constants', async (orig) => { + const real = await orig() + const { DEPLOYMENTS, forgeV2Ids } = await import('../deployments') + const devnet = { ...real.NETWORKS.devnet, key: 'devnet-sakura', v2: forgeV2Ids(DEPLOYMENTS['devnet-sakura']) } + return { ...real, NETWORKS: { ...real.NETWORKS, devnet } } +}) +vi.mock('./group-trust', async (orig) => ({ ...(await orig()), assertGroupHolds: async () => ({ unknown: [], unchecked: [], notice: null }) })) +vi.mock('../view/retry', () => ({ retryWhileMissing: async (read: () => Promise) => read(), retryUntil: async (read: () => Promise) => read() })) +vi.mock('./wif', async (orig) => { + const real = await orig() + return { ...real, controlsKey: (k: FakeKey, wif: string) => k.wif === wif } +}) +vi.mock('./identity-file', async (orig) => { + const real = await orig() + return { ...real, masterMaterialFromFile: () => ({ identityId: '9r27eDsuXEqoMNymW1A2MKFrpBhzSkepVKwXrGzq9dUD', networkKey: 'devnet-sakura', masterWif: 'MASTER', mnemonic: null }) } +}) +const disabled = vi.hoisted(() => [] as number[][]) +vi.mock('./limited-key', async (orig) => { + const real = await orig() + return { + ...real, + // A renewal registers key 20 (recorded, not sent). + registerLimitedKey: async (_sdk: unknown, params: { persist?: (k: { keyId: number; wif: string }) => Promise }) => { + const key = { keyId: 20, wif: encodeWif(new Uint8Array(32).fill(20), 'devnet') } + await params.persist?.(key) + return { ...key, limits: { remaining: 5n, total: 5n, expiresAt: Date.now() + 1e9 } } + }, + disableIdentityKeys: async (_sdk: unknown, params: { keyIds: number[] }) => { + disabled.push(params.keyIds) + return true + }, + } +}) +// Adopting an encryption key checks it through the SDK's wasm keys: recorded here instead. +const adopted = vi.hoisted(() => [] as Uint8Array[]) +vi.mock('./encryption-key', async (orig) => ({ + ...(await orig()), + adoptEncryptionKey: async (_sdk: unknown, _n: unknown, _id: unknown, _core: unknown, secret: Uint8Array) => { + adopted.push(secret.slice()) + secret.fill(0) + return 9 + }, +})) + +interface FakeKey extends WasmKey { + wif: string +} + +const NET = 'devnet' as const +const ID = '9r27eDsuXEqoMNymW1A2MKFrpBhzSkepVKwXrGzq9dUD' +const OWNER = decodeIdentifier(ID) +const FORGE = NETWORKS[NET].v2! +const META = decodeIdentifier(FORGE.meta!) +const PRF_INPUT = prfInput(FORGE_VAULT_PROFILE, META) +const sk = (n: number) => new Uint8Array(32).fill(n) +const wifOf = (n: number): string => encodeWif(sk(n), NET) +const pubHex = (n: number) => bytesToHex(secp256k1.getPublicKey(sk(n), true)) +/** A browser-vault protection for the wallet sign-in (no Argon2: fast). */ +const PASSKEY = { passkey: { credentialId: new Uint8Array([1]), prfSalt: new Uint8Array(32), output: new Uint8Array(32).fill(9) } } +const WAIT = { timeout: 15_000, interval: 20 } + +function fakeWindow(): unknown { + const data = new Map() + const localStorage = { + get length() { + return data.size + }, + key: (i: number) => [...data.keys()][i] ?? null, + getItem: (k: string) => data.get(k) ?? null, + setItem: (k: string, v: string) => void data.set(k, String(v)), + removeItem: (k: string) => void data.delete(k), + clear: () => data.clear(), + } + const win: Record = { localStorage, location: { hostname: 'forge.dashhq.org', pathname: '/' }, addEventListener: () => undefined, isSecureContext: true } + win.top = win + win.self = win + return win +} + +/** A group-bound HIGH key with a budget and an expiry: a Forge limited key or a v2 wallet key. */ +function groupKey(keyId: number): FakeKey { + return { + keyId, + wif: wifOf(keyId), + purposeNumber: 0, + securityLevelNumber: 2, + keyTypeNumber: 0, + data: pubHex(keyId), + totalBudget: 5_000_000_000n, + expiresAt: BigInt(Date.now() + 90 * 24 * 3600 * 1000), + contractBounds: { toJSON: () => ({ $type: 'contractGroup', id: FORGE.group }) }, + validatePrivateKey: () => false, + } +} + +const grantOf = (k: FakeKey): WalletKey => ({ + keyId: k.keyId, + wif: k.wif, + scope: { core: true, collab: true, community: true, meta: true, unbounded: false }, + limits: { remaining: k.totalBudget!, total: k.totalBudget!, expiresAt: Number(k.expiresAt) }, +}) + +/** The core's in-memory port, reading the same keys as the fake chain (through the real mapping). */ +class ChainPort extends MemoryVaultPort { + /** The next create lands, but its answer is lost (an unconfirmed write). */ + loseNextAnswer = false + constructor(private readonly chain: () => FakeKey[]) { + super() + } + override async put(o: Parameters[0]): Promise { + await super.put(o) + if (this.loseNextAnswer) { + this.loseNextAnswer = false + throw new UnconfirmedWriteError('doc') + } + } + override async identityKeys(): Promise { + return this.chain().flatMap((k) => { + const mapped = onChainKeyOf(k, k.totalBudget) + return mapped ? [mapped] : [] + }) + } +} + +describe('passkeys that hold a key on Platform', () => { + let keys: FakeKey[] + let port: ChainPort + let adapter: FakePasskeyAdapter + /** Every PRF output the authenticator handed out (each must be wiped once used). */ + let handedOut: Uint8Array[] + const sdk = { + identities: { + fetch: async () => ({ balance: 10n ** 11n, publicKeys: keys, getPublicKeyById: () => ({}) }), + keysRemainingBudgets: async (_id: string, ids: number[]) => new Map(ids.map((i) => [i, keys.find((k) => k.keyId === i)?.totalBudget ?? null])), + nonce: async () => 1n, + }, + } as unknown as EvoSDK + const controllers: (() => void)[] = [] + const make = (): AuthController => { + const c = new AuthController(async () => sdk, NET, { + port: () => port, + adapter: () => ({ + ...adapter, + get: async (o) => { + const a: PasskeyAssertion = await adapter.get(o) + handedOut.push(a.prfOutput) + return a + }, + }), + location: () => ({ hostname: 'forge.dashhq.org', pathname: '/' }), + available: () => true, + }) + controllers.push(c.attach()) + return c + } + const signIn = async (k: FakeKey, c = make()): Promise => { + await c.adoptWalletKeys(ID, [grantOf(k)], PASSKEY, { origin: 'app-connect' }) + return c + } + /** A new device: nothing of the identity kept in this browser (the passkey syncs with its provider). */ + const newDevice = async (c: AuthController): Promise => { + await c.forget(ID) + releaseUnlocked() + return make() + } + /** An entry sealed to a passkey of the owner, as anyone with a live key of the owner could write it. */ + const plant = async (slotKeys: { keyId: number; n?: number; purpose?: number; level?: number }[]) => { + const created = await adapter.create({ rpId: 'forge.dashhq.org', rpName: 'x', userHandle: userHandleFor(OWNER, META), userName: 'x', prfInput: PRF_INPUT, exclude: [] }) + const recipientKey = recipientFromPrf(adapter.prfOf(created.credentialId, PRF_INPUT)).publicKey + const bundle = { + format: FORGE_BUNDLE_FORMAT, + keys: slotKeys.map((s) => ({ purpose: s.purpose ?? 0, securityLevel: s.level ?? 2, keyType: 0, keyId: s.keyId, privateKey: sk(s.n ?? s.keyId) })), + } + port.plant(OWNER, sealEntry(FORGE_VAULT_PROFILE, { contractId: META, ownerId: OWNER, credentialId: created.credentialId, recipientKey, bundle, codec: FORGE_BUNDLE_CODEC })) + adapter.choose(created.credentialId) + return created.credentialId + } + + beforeEach(() => { + resetMemoryStores() + vi.stubGlobal('window', fakeWindow()) + releaseUnlocked() + keys = [{ ...groupKey(1), keyId: 0, securityLevelNumber: 0, contractBounds: undefined, totalBudget: undefined, expiresAt: undefined }, groupKey(5)] + port = new ChainPort(() => keys) + adapter = fakePasskeyAdapter({ multiDevice: true }) + handedOut = [] + adopted.length = 0 + disabled.length = 0 + }) + afterEach(() => { + for (const off of controllers.splice(0)) off() + vi.unstubAllGlobals() + }) + + it('adds a passkey, then signs a new device in with it, kept under the same passkey', async () => { + const c = await signIn(keys[1]!) + expect(c.platformPasskeyProblem()).toBeNull() + await c.addPlatformPasskey() + expect(adapter.calls.create).toHaveLength(1) + // Made, then confirmed with a prompt limited to it. + expect(adapter.calls.get.map((g) => g.allow.length)).toEqual([1]) + expect(port.entries).toHaveLength(1) + const entry = port.entries[0]! + expect(entry.authKeyId).toBe(5) + expect(await readPending(NET, ID)).toBeNull() + expect(await readMarkers(NET, ID)).toEqual([expect.objectContaining({ credentialId: entry.credentialId, recipientKey: entry.recipientKey, keyIds: [5] })]) + const rows = await c.listPlatformPasskeys() + expect(rows).toEqual([expect.objectContaining({ id: credentialName(entry.credentialId), thisDevice: true, keyId: 5, keyState: 'live', current: true, needsUpdate: false, encryptionKey: false })]) + + const next = await newDevice(c) + expect(await readMarkers(NET, ID)).toEqual([]) + const session = await next.signInWithPasskey() + expect(session).toMatchObject({ identityId: ID, keyId: 5, storage: 'vault' }) + // One discoverable prompt. + expect(adapter.calls.get.at(-1)?.allow).toEqual([]) + // The browser vault is protected by that same passkey, its PRF input the salt. + const record = await idbGet<{ slots: { kind: string; credentialId: Uint8Array; prfSalt: Uint8Array }[] }>('vault', `vault:${NET}:${ID}`) + expect(record?.slots).toEqual([expect.objectContaining({ kind: 'passkey', credentialId: entry.credentialId, prfSalt: PRF_INPUT })]) + expect(next.writeAuth!.getSigningKeyWif(FORGE.core)).toBe(wifOf(5)) + // The PRF outputs were wiped once used. + expect(handedOut.length).toBeGreaterThan(0) + for (const out of handedOut) expect(out.every((b) => b === 0)).toBe(true) + // This device's now. + expect((await readMarkers(NET, ID)).map((m) => credentialName(m.credentialId))).toEqual([credentialName(entry.credentialId)]) + // Again, over the key it now keeps: unlock instead. + await expect(next.signInWithPasskey()).rejects.toMatchObject({ code: 'held', message: expect.stringMatching(/Unlock it instead/) }) + }, 30_000) + + it('keeps the encryption key in the passkey only when asked, and hands it to the browser vault', async () => { + keys.push({ ...groupKey(9), purposeNumber: 1, securityLevelNumber: 3, contractBounds: undefined, totalBudget: undefined, expiresAt: undefined }) + const c = await signIn(keys[1]!) + await storeEncryptionKey(NET, ID, 9, sk(9)) + await c.addPlatformPasskey({ includeEncryptionKey: true }) + expect((await readMarkers(NET, ID))[0]).toMatchObject({ keyIds: [5, 9], encryptionKeyId: 9 }) + const next = await newDevice(c) + await next.signInWithPasskey() + expect(adopted).toEqual([sk(9)]) + }, 30_000) + + it('refuses an encryption key this browser does not hold, before any prompt', async () => { + keys.push({ ...groupKey(9), purposeNumber: 1, securityLevelNumber: 3, contractBounds: undefined, totalBudget: undefined, expiresAt: undefined }) + const c = await signIn(keys[1]!) + await expect(c.addPlatformPasskey({ includeEncryptionKey: true })).rejects.toMatchObject({ code: 'ineligible' }) + expect(adapter.calls.create).toHaveLength(0) + }, 30_000) + + it('refuses a key with no limits before any prompt', async () => { + keys[1] = { ...keys[1]!, contractBounds: { toJSON: () => ({ $type: 'singleContract', id: FORGE.core }) }, totalBudget: undefined, expiresAt: undefined } + const c = make() + await c.adoptWalletKeys(ID, [{ ...grantOf(keys[1]), limits: null }], PASSKEY) + await expect(c.addPlatformPasskey()).rejects.toMatchObject({ code: 'ineligible', message: expect.stringMatching(/no spending limit/) }) + expect(adapter.calls.create).toHaveLength(0) + }, 30_000) + + it('keeps a passkey whose confirm was closed for "Check again", and drops one with no PRF', async () => { + const c = await signIn(keys[1]!) + let failGets = 1 + const real = adapter + adapter = { ...real, get: async (o) => (failGets-- > 0 ? Promise.reject(new PasskeyError('closed', 'cancelled')) : real.get(o)) } + await expect(c.addPlatformPasskey()).rejects.toMatchObject({ code: 'cancelled' }) + const pending = await c.pendingPlatformPasskey() + expect(pending).not.toBeNull() + expect(port.entries).toHaveLength(0) + await c.finishPlatformPasskey() + expect(port.entries.map((e) => credentialName(e.credentialId))).toEqual([pending!.id]) + expect(await c.pendingPlatformPasskey()).toBeNull() + + adapter = fakePasskeyAdapter({ prf: false }) + await expect(c.addPlatformPasskey()).rejects.toMatchObject({ code: 'no-prf' }) + expect(await c.pendingPlatformPasskey()).toBeNull() + expect(adapter.signalled).toHaveLength(1) + }, 30_000) + + it('stops at 10 passkeys', async () => { + const c = await signIn(keys[1]!) + for (let i = 0; i < 10; i++) await plant([{ keyId: 5 }]) + const before = adapter.calls.create.length + await expect(c.addPlatformPasskey()).rejects.toMatchObject({ code: 'too-many' }) + expect(adapter.calls.create).toHaveLength(before) + }, 30_000) + + it('says a browser-only passkey only unlocks the browser that made it', async () => { + const c = make() + await plant([{ keyId: 5 }]) + adapter.overrideNextHandle(new Uint8Array(32).fill(3)) + await expect(c.signInWithPasskey()).rejects.toMatchObject({ code: 'not-vault', message: expect.stringMatching(/only unlocks the browser that made it/) }) + expect(c.getState().error).toMatch(/only unlocks the browser that made it/) + expect(await listVaults(NET)).toEqual([]) + }) + + it('refuses a planted entry whose key is disabled, and stores nothing', async () => { + keys[1] = { ...keys[1]!, disabledAt: 1n } + const c = make() + await plant([{ keyId: 5 }]) + await expect(c.signInWithPasskey()).rejects.toMatchObject({ code: 'refused', message: expect.stringMatching(/was disabled/) }) + expect(await listVaults(NET)).toEqual([]) + for (const out of handedOut) expect(out.every((b) => b === 0)).toBe(true) + }) + + it('after a renewal re-seals only this device’s own entries, still sealed to its recipient key', async () => { + const c = await signIn(keys[1]!) + await c.addPlatformPasskey() + await c.addPlatformPasskey() + const [mine, replaced] = port.entries.map((e) => e.credentialId) + // Another device's passkey, and one of this device's whose entry was since replaced by one + // sealed to someone else's key (deleted and planted again under the same credential id). + const other = await plant([{ keyId: 5 }]) + port.entries.find((e) => credentialName(e.credentialId) === credentialName(replaced!))!.recipientKey = recipientFromPrf(sk(77)).publicKey + port.writes.length = 0 + + keys.push(groupKey(20)) + await c.importIdentity({ fileText: '{}' }, PASSKEY, undefined, { renew: true }) + await vi.waitFor(() => expect(port.writes).toEqual([{ op: 'replace', credentialId: mine }]), WAIT) + const byId = (id: Uint8Array) => port.entries.find((e) => credentialName(e.credentialId) === credentialName(id))! + expect(byId(mine!).authKeyId).toBe(20) + expect(byId(replaced!).authKeyId).toBe(5) + expect(byId(other).authKeyId).toBe(5) + expect((await readMarkers(NET, ID)).find((m) => credentialName(m.credentialId) === credentialName(mine!))?.keyIds).toEqual([20]) + // The others need an update: one prompt each, limited to that passkey. + expect(await c.resealPlatformPasskeys()).toEqual({ resealed: 0, needUpdate: 2 }) + const rows = await c.listPlatformPasskeys() + expect(rows.filter((r) => r.needsUpdate).map((r) => r.id).sort()).toEqual([credentialName(replaced!), credentialName(other)].sort()) + expect(await c.resealPlatformPasskeys({ id: credentialName(other) })).toEqual({ resealed: 1, needUpdate: 0 }) + expect(adapter.calls.get.at(-1)?.allow.map(credentialName)).toEqual([credentialName(other)]) + expect(byId(other).authKeyId).toBe(20) + // A passkey that does not give the entry's key is refused (the replaced one). + await expect(c.resealPlatformPasskeys({ id: credentialName(replaced!) })).rejects.toMatchObject({ code: 'refused' }) + }, 60_000) + + it('removes a passkey, telling the provider only about this device’s', async () => { + const c = await signIn(keys[1]!) + await c.addPlatformPasskey() + const mine = port.entries[0]!.credentialId + const other = await plant([{ keyId: 5 }]) + await c.removePlatformPasskey(credentialName(other)) + expect(adapter.signalled).toEqual([]) + await c.removePlatformPasskey(credentialName(mine)) + expect(adapter.signalled.map(credentialName)).toEqual([credentialName(mine)]) + expect(port.entries).toEqual([]) + expect(await readMarkers(NET, ID)).toEqual([]) + }, 30_000) + + it('can delete the passkeys holding a key before that key is disabled', async () => { + keys.push(groupKey(6)) + const c = await signIn(keys[1]!) + await plant([{ keyId: 6 }]) + await plant([{ keyId: 5 }]) + await c.disableIdentityKey({ fileText: '{}' }, 6, { removePasskeys: true }) + expect(disabled).toEqual([[6]]) + expect(port.entries.map((e) => e.authKeyId)).toEqual([5]) + }, 30_000) + + it('keeps a passkey whose confirm the browser reports closed (a real NotAllowedError) for "Check again"', async () => { + const c = await signIn(keys[1]!) + let failGets = 1 + const real = adapter + adapter = { ...real, get: async (o) => (failGets-- > 0 ? Promise.reject(vaultPasskeyFailure(new DOMException('The operation either timed out or was not allowed.', 'NotAllowedError'), 'get')) : real.get(o)) } + await expect(c.addPlatformPasskey()).rejects.toMatchObject({ code: 'cancelled', message: expect.not.stringMatching(/w3\.org|not allowed/) }) + expect(await c.pendingPlatformPasskey()).not.toBeNull() + expect(real.signalled).toEqual([]) + // A second add waits for this one. + await expect(c.addPlatformPasskey()).rejects.toMatchObject({ code: 'pending' }) + }, 30_000) + + it('deletes an entry whose answer was lost before discarding its passkey, and never orphans one', async () => { + const c = await signIn(keys[1]!) + port.loseNextAnswer = true + await expect(c.addPlatformPasskey()).rejects.toMatchObject({ code: 'pending' }) + expect(port.entries).toHaveLength(1) + expect(await c.pendingPlatformPasskey()).not.toBeNull() + await c.abandonPlatformPasskey() + expect(port.entries).toEqual([]) + expect(adapter.signalled).toHaveLength(1) + expect(await c.pendingPlatformPasskey()).toBeNull() + + // "Check again" over an entry that did land: re-sealed and marked, nothing dropped. + port.loseNextAnswer = true + await expect(c.addPlatformPasskey()).rejects.toMatchObject({ code: 'pending' }) + await c.finishPlatformPasskey() + expect(port.entries).toHaveLength(1) + expect(await readMarkers(NET, ID)).toHaveLength(1) + expect(adapter.signalled).toHaveLength(1) + }, 30_000) + + it('refuses an entry replaced under a passkey’s credential id (sealed to another key)', async () => { + const c = await signIn(keys[1]!) + await c.addPlatformPasskey() + port.entries[0]!.recipientKey = recipientFromPrf(sk(77)).publicKey + const next = await newDevice(c) + await expect(next.signInWithPasskey()).rejects.toMatchObject({ code: 'refused' }) + expect(await listVaults(NET)).toEqual([]) + }, 30_000) + + it('writes no marker back after forgetting, even with a re-seal in flight', async () => { + const c = await signIn(keys[1]!) + await c.addPlatformPasskey() + keys.push(groupKey(20)) + await c.importIdentity({ fileText: '{}' }, PASSKEY, undefined, { renew: true }) + await c.forget(ID) + expect(await readMarkers(NET, ID)).toEqual([]) + }, 30_000) + + it('still disables a key when the passkeys that hold it cannot be removed first, and says so', async () => { + keys.push(groupKey(6)) + const c = await signIn(keys[1]!) + await plant([{ keyId: 6 }]) + // This browser's key can no longer sign the deletes. + port.remove = async () => { + throw new Error('the key has no budget left') + } + await c.disableIdentityKey({ fileText: '{}' }, 6, { removePasskeys: true }) + expect(disabled).toEqual([[6]]) + expect(c.getState().notice).toMatch(/The key was disabled, but the passkeys that hold it could not be removed: the key has no budget left/) + }, 30_000) + + it('does not add a changed encryption key to an entry silently: it waits for that passkey’s update', async () => { + keys.push({ ...groupKey(9), purposeNumber: 1, securityLevelNumber: 3, contractBounds: undefined, totalBudget: undefined, expiresAt: undefined }) + const c = await signIn(keys[1]!) + await storeEncryptionKey(NET, ID, 9, sk(9)) + await c.addPlatformPasskey({ includeEncryptionKey: true }) + expect((await readMarkers(NET, ID))[0]).toMatchObject({ encryptionKeyId: 9 }) + // A newer encryption key on the identity, held here too. + keys.push({ ...groupKey(10), purposeNumber: 1, securityLevelNumber: 3, contractBounds: undefined, totalBudget: undefined, expiresAt: undefined }) + await storeEncryptionKey(NET, ID, 10, sk(10)) + port.writes.length = 0 + expect(await c.resealPlatformPasskeys()).toEqual({ resealed: 0, needUpdate: 1 }) + expect(port.writes).toEqual([]) + // Updating that passkey on purpose, with the choice made again, does put it in. + const [row] = await c.listPlatformPasskeys() + expect(await c.resealPlatformPasskeys({ id: row!.id, includeEncryptionKey: true })).toEqual({ resealed: 1, needUpdate: 0 }) + expect((await readMarkers(NET, ID))[0]).toMatchObject({ encryptionKeyId: 10 }) + }, 30_000) + + it('renewing a passkey’s key in a wallet keeps the old key live, held only: no passkey seals it again', async () => { + const c = await signIn(keys[1]!) + await c.addPlatformPasskey() + const next = await newDevice(c) + await next.signInWithPasskey() + // The wallet's new key; the old one (key 5) is another browser's grant, so it is not disabled. + keys.push(groupKey(6)) + await next.adoptWalletKeys(ID, [grantOf(keys[2]!)], PASSKEY, { origin: 'app-connect' }) + expect(next.writeAuth!.getSigningKeyWif(FORGE.core)).toBe(wifOf(6)) + // The old key is held beside the new one, never to sign and never sealed into a passkey. + await next.addPlatformPasskey() + const sealed = (await readMarkers(NET, ID)).flatMap((m) => m.keyIds) + expect(sealed).not.toContain(5) + expect(sealed).toContain(6) + }, 60_000) + + it('keeps the key with the origin "passkey": renewable in a wallet or with the identity file', async () => { + const c = await signIn(keys[1]!) + await c.addPlatformPasskey() + const next = await newDevice(c) + const session = await next.signInWithPasskey() + // Who made the key is unknown on this device (a wallet, or the master key through dg or the file). + expect(session.origin).toBe('passkey') + expect((await listVaults(NET)).find((v) => v.identityId === ID)).toMatchObject({ keyId: 5 }) + // Wallet renewal is open to it, like a wallet-granted key's. + expect(await next.walletRenewalRequest()).toMatchObject({ identityHint: ID, replacesKeyId: 5 }) + // A master-key renewal makes it an ordinary Forge key again. + keys.push(groupKey(20)) + await next.importIdentity({ fileText: '{}' }, PASSKEY, undefined, { renew: true }) + expect(next.getState().session?.origin).toBeUndefined() + }, 30_000) + + it('stays hidden until the deployed forge-meta has the vault entry type', async () => { + let deployed = false + const reads: string[] = [] + const make1 = (): AuthController => + new AuthController(async () => sdk, NET, { + port: () => port, + adapter: () => adapter, + location: () => ({ hostname: 'forge.dashhq.org', pathname: '/' }), + available: () => true, + deployed: async (_sdk, meta) => { + reads.push(meta) + return deployed + }, + }) + const c = make1() + // Before the read the page and network allow it; the read says the type is not there yet. + expect(c.platformPasskeyProblem()).toBeNull() + expect(await c.checkPlatformPasskeys()).toMatch(/aren't available on this network yet/) + expect(c.platformPasskeyProblem()).toMatch(/aren't available on this network yet/) + expect(reads).toEqual([FORGE.meta]) + await expect(c.signInWithPasskey()).rejects.toMatchObject({ code: 'unavailable' }) + expect(adapter.calls.get).toHaveLength(0) + // Once forge-meta is updated, a fresh page load sees it. + deployed = true + const later = make1() + expect(await later.checkPlatformPasskeys()).toBeNull() + expect(later.platformPasskeyProblem()).toBeNull() + // An answer of "there" is remembered; no second read. + expect(await later.checkPlatformPasskeys()).toBeNull() + expect(reads).toHaveLength(2) + }) + + it('treats a failed read as a problem, and asks again next time', async () => { + let fail = true + const c = new AuthController(async () => sdk, NET, { + port: () => port, + adapter: () => adapter, + location: () => ({ hostname: 'forge.dashhq.org', pathname: '/' }), + available: () => true, + deployed: async () => { + if (fail) throw new Error('offline') + return true + }, + }) + expect(await c.checkPlatformPasskeys()).toMatch(/Couldn't check whether passkeys/) + // Nothing was decided: the controls stay hidden, but the vault is not marked as missing. + expect(c.platformPasskeyProblem()).toBeNull() + fail = false + expect(await c.checkPlatformPasskeys()).toBeNull() + }) + + it('leaves a wallet grant with no spending limit out of the passkey, and says how many', async () => { + // A v1 wallet's one-contract grant: no budget, no expiry (its entry ciphertext would be public for good). + const v1: FakeKey = { ...groupKey(6), contractBounds: { toJSON: () => ({ $type: 'singleContract', id: FORGE.collab }) }, totalBudget: undefined, expiresAt: undefined } + keys.push(v1) + const c = await signIn(keys[1]!) + await c.addWalletGrant(ID, { keyId: 6, wif: v1.wif, scope: { core: false, collab: true, community: false, meta: false, unbounded: false }, limits: null }, FORGE.collab) + expect(await c.platformPasskeyLeftOut()).toBe(1) + await c.addPlatformPasskey() + expect(port.entries).toHaveLength(1) + expect((await readMarkers(NET, ID))[0]?.keyIds).toEqual([5]) + // Nothing is left out for a session that holds no such key. + const plain = await newDevice(c) + await plain.adoptWalletKeys(ID, [grantOf(keys[1]!)], PASSKEY, { origin: 'app-connect' }) + expect(await plain.platformPasskeyLeftOut()).toBe(0) + }, 30_000) + + it('is not offered on another host', () => { + const c = new AuthController(async () => sdk, NET, { port: () => port, adapter: () => adapter, location: () => ({ hostname: 'evil.dashhq.org', pathname: '/' }), available: () => true }) + expect(c.platformPasskeyProblem()).toMatch(/Forge’s own address/) + return expect(c.signInWithPasskey()).rejects.toMatchObject({ code: 'unavailable' }) + }) +}) diff --git a/forge-web/lib/auth/passkey-vault.live.test.ts b/forge-web/lib/auth/passkey-vault.live.test.ts new file mode 100644 index 000000000..e23caad23 --- /dev/null +++ b/forge-web/lib/auth/passkey-vault.live.test.ts @@ -0,0 +1,130 @@ +/** + * The passkey vault, live on a devnet with a software authenticator (the vendored core's fake + * adapter stands in for Face ID or a phone; everything else is Forge's own code: the Platform port + * with proved reads, the writes through the WriteEngine, the chain check on every open, the vault + * session). SKIPPED by default (real spend: it registers and disables a key, and writes, replaces + * and deletes passkey entries): + * + * FORGE_LIVE=1 NEXT_PUBLIC_NETWORK=devnet NEXT_PUBLIC_DEVNET_NAME=sakura \ + * pnpm exec vitest run lib/auth/passkey-vault.live.test.ts + * + * Needs the RELAY test identity of the devnet (`~/.config/dash-forge/test-identities/devnet-sakura/ + * RELAY.identity.json`), or the identity file named by FORGE_WALLET_IDENTITY_FILE, with about + * 0.05 DASH of credits. It also needs `vaultEntry` in the deployed forge-meta + * (`deploy-v2.mjs --update meta`); until that lands the test says so and ends before it spends. + * + * 1. a limited key is registered for a fresh browser with the identity file (group-bound, 0.05 DASH); + * 2. add a passkey, then a second: the group-bound key writes `vaultEntry` (whole-contract group + * membership covers a type added later: the assumption the update's rehearsal must confirm); + * 3. a new device (empty browser storage) signs in with the passkey alone: same key, free reads; + * 4. re-seal one entry with its passkey; remove both entries (refunded deposits); + * 5. cleanup: the master key disables the key this run registered. + * + * It prints what each step cost, for docs/economics.md and lib/sdk/cost.ts (`FEE …` lines). + */ + +import { existsSync, readFileSync } from 'node:fs' +import { homedir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' + +import { DEFAULT_NETWORK, NETWORKS } from '../constants' +import { resetMemoryStores } from '../idb' +import { evoSdkService } from '../sdk' +import { readIdentityBalance } from '../sdk/write' +import { fakePasskeyAdapter } from '../vendor/platform-auth/passkey-vault/__fixtures__/fake-passkey' +import { AuthController } from './controller' +import { vaultEntryDeployed } from './passkey-vault/deployed' + +const DEVNET = NETWORKS.devnet.devnetName ?? '' +const FILE = process.env['FORGE_WALLET_IDENTITY_FILE'] ?? join(homedir(), '.config/dash-forge/test-identities', `devnet-${DEVNET}`, 'RELAY.identity.json') +const LIVE = process.env['FORGE_LIVE'] === '1' && DEFAULT_NETWORK === 'devnet' && existsSync(FILE) + +/** Credits to DASH, for the printed lines. */ +const dash = (credits: bigint): string => (Number(credits) / 1e11).toFixed(6) + +describe.skipIf(!LIVE)('live passkey vault (software authenticator, forge-meta vaultEntry)', () => { + it( + 'add, add, sign in on a new device, re-seal, remove, cleanup', + async () => { + await evoSdkService.initialize({ network: 'devnet', contractIds: [], timeoutMs: 30000 }) + const sdk = evoSdkService.getSdk() + const forge = NETWORKS.devnet.v2! + const network = 'devnet' as const + if (forge.meta === undefined || !(await vaultEntryDeployed(sdk, forge.meta))) { + // eslint-disable-next-line no-console + console.log('SKIPPED: forge-meta on this devnet has no vaultEntry yet (deploy-v2.mjs --update meta is pending). Nothing was spent.') + return + } + + const fileText = readFileSync(FILE, 'utf8') + const adapter = fakePasskeyAdapter({ multiDevice: true }) + const deps = { + adapter: () => adapter, + location: () => ({ hostname: 'localhost', pathname: '/' }), + available: () => true, + } + const make = (): AuthController => new AuthController(async () => sdk, network, deps) + const protection = { passphrase: 'live passkey vault passphrase' } + let identityId = '' + + /** What `step` cost the identity, once the balance settles. */ + const measure = async (label: string, step: () => Promise): Promise => { + const before = await readIdentityBalance(sdk, identityId) + await step() + let after = before + for (let i = 0; i < 15; i += 1) { + await new Promise((resolve) => setTimeout(resolve, 2000)) + const now = await readIdentityBalance(sdk, identityId) + if (now === after && now !== before) break + after = now + } + // eslint-disable-next-line no-console + console.log(`FEE ${label}: ${before - after} credits (${dash(before - after)} DASH)`) + return before - after + } + + resetMemoryStores() + const first = make() + // Whoever holds the key at the end revokes it (the new device, once it signed in). + let owner = first + try { + // 1. A fresh browser's limited key, registered with the identity file. + const session = await first.importIdentity({ fileText }, protection) + identityId = session.identityId + expect(session.storage).toBe('vault') + expect(first.platformPasskeyProblem()).toBeNull() + + // 2. Two passkeys: the first builds the owner's subtree, the second is the steady state. + const firstFee = await measure('first entry', () => first.addPlatformPasskey()) + const secondFee = await measure('later entry', () => first.addPlatformPasskey()) + expect(firstFee).toBeGreaterThan(0n) + expect(secondFee).toBeGreaterThan(0n) + const rows = await first.listPlatformPasskeys() + expect(rows).toHaveLength(2) + expect(rows.every((r) => r.thisDevice && r.current && !r.needsUpdate && r.keyState === 'live')).toBe(true) + + // 3. A new device: nothing of the identity in this browser, the passkey alone. + resetMemoryStores() + const device = make() + owner = device + const free = await measure('sign-in (reads only)', async () => { + const next = await device.signInWithPasskey() + expect(next).toMatchObject({ identityId, keyId: session.keyId, storage: 'vault', origin: 'passkey' }) + }) + expect(free).toBe(0n) + + // 4. Re-seal one entry (its passkey confirms it), then remove both (deposits come back). + const [one, two] = await device.listPlatformPasskeys() + await measure('re-seal', async () => expect(await device.resealPlatformPasskeys({ id: one!.id })).toEqual({ resealed: 1, needUpdate: 0 })) + await measure('delete (refund is negative)', () => device.removePlatformPasskey(one!.id)) + await measure('delete (the last one)', () => device.removePlatformPasskey(two!.id)) + expect(await device.listPlatformPasskeys()).toEqual([]) + } finally { + // 5. Leave the identity as it was: the master key disables the key this run registered. + if (identityId !== '') await owner.revokeStored(identityId, { fileText }, { removePasskeys: true }).catch(() => undefined) + } + }, + 20 * 60_000, + ) +}) diff --git a/forge-web/lib/auth/passkey-vault/deployed.test.ts b/forge-web/lib/auth/passkey-vault/deployed.test.ts new file mode 100644 index 000000000..829c384d3 --- /dev/null +++ b/forge-web/lib/auth/passkey-vault/deployed.test.ts @@ -0,0 +1,52 @@ +/** + * The passkey vault is inert until forge-meta declares `vaultEntry`: the check reads the contract + * Platform serves, tells "no vault yet" from "could not read", and never takes a stale snapshot's + * word for it. + */ + +import type { EvoSDK } from '@dashevo/evo-sdk' +import { describe, expect, it, vi } from 'vitest' + +import { vaultEntryDeployed } from './deployed' +import { PASSKEYS_NOT_DEPLOYED } from './policy' + +const sdkWith = (fetch: (id: string) => Promise): EvoSDK => ({ contracts: { fetch } }) as unknown as EvoSDK + +describe('whether forge-meta has the passkey vault', () => { + it('is deployed when the contract declares vaultEntry (wasm contract or its JSON)', async () => { + expect(await vaultEntryDeployed(sdkWith(async () => ({ schemas: { profile: {}, vaultEntry: {} } })), 'META')).toBe(true) + expect(await vaultEntryDeployed(sdkWith(async () => ({ toJSON: () => ({ documentSchemas: { vaultEntry: {} } }) })), 'META')).toBe(true) + }) + + it('is not deployed when the contract lacks the type, is empty, or is not there', async () => { + expect(await vaultEntryDeployed(sdkWith(async () => ({ schemas: { profile: {}, follow: {} } })), 'META')).toBe(false) + expect(await vaultEntryDeployed(sdkWith(async () => ({ toJSON: () => ({}) })), 'META')).toBe(false) + expect(await vaultEntryDeployed(sdkWith(async () => undefined), 'META')).toBe(false) + expect( + await vaultEntryDeployed( + sdkWith(async () => { + throw new Error('contract not found error: contract not found when querying from value with contract info') + }), + 'META', + ), + ).toBe(false) + }) + + it('asks for forge-meta itself, and fails on a read it could not make', async () => { + const fetch = vi.fn(async () => ({ schemas: {} })) + await vaultEntryDeployed(sdkWith(fetch), 'META-ID') + expect(fetch).toHaveBeenCalledWith('META-ID') + await expect( + vaultEntryDeployed( + sdkWith(async () => { + throw new Error('request timed out') + }), + 'META', + ), + ).rejects.toThrow(/timed out/) + }) + + it('says why in a sentence', () => { + expect(PASSKEYS_NOT_DEPLOYED).toMatch(/aren't available on this network yet/) + }) +}) diff --git a/forge-web/lib/auth/passkey-vault/deployed.ts b/forge-web/lib/auth/passkey-vault/deployed.ts new file mode 100644 index 000000000..fefef4b7f --- /dev/null +++ b/forge-web/lib/auth/passkey-vault/deployed.ts @@ -0,0 +1,37 @@ +/** + * Whether the forge-meta Platform serves has the passkey vault's `vaultEntry` type. The type is an + * additive update of forge-meta (`deploy-v2.mjs --update meta`): until it lands, a network has the + * contract but no vault, and every passkey control stays hidden rather than fail on a read. + * + * The answer comes from a proved contract fetch, which bypasses the bundled snapshots (the + * snapshot of a network moves with the update, but a stale build must not offer what Platform + * does not have). A missing contract (`./sdk/contract-missing`) is "not deployed"; a failed read + * is neither answer and throws. + */ + +import type { EvoSDK } from '@dashevo/evo-sdk' + +import { authSdk } from '../../sdk/facade' +import { isContractMissingError } from '../../sdk/contract-missing' + +/** The document type the vault's entries are. */ +const VAULT_ENTRY_TYPE = 'vaultEntry' + +/** The document types a fetched contract declares (the wasm contract's `schemas`, else its JSON). */ +function documentTypesOf(contract: unknown): readonly string[] { + const c = contract as { schemas?: unknown; toJSON?: () => { documentSchemas?: unknown } } + const schemas = c.schemas ?? c.toJSON?.().documentSchemas + return typeof schemas === 'object' && schemas !== null ? Object.keys(schemas) : [] +} + +/** Whether forge-meta (`metaId`, base58) declares `vaultEntry`. Throws when Platform cannot be read. */ +export async function vaultEntryDeployed(sdk: EvoSDK, metaId: string): Promise { + let contract: unknown + try { + contract = await authSdk(sdk).contracts.fetch(metaId) + } catch (e) { + if (isContractMissingError(e)) return false + throw e + } + return contract !== undefined && documentTypesOf(contract).includes(VAULT_ENTRY_TYPE) +} diff --git a/forge-web/lib/auth/passkey-vault/markers.test.ts b/forge-web/lib/auth/passkey-vault/markers.test.ts new file mode 100644 index 000000000..7106c8a6e --- /dev/null +++ b/forge-web/lib/auth/passkey-vault/markers.test.ts @@ -0,0 +1,51 @@ +/** This device's passkey records: one marker per credential, a pending enrolment, both forgotten together. */ + +import { afterEach, describe, expect, it } from 'vitest' + +import { idbPut, resetMemoryStores } from '../../idb' +import { clearPending, dropMarker, forgetPasskeyRecords, markerFor, putMarker, readMarkers, readPending, writePending, type PasskeyMarker } from './markers' + +const ID = 'JCuebezAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +const marker = (n: number, keyIds = [5]): PasskeyMarker => ({ credentialId: new Uint8Array(16).fill(n), recipientKey: new Uint8Array(32).fill(n), keyIds, addedAt: n }) + +afterEach(() => resetMemoryStores()) + +describe("this device's passkey markers", () => { + it('keep one marker per credential, per network and identity', async () => { + await putMarker('devnet', ID, marker(1)) + await putMarker('devnet', ID, marker(2)) + await putMarker('devnet', ID, marker(1, [6, 7])) + const got = await readMarkers('devnet', ID) + expect(got.map((m) => [m.addedAt, m.keyIds])).toEqual([ + [2, [5]], + [1, [6, 7]], + ]) + expect(markerFor(got, new Uint8Array(16).fill(2))?.addedAt).toBe(2) + expect(await readMarkers('testnet', ID)).toEqual([]) + await dropMarker('devnet', ID, new Uint8Array(16).fill(2)) + expect((await readMarkers('devnet', ID)).map((m) => m.addedAt)).toEqual([1]) + }) + + it('ignore a malformed record: it trusts nothing', async () => { + await idbPut('vault', `pv-own:devnet:${ID}`, [{ credentialId: 'x', recipientKey: new Uint8Array(31), keyIds: [], addedAt: 1 }, marker(3)]) + expect((await readMarkers('devnet', ID)).map((m) => m.addedAt)).toEqual([3]) + }) + + it('keep a pending enrolment as public ids only, cleared by its own credential', async () => { + const pending = { ownerId: new Uint8Array(32).fill(7), credentialId: new Uint8Array(20).fill(8), createPrf: new Uint8Array(32).fill(9) } + await writePending('devnet', ID, pending) + expect(await readPending('devnet', ID)).toEqual({ ownerId: pending.ownerId, credentialId: pending.credentialId }) + await clearPending('devnet', ID, new Uint8Array(20).fill(1)) + expect(await readPending('devnet', ID)).not.toBeNull() + await clearPending('devnet', ID, pending.credentialId) + expect(await readPending('devnet', ID)).toBeNull() + }) + + it('are all forgotten with the identity', async () => { + await putMarker('devnet', ID, marker(1)) + await writePending('devnet', ID, { ownerId: new Uint8Array(32), credentialId: new Uint8Array(16) }) + await forgetPasskeyRecords('devnet', ID) + expect(await readMarkers('devnet', ID)).toEqual([]) + expect(await readPending('devnet', ID)).toBeNull() + }) +}) diff --git a/forge-web/lib/auth/passkey-vault/markers.ts b/forge-web/lib/auth/passkey-vault/markers.ts new file mode 100644 index 000000000..40fde60be --- /dev/null +++ b/forge-web/lib/auth/passkey-vault/markers.ts @@ -0,0 +1,126 @@ +/** + * What this device records about its own vault passkeys, in IndexedDB beside the browser vault + * (public facts only, no key material): + * + * - `pv-own::`: a trust marker per passkey this device made or signed in with, + * `{credentialId, recipientKey, keyIds, encryptionKeyId?, addedAt}`. Its recipient key came from + * the passkey's own PRF output in this browser, never from a read of Platform, so it is the one + * thing a re-seal without a prompt may trust (`PasskeyVault.trustMarker`): an entry anyone with a + * live key could plant carries the attacker's recipient key, which no marker here names. + * - `pv-pending::`: an enrolment made but not yet stored and seen on Platform, + * as `{ownerId, credentialId}` only, so "Check again" works after a reload. + * + * Forgetting the identity on this device deletes both ({@link forgetPasskeyRecords}). + */ + +import type { Network } from '../../constants' +import { idbDelete, idbGet, idbUpdate } from '../../idb' +import { bytesEqual } from '../../vendor/platform-auth/passkey-vault' + +/** This device's record of one of its passkeys. */ +export interface PasskeyMarker { + readonly credentialId: Uint8Array + /** The HPKE recipient key the passkey's PRF output derived here. */ + readonly recipientKey: Uint8Array + /** The key ids last sealed to it, in slot order (slot 0 first). */ + readonly keyIds: readonly number[] + /** The encryption key sealed with them, when the user chose to include it. */ + readonly encryptionKeyId?: number + /** When this device made it or first signed in with it (ms). */ + readonly addedAt: number +} + +/** A passkey made by an enrolment that has not finished (public ids only). */ +export interface PendingPasskey { + readonly ownerId: Uint8Array + readonly credentialId: Uint8Array +} + +const markersKey = (network: Network, identityId: string): string => `pv-own:${network}:${identityId}` +const pendingKey = (network: Network, identityId: string): string => `pv-pending:${network}:${identityId}` + +/** A Uint8Array from any realm (a structured clone may come back from another one). */ +const isBytes = (v: unknown, length?: number): v is Uint8Array => + Object.prototype.toString.call(v) === '[object Uint8Array]' && (length === undefined || (v as Uint8Array).length === length) +const isKeyId = (v: unknown): v is number => typeof v === 'number' && Number.isInteger(v) && v >= 0 + +function isMarker(v: unknown): v is PasskeyMarker { + const m = v as Partial | null + return ( + typeof m === 'object' && + m !== null && + isBytes(m.credentialId) && + isBytes(m.recipientKey, 32) && + Array.isArray(m.keyIds) && + m.keyIds.every(isKeyId) && + (m.encryptionKeyId === undefined || isKeyId(m.encryptionKeyId)) && + typeof m.addedAt === 'number' + ) +} + +/** The well-formed markers of a stored value (a malformed one is ignored: it trusts nothing). */ +const validMarkers = (v: unknown): PasskeyMarker[] => (Array.isArray(v) ? v.filter(isMarker) : []) + +/** The markers of a stored value but the one of `credentialId`. */ +const withoutCredential = (v: unknown, credentialId: Uint8Array): PasskeyMarker[] => validMarkers(v).filter((m) => !bytesEqual(m.credentialId, credentialId)) + +/** This device's markers for `identityId`. */ +export async function readMarkers(network: Network, identityId: string): Promise { + const v = await idbGet('vault', markersKey(network, identityId)) + return validMarkers(v).map((m) => ({ ...m, credentialId: new Uint8Array(m.credentialId), recipientKey: new Uint8Array(m.recipientKey) })) +} + +/** The marker of `credentialId`, or null. */ +export function markerFor(markers: readonly PasskeyMarker[], credentialId: Uint8Array): PasskeyMarker | null { + return markers.find((m) => bytesEqual(m.credentialId, credentialId)) ?? null +} + +/** + * The marker that makes `entry` this device's: the one of its credential, recording its recipient + * key. An entry replaced since (sealed to another key under the same credential id) has none. + */ +export function ownMarkerFor(markers: readonly PasskeyMarker[], entry: { readonly credentialId: Uint8Array; readonly recipientKey: Uint8Array }): PasskeyMarker | null { + const m = markerFor(markers, entry.credentialId) + return m !== null && bytesEqual(m.recipientKey, entry.recipientKey) ? m : null +} + +/** Record (or replace) the marker of `marker.credentialId`, in one transaction with the others. */ +export async function putMarker(network: Network, identityId: string, marker: PasskeyMarker): Promise { + const at = markersKey(network, identityId) + await idbUpdate('vault', at, (current) => [[at, [...withoutCredential(current, marker.credentialId), marker]]]) +} + +/** Forget the marker of `credentialId` (its entry was removed). */ +export async function dropMarker(network: Network, identityId: string, credentialId: Uint8Array): Promise { + const at = markersKey(network, identityId) + await idbUpdate('vault', at, (current) => { + const kept = withoutCredential(current, credentialId) + return [[at, kept.length > 0 ? kept : undefined]] + }) +} + +/** The enrolment of `identityId` that has not finished, or null. */ +export async function readPending(network: Network, identityId: string): Promise { + const v = await idbGet>('vault', pendingKey(network, identityId)) + return v && isBytes(v.ownerId, 32) && isBytes(v.credentialId) ? { ownerId: new Uint8Array(v.ownerId), credentialId: new Uint8Array(v.credentialId) } : null +} + +/** Record an enrolment until it is stored and seen (one per identity: a newer one replaces it). */ +export async function writePending(network: Network, identityId: string, pending: PendingPasskey): Promise { + const at = pendingKey(network, identityId) + await idbUpdate('vault', at, () => [[at, { ownerId: pending.ownerId.slice(), credentialId: pending.credentialId.slice() }]]) +} + +/** Drop the pending enrolment of `credentialId` (any, when omitted). */ +export async function clearPending(network: Network, identityId: string, credentialId?: Uint8Array): Promise { + const at = pendingKey(network, identityId) + await idbUpdate>('vault', at, (current) => + credentialId === undefined || (isBytes(current?.credentialId) && bytesEqual(current.credentialId, credentialId)) ? [[at, undefined]] : [], + ) +} + +/** Delete every passkey record this device keeps for `identityId` (forgetting it here). */ +export async function forgetPasskeyRecords(network: Network, identityId: string): Promise { + await idbDelete('vault', markersKey(network, identityId)) + await idbDelete('vault', pendingKey(network, identityId)) +} diff --git a/forge-web/lib/auth/passkey-vault/offer.test.ts b/forge-web/lib/auth/passkey-vault/offer.test.ts new file mode 100644 index 000000000..93dbaba8a --- /dev/null +++ b/forge-web/lib/auth/passkey-vault/offer.test.ts @@ -0,0 +1,58 @@ +// @vitest-environment jsdom +/** The one-time passkey offer never nags: twice at most, never after "Not now", and never without a record. */ + +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { dismissOffer, MAX_OFFERS, noteOffered, shouldOffer } from './offer' + +const ID = '9r27eDsuXEqoMNymW1A2MKFrpBhzSkepVKwXrGzq9dUD' +const OTHER = 'BTJPjCLCnRaJQkqakpcdLYFsaHgFf5XSEBNxFCyYBteH' + +beforeEach(() => { + localStorage.clear() + vi.restoreAllMocks() +}) + +describe('the passkey offer', () => { + it('is made to a new identity, at most twice, and then never again', () => { + expect(shouldOffer('devnet', ID)).toBe(true) + for (let i = 0; i < MAX_OFFERS; i++) { + expect(shouldOffer('devnet', ID)).toBe(true) + expect(noteOffered('devnet', ID)).toBe(true) + } + expect(shouldOffer('devnet', ID)).toBe(false) + }) + + it('stops for good after "Not now", for that identity and network only', () => { + noteOffered('devnet', ID) + dismissOffer('devnet', ID) + expect(shouldOffer('devnet', ID)).toBe(false) + expect(shouldOffer('devnet', OTHER)).toBe(true) + expect(shouldOffer('testnet', ID)).toBe(true) + // Dismissing before it was ever shown also sticks (a passkey already exists here). + dismissOffer('devnet', OTHER) + expect(shouldOffer('devnet', OTHER)).toBe(false) + }) + + it('is never made when the browser will not keep the record (it could repeat forever)', () => { + vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { + throw new Error('blocked') + }) + expect(shouldOffer('devnet', ID)).toBe(false) + expect(noteOffered('devnet', ID)).toBe(false) + }) + + it('is not made when the record can be read but not written', () => { + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw new Error('quota') + }) + expect(noteOffered('devnet', ID)).toBe(false) + }) + + it('ignores a corrupt record', () => { + localStorage.setItem(`forge.passkey-offer:devnet:${ID}`, '{"shown":"many","done":1}') + expect(shouldOffer('devnet', ID)).toBe(true) + localStorage.setItem(`forge.passkey-offer:devnet:${ID}`, 'not json') + expect(shouldOffer('devnet', ID)).toBe(false) + }) +}) diff --git a/forge-web/lib/auth/passkey-vault/offer.ts b/forge-web/lib/auth/passkey-vault/offer.ts new file mode 100644 index 000000000..9aa3e51f7 --- /dev/null +++ b/forge-web/lib/auth/passkey-vault/offer.ts @@ -0,0 +1,57 @@ +/** + * The one-time offer to add a passkey after signing in (`components/passkey-offer.tsx`): it must + * never nag. Per identity on this browser it shows at most {@link MAX_OFFERS} times, once per page + * load, and never again after "Not now" or once a passkey exists (added here or signed in with). + * The record is localStorage, per network and identity; a browser that blocks it shows nothing. + */ + +import type { Network } from '../../constants' + +/** How many page loads may show the offer, whatever the user does with it. */ +export const MAX_OFFERS = 2 + +interface OfferRecord { + readonly shown: number + readonly done: boolean +} + +const key = (network: Network, identityId: string): string => `forge.passkey-offer:${network}:${identityId}` + +function read(network: Network, identityId: string): OfferRecord | null { + try { + const v: unknown = JSON.parse(window.localStorage.getItem(key(network, identityId)) ?? 'null') + if (typeof v !== 'object' || v === null) return { shown: 0, done: false } + const r = v as Partial + return { shown: typeof r.shown === 'number' && r.shown >= 0 ? r.shown : 0, done: r.done === true } + } catch { + // Storage blocked or unreadable: no record, so no way to promise it will not repeat. + return null + } +} + +function write(network: Network, identityId: string, record: OfferRecord): boolean { + try { + window.localStorage.setItem(key(network, identityId), JSON.stringify(record)) + return true + } catch { + return false + } +} + +/** Whether to show the offer now: not dismissed, not shown {@link MAX_OFFERS} times, and storage works. */ +export function shouldOffer(network: Network, identityId: string): boolean { + const r = read(network, identityId) + return r !== null && !r.done && r.shown < MAX_OFFERS +} + +/** Count a showing. Returns false when it could not be recorded (then nothing is shown). */ +export function noteOffered(network: Network, identityId: string): boolean { + const r = read(network, identityId) + return r !== null && write(network, identityId, { shown: r.shown + 1, done: r.done }) +} + +/** Never offer again for this identity on this browser ("Not now", or a passkey was added). */ +export function dismissOffer(network: Network, identityId: string): void { + const r = read(network, identityId) + write(network, identityId, { shown: r?.shown ?? 0, done: true }) +} diff --git a/forge-web/lib/auth/passkey-vault/policy.test.ts b/forge-web/lib/auth/passkey-vault/policy.test.ts new file mode 100644 index 000000000..5dafe49dc --- /dev/null +++ b/forge-web/lib/auth/passkey-vault/policy.test.ts @@ -0,0 +1,40 @@ +/** Where a passkey that holds a key on Platform may be made: exactly two hosts, never a parent domain. */ + +import { describe, expect, it } from 'vitest' + +import { passkeyVaultProblem, passkeyVaultRpId } from './policy' + +const at = (hostname: string, pathname = '/') => ({ hostname, pathname }) +const META = { meta: 'meta' } +const yes = () => true + +describe('the passkey vault’s relying party', () => { + it('is the page’s host, for forge.dashhq.org and localhost only', () => { + expect(passkeyVaultRpId(at('forge.dashhq.org'))).toBe('forge.dashhq.org') + expect(passkeyVaultRpId(at('FORGE.dashhq.org'))).toBe('forge.dashhq.org') + expect(passkeyVaultRpId(at('localhost'))).toBe('localhost') + }) + + it.each([ + ['the parent domain', at('dashhq.org')], + ['another subdomain', at('evil.dashhq.org')], + ['a deeper subdomain', at('x.forge.dashhq.org')], + ['an IPFS subdomain gateway', at('bafybeigdyrzt.ipfs.dweb.link')], + ['an IPNS subdomain gateway', at('forge-dashhq-org.ipns.localhost')], + ['a path gateway', at('localhost', '/ipfs/bafy/')], + ['a shared host', at('someone.github.io')], + ['an IP address', at('127.0.0.1')], + ])('is refused on %s', (_what, location) => { + expect(passkeyVaultRpId(location)).toBeNull() + expect(passkeyVaultProblem(META, location, yes)).not.toBeNull() + }) + + it('is offered only where forge-meta exists and the browser has passkeys', () => { + expect(passkeyVaultProblem(META, at('forge.dashhq.org'), yes)).toBeNull() + expect(passkeyVaultProblem({}, at('forge.dashhq.org'), yes)).toMatch(/aren't available on this network/) + expect(passkeyVaultProblem(null, at('forge.dashhq.org'), yes)).toMatch(/aren't available on this network/) + expect(passkeyVaultProblem(META, at('forge.dashhq.org'), () => false)).toMatch(/can't use passkeys/) + expect(passkeyVaultProblem(META, null, yes)).toMatch(/can't use passkeys/) + expect(passkeyVaultProblem(META, at('someone.github.io'), yes)).toMatch(/dedicated origin/) + }) +}) diff --git a/forge-web/lib/auth/passkey-vault/policy.ts b/forge-web/lib/auth/passkey-vault/policy.ts new file mode 100644 index 000000000..9c32afd4b --- /dev/null +++ b/forge-web/lib/auth/passkey-vault/policy.ts @@ -0,0 +1,47 @@ +/** + * Where a passkey that holds a key on Platform may be made and used (PLAN-passkey-vault.md §3, + * "RP ID policy"). Its relying party id is exactly the page's host, and only two hosts qualify: + * `forge.dashhq.org` and `localhost` (development and the e2e suite). Never a parent domain such + * as `dashhq.org`: every subdomain could then ask the browser for the same PRF output, so any of + * them could open every Forge passkey's entry. IPFS subdomain gateways are refused too: each CID is + * its own origin, so a passkey made there would be lost with the next release. + * + * The browser vault's own passkeys (`../vault`) are unaffected: they stay on the page's origin. + */ + +import type { ForgeIds } from '../../deployments' +import { passkeysAvailable, sharedOriginProblem } from '../vault' + +/** The only relying party ids a vault passkey is made for. */ +const PASSKEY_VAULT_RP_IDS: readonly string[] = ['forge.dashhq.org', 'localhost'] + +/** Why the controls are hidden on a network without forge-meta, or whose forge-meta has no `vaultEntry` yet. */ +export const PASSKEYS_NOT_DEPLOYED = "Passkeys that work on your other devices aren't available on this network yet." + +type PageLocation = { readonly hostname: string; readonly pathname: string } + +const currentLocation = (): PageLocation | null => (typeof window === 'undefined' ? null : window.location) + +/** An IPFS or IPNS subdomain gateway host (`.ipfs.`): one origin per release. */ +const IPFS_SUBDOMAIN = /\.ip[fn]s\./i + +/** The relying party id for vault passkeys on this page, or null when the page may not have one. */ +export function passkeyVaultRpId(location: PageLocation | null = currentLocation()): string | null { + if (location === null) return null + const host = location.hostname.toLowerCase() + if (IPFS_SUBDOMAIN.test(host) || sharedOriginProblem(location) !== null) return null + return PASSKEY_VAULT_RP_IDS.includes(host) ? host : null +} + +/** + * Why passkeys that hold a key on Platform are not offered here (a sentence for the UI), or null + * when they are. The vault's entries live in forge-meta: a network without it has none. + */ +export function passkeyVaultProblem(forge: Pick | null, location: PageLocation | null = currentLocation(), available: () => boolean = passkeysAvailable): string | null { + if (forge?.meta === undefined) return PASSKEYS_NOT_DEPLOYED + if (location === null || !available()) return "This browser can't use passkeys on this page." + const shared = sharedOriginProblem(location) + if (shared !== null) return shared + if (passkeyVaultRpId(location) === null) return 'Passkeys that work on your other devices need Forge’s own address: open https://forge.dashhq.org.' + return null +} diff --git a/forge-web/lib/auth/passkey-vault/port.test.ts b/forge-web/lib/auth/passkey-vault/port.test.ts new file mode 100644 index 000000000..1b6e3f87b --- /dev/null +++ b/forge-web/lib/auth/passkey-vault/port.test.ts @@ -0,0 +1,162 @@ +/** + * The passkey vault's port over a fake SDK: proved reads of `vaultEntry` rows checked against the + * schema and their owner, identity keys in the core's shape (an unreadable bound drops the key), + * and writes through Forge's write helpers (create, replace of the sealed fields only, delete). + */ + +import { describe, expect, it, vi, beforeEach } from 'vitest' +import type { EvoSDK } from '@dashevo/evo-sdk' + +import { bytesToBase64 } from '../../sdk/query' +import type { WriteAuth } from '../../sdk/write' +import { base58Encode } from '../base58' +import { credentialBytes, credentialName, forgeVaultPort } from './port' + +const writes = vi.hoisted(() => [] as { op: string; params: Record }[]) +vi.mock('../../sdk/write', async (orig) => ({ + ...(await orig()), + createDocumentIdempotent: async (_sdk: unknown, _auth: unknown, params: Record) => void writes.push({ op: 'create', params }), + replaceDocumentIdempotent: async (_sdk: unknown, _auth: unknown, params: Record) => void writes.push({ op: 'replace', params }), + deleteDocumentIdempotent: async (_sdk: unknown, _auth: unknown, params: Record) => void writes.push({ op: 'delete', params }), +})) + +const OWNER = new Uint8Array(32).fill(7) +const OTHER = new Uint8Array(32).fill(8) +const META = base58Encode(new Uint8Array(32).fill(3)) +const GROUP = base58Encode(new Uint8Array(32).fill(4)) +const CRED = new Uint8Array(20).fill(5) + +function row(over: Record = {}): Record { + return { + $id: 'doc1', + $ownerId: base58Encode(OWNER), + $revision: 2, + $createdAt: 1000, + $updatedAt: 2000, + credentialId: bytesToBase64(CRED), + recipientKey: bytesToBase64(new Uint8Array(32).fill(1)), + version: 1, + authKeyId: 4, + enc: bytesToBase64(new Uint8Array(32).fill(2)), + sealed: bytesToBase64(new Uint8Array(256).fill(3)), + ...over, + } +} + +function fakeSdk(rows: Record[], keys: unknown[] | null = []) { + const queries: unknown[] = [] + const sdk = { + version: () => 11, + documents: { + query: async (q: unknown) => { + queries.push(q) + return new Map(rows.map((r, i) => [String(i), { toJSON: () => r }])) + }, + }, + identities: { + fetch: async () => (keys === null ? undefined : { publicKeys: keys, balance: 0n }), + keysRemainingBudgets: async (_id: string, ids: number[]) => new Map(ids.map((i) => [i, i === 4 ? 7n : null])), + }, + } as unknown as EvoSDK + return { sdk, queries } +} + +const auth: WriteAuth = { identityId: base58Encode(OWNER), network: 'devnet', getSigningKeyWif: () => 'wif' } + +beforeEach(() => { + writes.length = 0 +}) + +describe('the passkey vault port', () => { + it('lists the owner’s entries from forge-meta with one proved read, checked against the schema', async () => { + const { sdk, queries } = fakeSdk([row()]) + const [e] = await forgeVaultPort({ sdk, contractId: META }).list(OWNER) + expect(queries).toEqual([ + { dataContractId: META, documentTypeName: 'vaultEntry', where: [['$ownerId', '==', base58Encode(OWNER)]], orderBy: [['credentialId', 'asc']], limit: 100 }, + ]) + expect(e).toMatchObject({ documentId: 'doc1', revision: 2, createdAt: 1000, updatedAt: 2000, version: 1, authKeyId: 4 }) + expect(e!.credentialId).toEqual(CRED) + expect(e!.sealed).toHaveLength(256) + expect(e!.ownerId).toEqual(OWNER) + }) + + it('reads one credential by the unique index, and says null only when none is there', async () => { + const { sdk, queries } = fakeSdk([row()]) + expect(await forgeVaultPort({ sdk, contractId: META }).byCredential(OWNER, CRED)).not.toBeNull() + expect((queries[0] as { where: unknown }).where).toEqual([ + ['$ownerId', '==', base58Encode(OWNER)], + ['credentialId', '==', bytesToBase64(CRED)], + ]) + expect(await forgeVaultPort({ sdk: fakeSdk([]).sdk, contractId: META }).byCredential(OWNER, CRED)).toBeNull() + }) + + it.each([ + ['another owner', { $ownerId: base58Encode(OTHER) }], + ['a short recipient key', { recipientKey: bytesToBase64(new Uint8Array(31)) }], + ['a short credential id', { credentialId: bytesToBase64(new Uint8Array(15)) }], + ['an oversized ciphertext', { sealed: bytesToBase64(new Uint8Array(257)) }], + ['no key id', { authKeyId: undefined }], + ])('refuses a row with %s (an error, never an absent entry)', async (_what, over) => { + const port = forgeVaultPort({ sdk: fakeSdk([row(over)]).sdk, contractId: META }) + await expect(port.list(OWNER)).rejects.toThrow() + await expect(port.byCredential(OWNER, CRED)).rejects.toThrow() + }) + + it('reads the identity’s keys in the core’s shape, with remaining budgets; an unreadable bound drops the key', async () => { + const keys = [ + { keyId: 0, purposeNumber: 0, securityLevelNumber: 0, keyTypeNumber: 0, data: '02'.padEnd(66, '1') }, + { + keyId: 4, + purposeNumber: 0, + securityLevelNumber: 2, + keyTypeNumber: 0, + data: '03'.padEnd(66, '2'), + totalBudget: 10n, + expiresAt: 5000n, + contractBounds: { toJSON: () => ({ $type: 'contractGroup', id: GROUP }) }, + }, + { keyId: 5, purposeNumber: 0, securityLevelNumber: 2, keyTypeNumber: 2, data: 'aa'.repeat(20), disabledAt: 1n, totalBudget: 1n }, + { keyId: 6, purposeNumber: 0, securityLevelNumber: 2, keyTypeNumber: 0, data: '02'.padEnd(66, '3'), contractBounds: { toJSON: () => ({ $type: 'mystery', id: GROUP }) } }, + { keyId: 7, purposeNumber: 0, securityLevelNumber: 2, data: '02'.padEnd(66, '3') }, + ] + const got = await forgeVaultPort({ sdk: fakeSdk([], keys).sdk, contractId: META }).identityKeys(OWNER) + expect(got?.map((k) => k.id)).toEqual([0, 4, 5]) + expect(got?.[1]).toMatchObject({ purpose: 0, securityLevel: 2, type: 0, disabled: false, expiresAt: 5000, totalBudget: 10n, remainingBudget: 7n }) + expect(got?.[1]?.contractBounds).toEqual({ kind: 'contractGroup', groupId: new Uint8Array(32).fill(4) }) + // A budgeted key whose remaining budget the node did not answer: unknown, not spent. + expect(got?.[2]).toMatchObject({ disabled: true, type: 2 }) + expect(got?.[2]?.remainingBudget).toBeUndefined() + expect(await forgeVaultPort({ sdk: fakeSdk([], null).sdk, contractId: META }).identityKeys(OWNER)).toBeNull() + }) + + it('creates, replaces only the sealed fields at the revision read, and deletes, as the session', async () => { + const { sdk } = fakeSdk([row()]) + const port = forgeVaultPort({ sdk, contractId: META, auth }) + const existing = (await port.byCredential(OWNER, CRED))! + const entry = { version: 1, credentialId: CRED, recipientKey: existing.recipientKey, authKeyId: 9, enc: new Uint8Array(32), sealed: new Uint8Array(256) } + await port.put({ ownerId: OWNER, entry, existing: null }) + await port.put({ ownerId: OWNER, entry, existing }) + await port.remove({ ownerId: OWNER, entry: existing }) + expect(writes.map((w) => w.op)).toEqual(['create', 'replace', 'delete']) + expect(writes[0]!.params).toMatchObject({ contractId: META, documentType: 'vaultEntry', data: { credentialId: CRED, authKeyId: 9, version: 1 } }) + expect(writes[1]!.params).toMatchObject({ documentId: 'doc1', expectedRevision: 2n }) + expect(Object.keys(writes[1]!.params['changes'] as object).sort()).toEqual(['authKeyId', 'enc', 'sealed', 'version']) + expect(writes[2]!.params).toMatchObject({ contractId: META, documentType: 'vaultEntry', documentId: 'doc1' }) + // The recipient key is immutable: a replace to another is a bug, refused before signing. + await expect(port.put({ ownerId: OWNER, entry: { ...entry, recipientKey: new Uint8Array(32) }, existing })).rejects.toThrow(/same passkey/) + }) + + it('writes nothing without a signer for that identity', async () => { + const { sdk } = fakeSdk([row()]) + const entry = { version: 1, credentialId: CRED, recipientKey: new Uint8Array(32), authKeyId: 9, enc: new Uint8Array(32), sealed: new Uint8Array(256) } + await expect(forgeVaultPort({ sdk, contractId: META }).put({ ownerId: OWNER, entry, existing: null })).rejects.toThrow(/cannot write/) + await expect(forgeVaultPort({ sdk, contractId: META, auth }).put({ ownerId: OTHER, entry, existing: null })).rejects.toThrow(/cannot write/) + expect(writes).toEqual([]) + }) + + it('names credential ids in base64url and back', () => { + const id = Uint8Array.from({ length: 33 }, (_, i) => i * 7 + 250) + expect(credentialName(id)).not.toMatch(/[+/=]/) + expect(credentialBytes(credentialName(id))).toEqual(id) + }) +}) diff --git a/forge-web/lib/auth/passkey-vault/port.ts b/forge-web/lib/auth/passkey-vault/port.ts new file mode 100644 index 000000000..d00dc2ee6 --- /dev/null +++ b/forge-web/lib/auth/passkey-vault/port.ts @@ -0,0 +1,242 @@ +/** + * The passkey vault's chain port over Forge's SDK connection: `vaultEntry` documents in + * forge-meta, and the owner's keys, all read with proofs (the trusted connection proof-checks + * every query, `lib/sdk/query.ts` {@link queryDocumentsWithProof}). Writes go through Forge's + * write helpers, which already run as the identity's only writer (`serialized(identityId)`, + * `lib/sdk/write.ts`) and settle a lost answer by reading back, so a retried action lands once. + * + * The signer is the session's {@link WriteAuth}: a write to forge-meta needs a key whose bounds + * cover it (a group-bound Forge key does). A port built without one reads only. + * + * Every row is checked against the schema's sizes and its owner before the core sees it; a row + * that does not read is an error, never an absent entry (a planted or unreadable entry must not + * make the vault create a second one, or skip a cap). + */ + +import { hexToBytes } from '@noble/hashes/utils.js' +import type { EvoSDK } from '@dashevo/evo-sdk' + +import { DOC } from '../../repo/contract' +import { authSdk, type WasmKey } from '../../sdk/facade' +import { base64ToBytes, bytesToBase64, queryDocumentsWithProof, type PlainDocument } from '../../sdk/query' +import { createDocumentIdempotent, deleteDocumentIdempotent, replaceDocumentIdempotent, type WriteAuth } from '../../sdk/write' +import { + bytesEqual, + MAX_CREDENTIAL_ID_LENGTH, + MIN_CREDENTIAL_ID_LENGTH, + type ContractBounds, + type OnChainKey, + type SealedVaultEntry, + type VaultEntryRecord, + type VaultPort, +} from '../../vendor/platform-auth/passkey-vault' +import { base58Encode, decodeIdentifier } from '../base58' + +/** The most entries one read lists (Platform's page limit; the client's cap is 10). */ +const VAULT_LIST_LIMIT = 100 + +/** Bytes from a document field as the SDK's JSON gives them (base64), or as bytes. */ +function bytesOf(value: unknown): Uint8Array | null { + if (value instanceof Uint8Array) return value.slice() + if (typeof value !== 'string') return null + try { + return base64ToBytes(value) + } catch { + return null + } +} + +const isU32 = (n: unknown): n is number => typeof n === 'number' && Number.isInteger(n) && n >= 0 && n <= 0xffffffff +const msOf = (v: unknown): number | undefined => (typeof v === 'number' && Number.isFinite(v) ? v : undefined) + +/** + * A `vaultEntry` row as the core's record, checked against the schema (`forge-meta.json`) and + * the owner asked for. Throws on anything else. + */ +function entryOf(doc: PlainDocument, ownerId: Uint8Array): VaultEntryRecord { + const owner = doc['$ownerId'] + const credentialId = bytesOf(doc['credentialId']) + const recipientKey = bytesOf(doc['recipientKey']) + const enc = bytesOf(doc['enc']) + const sealed = bytesOf(doc['sealed']) + const { version, authKeyId } = doc + const id = doc['$id'] + const ok = + typeof owner === 'string' && + bytesEqual(decodeIdentifier(owner), ownerId) && + typeof id === 'string' && + credentialId !== null && + credentialId.length >= MIN_CREDENTIAL_ID_LENGTH && + credentialId.length <= MAX_CREDENTIAL_ID_LENGTH && + recipientKey?.length === 32 && + enc?.length === 32 && + sealed !== null && + sealed.length >= 32 && + sealed.length <= 256 && + typeof version === 'number' && + isU32(authKeyId) + // copy-lint-ignore: a developer error (the SDK answered a row the schema forbids) + if (!ok) throw new Error('a passkey entry on Platform does not read as one') + const revision = msOf(doc['$revision']) + const createdAt = msOf(doc['$createdAt']) + const updatedAt = msOf(doc['$updatedAt']) + return { + ownerId: ownerId.slice(), + documentId: id, + version, + credentialId, + recipientKey, + authKeyId, + enc, + sealed, + ...(revision !== undefined ? { revision } : {}), + ...(createdAt !== undefined ? { createdAt } : {}), + ...(updatedAt !== undefined ? { updatedAt } : {}), + } +} + +/** A key's bounds in the core's shape: undefined when it has none, null when they do not read. */ +function boundsOf(k: Pick): ContractBounds | undefined | null { + if (!k.contractBounds) return undefined + let json: { $type?: unknown; id?: unknown; documentTypeName?: unknown } + try { + json = k.contractBounds.toJSON() + } catch { + return null + } + if (typeof json.id !== 'string') return null + let id: Uint8Array + try { + id = decodeIdentifier(json.id) + } catch { + return null + } + switch (json.$type) { + case 'singleContract': + return { kind: 'singleContract', contractId: id } + case 'documentType': + return typeof json.documentTypeName === 'string' ? { kind: 'singleContractDocumentType', contractId: id, documentType: json.documentTypeName } : null + case 'contractGroup': + return { kind: 'contractGroup', groupId: id } + default: + return null + } +} + +/** + * An identity key in the core's shape, or null when it cannot be read faithfully (no key type, + * undecodable data, unreadable bounds): such a key is dropped, never shown as unbound. + */ +export function onChainKeyOf(k: WasmKey, remainingBudget?: bigint | null): OnChainKey | null { + const bounds = boundsOf(k) + if (k.keyTypeNumber === undefined || typeof k.data !== 'string' || !/^(?:[0-9a-f]{2})+$/i.test(k.data) || bounds === null) return null + return { + id: k.keyId, + purpose: k.purposeNumber, + securityLevel: k.securityLevelNumber, + type: k.keyTypeNumber, + data: hexToBytes(k.data), + disabled: k.disabledAt !== undefined, + ...(bounds !== undefined ? { contractBounds: bounds } : {}), + ...(k.expiresAt !== undefined ? { expiresAt: Number(k.expiresAt) } : {}), + ...(k.totalBudget !== undefined ? { totalBudget: k.totalBudget } : {}), + // Drive keeps a remaining budget for every budgeted key: none read is a node behind (unknown). + ...(remainingBudget !== undefined && remainingBudget !== null ? { remainingBudget } : {}), + } +} + +/** The fields a `vaultEntry` stores (bytes stay bytes: the write path keeps them binary). */ +function entryData(entry: SealedVaultEntry): Record { + return { credentialId: entry.credentialId, recipientKey: entry.recipientKey, version: entry.version, authKeyId: entry.authKeyId, enc: entry.enc, sealed: entry.sealed } +} + +export interface ForgeVaultPortOptions { + readonly sdk: EvoSDK + /** forge-meta, the contract `vaultEntry` lives in. */ + readonly contractId: string + /** The session's signer; without it the port reads only. */ + readonly auth?: WriteAuth | null +} + +/** The passkey vault's port over `sdk`. */ +export function forgeVaultPort({ sdk, contractId, auth = null }: ForgeVaultPortOptions): VaultPort { + const query = (ownerId: Uint8Array, credentialId?: Uint8Array) => + queryDocumentsWithProof(sdk, { + dataContractId: contractId, + documentTypeName: DOC.vaultEntry, + // The unique `byCredential [$ownerId, credentialId]` index serves both reads. + where: [['$ownerId', '==', base58Encode(ownerId)], ...(credentialId ? [['credentialId', '==', bytesToBase64(credentialId)] as const] : [])], + orderBy: [['credentialId', 'asc']], + limit: credentialId ? 1 : VAULT_LIST_LIMIT, + }) + const signer = (ownerId: Uint8Array): WriteAuth => { + // copy-lint-ignore: a developer error (a write through a read-only port, or for another identity) + if (auth === null || auth.identityId !== base58Encode(ownerId)) throw new Error('this passkey vault port cannot write for that identity') + return auth + } + const byCredential = async (ownerId: Uint8Array, credentialId: Uint8Array): Promise => { + const { documents } = await query(ownerId, credentialId) + return documents.map((d) => entryOf(d, ownerId)).find((e) => bytesEqual(e.credentialId, credentialId)) ?? null + } + return { + async list(ownerId) { + const { documents } = await query(ownerId) + return documents.map((d) => entryOf(d, ownerId)) + }, + + byCredential, + + async identityKeys(ownerId) { + const id = base58Encode(ownerId) + const api = authSdk(sdk) + const identity = await api.identities.fetch(id) + if (!identity) return null + const budgeted = identity.publicKeys.filter((k) => k.totalBudget !== undefined).map((k) => k.keyId) + // Keyed by number whatever the SDK keys its map with (a bigint key would read as no budget). + const read = budgeted.length > 0 ? await api.identities.keysRemainingBudgets(id, budgeted) : new Map() + const budgets = new Map([...read].map(([keyId, remaining]) => [Number(keyId), remaining] as const)) + return identity.publicKeys.flatMap((k) => { + const key = onChainKeyOf(k, budgets.get(k.keyId)) + return key ? [key] : [] + }) + }, + + async put({ ownerId, entry, existing }) { + const writer = signer(ownerId) + if (existing === null) { + await createDocumentIdempotent(sdk, writer, { contractId, documentType: DOC.vaultEntry, data: entryData(entry) }) + return + } + // credentialId and recipientKey are immutable: only the sealed fields and the key id change. + // copy-lint-ignore: a developer error (the core never asks for this) + if (!bytesEqual(existing.credentialId, entry.credentialId) || !bytesEqual(existing.recipientKey, entry.recipientKey) || existing.documentId === undefined) { + throw new Error('a passkey entry can only be replaced by one for the same passkey') + } + await replaceDocumentIdempotent(sdk, writer, { + contractId, + documentType: DOC.vaultEntry, + documentId: existing.documentId, + changes: { version: entry.version, authKeyId: entry.authKeyId, enc: entry.enc, sealed: entry.sealed }, + ...(existing.revision !== undefined ? { expectedRevision: BigInt(existing.revision) } : {}), + }) + }, + + async remove({ ownerId, entry }) { + const writer = signer(ownerId) + const documentId = entry.documentId ?? (await byCredential(ownerId, entry.credentialId))?.documentId + if (documentId === undefined) return + await deleteDocumentIdempotent(sdk, writer, { contractId, documentType: DOC.vaultEntry, documentId }) + }, + } +} + +/** A credential id as the UI names it (base64url, no padding). */ +export function credentialName(credentialId: Uint8Array): string { + return bytesToBase64(credentialId).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') +} + +/** The bytes of a credential id {@link credentialName} named. */ +export function credentialBytes(name: string): Uint8Array { + const b64 = name.replace(/-/g, '+').replace(/_/g, '/') + return base64ToBytes(b64 + '='.repeat((4 - (b64.length % 4)) % 4)) +} diff --git a/forge-web/lib/auth/passkey-vault/profile.test.ts b/forge-web/lib/auth/passkey-vault/profile.test.ts new file mode 100644 index 000000000..6787fbe10 --- /dev/null +++ b/forge-web/lib/auth/passkey-vault/profile.test.ts @@ -0,0 +1,78 @@ +/** + * Forge's real passkey-vault profile reproduces the bytes `__vectors__/forge.json` pins (written by + * the core's independent Python generator): any drift here would orphan every Forge passkey. + */ + +import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js' +import { describe, expect, it } from 'vitest' + +import { entryAad, hpkeInfo, openEntry, prfInput, recipientFromPrf, sealEntry, type SlotKey } from '../../vendor/platform-auth/passkey-vault' +import { forgeProfile } from '../../vendor/platform-auth/passkey-vault/__fixtures__/profiles' +import { loadVectors, req, slotBundle, type VectorFile } from '../../vendor/platform-auth/passkey-vault/__fixtures__/vectors' +import { FORGE_BUNDLE_CODEC, FORGE_BUNDLE_FORMAT, FORGE_VAULT_PROFILE } from './profile' + +const file = loadVectors }>('forge') +const contractId = hexToBytes(file.contractId) +const ownerId = hexToBytes(file.ownerId) +const hex = bytesToHex +const shape = (keys: readonly SlotKey[]) => keys.map((k) => ({ ...k, privateKey: hex(k.privateKey) })) + +describe("Forge's passkey-vault profile", () => { + it('is the profile the vectors were generated for', () => { + const { formats, ...labels } = file.profile as { formats: { id: number; length: number; maxKeys: number }[] } + expect(labels).toEqual({ + prfLabel: FORGE_VAULT_PROFILE.prfLabel, + infoLabel: FORGE_VAULT_PROFILE.infoLabel, + aadDocType: FORGE_VAULT_PROFILE.aadDocType, + entryVersion: FORGE_VAULT_PROFILE.entryVersion, + strictSealedLength: FORGE_VAULT_PROFILE.strictSealedLength, + }) + expect(formats.map((f) => ({ id: f.id, length: f.length, maxKeys: f.maxKeys }))).toEqual([{ id: FORGE_BUNDLE_FORMAT, length: FORGE_BUNDLE_CODEC.length, maxKeys: 6 }]) + expect(FORGE_VAULT_PROFILE.formats).toEqual([FORGE_BUNDLE_CODEC]) + }) + + for (const v of file.vectors) { + it(`${v.name}: seals and opens to the generator's bytes`, () => { + const prf = hexToBytes(v.prfOutput) + expect(hex(prfInput(FORGE_VAULT_PROFILE, contractId))).toBe(req(v.prfInput, 'prfInput')) + const recipient = recipientFromPrf(prf) + expect(hex(recipient.privateKey)).toBe(req(v.recipientSk, 'recipientSk')) + expect(hex(recipient.publicKey)).toBe(req(v.recipientKey, 'recipientKey')) + const entry = sealEntry(FORGE_VAULT_PROFILE, { + contractId, + ownerId, + credentialId: hexToBytes(v.credentialId), + recipientKey: recipient.publicKey, + bundle: slotBundle(FORGE_BUNDLE_FORMAT, v.keys), + codec: FORGE_BUNDLE_CODEC, + ephemeralIkm: hexToBytes(v.ephemeralIkm), + }) + expect(entry.authKeyId).toBe(req(v.authKeyId, 'authKeyId')) + expect(hex(hpkeInfo(FORGE_VAULT_PROFILE, contractId, ownerId))).toBe(req(v.info, 'info')) + expect(hex(entryAad(FORGE_VAULT_PROFILE, entry))).toBe(req(v.aad, 'aad')) + expect(hex(FORGE_BUNDLE_CODEC.encode(slotBundle(FORGE_BUNDLE_FORMAT, v.keys)))).toBe(req(v.bundle, 'bundle')) + expect(hex(entry.enc)).toBe(req(v.enc, 'enc')) + expect(hex(entry.sealed)).toBe(req(v.sealed, 'sealed')) + expect(entry.sealed).toHaveLength(256) + + const opened = openEntry(FORGE_VAULT_PROFILE, { contractId, ownerId, entry, prfOutput: prf }) + expect(opened.codec).toBe(FORGE_BUNDLE_CODEC) + expect(shape(opened.bundle.keys)).toEqual(shape(slotBundle(FORGE_BUNDLE_FORMAT, v.keys).keys)) + // The core's fixture profile opens Forge's entries too: the same bytes, whatever the rules. + expect(shape(openEntry(forgeProfile, { contractId, ownerId, entry, prfOutput: prf }).bundle.keys)).toEqual(shape(opened.bundle.keys)) + }) + } + + it('refuses MASTER, CRITICAL, TRANSFER and a second encryption key in a bundle', () => { + const sk = (n: number) => new Uint8Array(32).fill(n) + const main: SlotKey = { purpose: 0, securityLevel: 2, keyType: 0, keyId: 1, privateKey: sk(1) } + const enc = (keyId: number): SlotKey => ({ purpose: 1, securityLevel: 3, keyType: 0, keyId, privateKey: sk(keyId) }) + const encode = (keys: SlotKey[]) => FORGE_BUNDLE_CODEC.encode({ format: FORGE_BUNDLE_FORMAT, keys }) + expect(() => encode([main, enc(2)])).not.toThrow() + expect(() => encode([{ ...main, securityLevel: 0 }])).toThrow(/slot 0/) + expect(() => encode([{ ...main, securityLevel: 1 }])).toThrow(/slot 0/) + expect(() => encode([main, { ...main, keyId: 2, purpose: 3 }])).toThrow(/slot 1/) + expect(() => encode([enc(2)])).toThrow(/slot 0/) + expect(() => encode([main, enc(2), enc(3)])).toThrow(/one encryption key/) + }) +}) diff --git a/forge-web/lib/auth/passkey-vault/profile.ts b/forge-web/lib/auth/passkey-vault/profile.ts new file mode 100644 index 000000000..b9da414eb --- /dev/null +++ b/forge-web/lib/auth/passkey-vault/profile.ts @@ -0,0 +1,53 @@ +/** + * Forge's passkey-vault profile (PLAN-passkey-vault.md §1): the labels and the one bundle format + * that make a `vaultEntry` Forge's. The ids, lengths, key count and labels define the bytes every + * entry on Platform carries, so they are pinned by `__vectors__/forge.json` (the vendored core's, + * written by an independent generator) and must never change: a change orphans every passkey. + * + * One format, padded to 240 bytes (256 sealed): slot 0 is the session's main key, then the live + * per-contract wallet grants, then at most one encryption key. Every entry has the same size + * whatever it holds. The codec's `allow` and `check` are shape rules only; whether a key may be + * used is the chain check's (`./service`), against the identity read with proofs. + */ + +import { KeyPurpose, KeyType, SecurityLevel, defineProfile, slotKeysCodec, type SlotKey } from '../../vendor/platform-auth/passkey-vault' + +type KeyShape = Readonly> + +/** The relying party name a vault passkey shows in the user's passkey manager. */ +export const PASSKEY_VAULT_RP_NAME = 'Dash Forge' + +/** The bundle format byte of Forge's one format. */ +export const FORGE_BUNDLE_FORMAT = 1 + +/** Keys one bundle holds: 2 + 6 × 39 = 236 of its 240 bytes. */ +export const FORGE_BUNDLE_MAX_KEYS = 6 + +/** A signing key type Forge keys use: a secp256k1 point, or its hash160. */ +const signingType = (k: KeyShape): boolean => k.keyType === KeyType.ECDSA_SECP256K1 || k.keyType === KeyType.ECDSA_HASH160 + +/** + * Slot 0 and the wallet grants: AUTHENTICATION at HIGH (never MASTER or CRITICAL). After them, one + * ENCRYPTION key at MEDIUM (secp256k1). Never TRANSFER or any other purpose. + */ +function forgeAllow(k: KeyShape, slot: number): boolean { + if (k.purpose === KeyPurpose.AUTHENTICATION) return k.securityLevel === SecurityLevel.HIGH && signingType(k) + return slot > 0 && k.purpose === KeyPurpose.ENCRYPTION && k.securityLevel === SecurityLevel.MEDIUM && k.keyType === KeyType.ECDSA_SECP256K1 +} + +export const FORGE_BUNDLE_CODEC = slotKeysCodec({ + id: FORGE_BUNDLE_FORMAT, + length: 240, + maxKeys: FORGE_BUNDLE_MAX_KEYS, + allow: forgeAllow, + check: (keys) => (keys.filter((k) => k.purpose === KeyPurpose.ENCRYPTION).length <= 1 ? null : 'a bundle holds one encryption key at most'), +}) + +export const FORGE_VAULT_PROFILE = defineProfile({ + prfLabel: 'dash-forge/passkey-vault/v1/prf', + infoLabel: 'dash-forge/passkey-vault/v1', + aadDocType: 'vaultEntry', + entryVersion: 1, + formats: [FORGE_BUNDLE_CODEC], + strictSealedLength: true, +}) diff --git a/forge-web/lib/auth/passkey-vault/service.test.ts b/forge-web/lib/auth/passkey-vault/service.test.ts new file mode 100644 index 000000000..0f3a804f3 --- /dev/null +++ b/forge-web/lib/auth/passkey-vault/service.test.ts @@ -0,0 +1,327 @@ +/** + * Forge's passkey vault against the core's in-memory port and software authenticator: what a + * session may seal, the chain check an opened passkey must pass (planted entries refused), the + * user-handle refusals, the cap, the copies handed back, and the rows Settings lists. + */ + +import { secp256k1 } from '@noble/curves/secp256k1.js' +import { beforeEach, describe, expect, it } from 'vitest' + +import { + KeyPurpose, + KeyType, + PasskeyError, + recipientFromPrf, + SecurityLevel, + sealEntry, + userHandleFor, + VaultError, + type OnChainKey, + type SlotKey, +} from '../../vendor/platform-auth/passkey-vault' +import { fakePasskeyAdapter, type FakePasskeyAdapter } from '../../vendor/platform-auth/passkey-vault/__fixtures__/fake-passkey' +import { MemoryVaultPort } from '../../vendor/platform-auth/passkey-vault/__fixtures__/memory-port' +import { base58Encode } from '../base58' +import type { VaultSecret } from '../vault' +import { encodeWif } from '../wif' +import type { PasskeyMarker } from './markers' +import { FORGE_BUNDLE_CODEC, FORGE_BUNDLE_FORMAT, FORGE_VAULT_PROFILE } from './profile' +import { credentialName } from './port' +import { + forgePasskeyVault, + needsReseal, + passkeyRows, + platformPasskeyError, + PlatformPasskeyError, + passkeyIsUseless, + sealableSession, + vaultPasskeyFailure, + verifyBundle, + wipeSession, + type ForgePasskeyVault, + type VaultForgeIds, +} from './service' + +const NET = 'devnet' as const +const NOW = 1_800_000_000_000 +const DAY = 24 * 60 * 60 * 1000 +const id32 = (n: number) => new Uint8Array(32).fill(n) +const FORGE: VaultForgeIds = { core: base58Encode(id32(11)), collab: base58Encode(id32(12)), community: base58Encode(id32(13)), meta: base58Encode(id32(14)), group: base58Encode(id32(15)) } +const OWNER = id32(7) +const IDENTITY = base58Encode(OWNER) +const RP = 'forge.dashhq.org' + +const sk = (n: number) => new Uint8Array(32).fill(n) +const wifOf = (n: number) => encodeWif(sk(n), NET) +const pub = (n: number) => secp256k1.getPublicKey(sk(n), true) + +/** A live key whose private key is `sk(id)`. */ +function key(id: number, over: Partial = {}): OnChainKey { + return { id, purpose: KeyPurpose.AUTHENTICATION, securityLevel: SecurityLevel.HIGH, type: KeyType.ECDSA_SECP256K1, disabled: false, ...over, data: over.data ?? pub(id) } +} +/** A Forge limited key (or v2 wallet key): group-bound, budgeted, expiring. */ +const limited = (id: number, over: Partial = {}) => + key(id, { contractBounds: { kind: 'contractGroup', groupId: id32(15) }, totalBudget: 5_000_000_000n, remainingBudget: 4_000_000_000n, expiresAt: NOW + 90 * DAY, ...over }) +/** A per-contract wallet grant a passkey may hold: bound to one contract, budgeted and expiring. */ +const grant = (id: number, contract: number, over: Partial = {}) => + key(id, { contractBounds: { kind: 'singleContract', contractId: id32(contract) }, totalBudget: 5_000_000_000n, remainingBudget: 4_000_000_000n, expiresAt: NOW + 90 * DAY, ...over }) +/** A v1 wallet's grant: bound to one contract with no budget and no expiry. */ +const unlimitedGrant = (id: number, contract: number) => key(id, { contractBounds: { kind: 'singleContract', contractId: id32(contract) } }) +const encryptionKey = (id: number, over: Partial = {}) => key(id, { purpose: KeyPurpose.ENCRYPTION, securityLevel: SecurityLevel.MEDIUM, ...over }) + +const slot = (k: OnChainKey, privateKey = sk(k.id)): SlotKey => ({ purpose: k.purpose, securityLevel: k.securityLevel, keyType: k.type, keyId: k.id, privateKey }) + +let port: MemoryVaultPort +let adapter: FakePasskeyAdapter +let vault: ForgePasskeyVault + +beforeEach(() => { + port = new MemoryVaultPort() + adapter = fakePasskeyAdapter({ multiDevice: true }) + vault = forgePasskeyVault({ port, adapter, rpId: RP, forge: FORGE, network: NET, now: () => NOW, sleep: async () => undefined }) +}) + +const blank = { ownerId: OWNER, keys: [] as SlotKey[] } + +/** Enrol a passkey and seal `secret` to it, as the controller does. */ +async function enrolAndStore(secret: VaultSecret, keys: OnChainKey[], encryption: { keyId: number; secret: Uint8Array } | null = null) { + port.setKeys(OWNER, keys) + const pending = await vault.enroll(blank, { userName: 'Dash Forge' }) + const confirmed = await vault.confirm(pending) + const s = sealableSession({ ownerId: OWNER, secret, keys, forge: FORGE, now: NOW, encryption }) + try { + await vault.store(s, confirmed) + } finally { + wipeSession(s) + } + return { credentialId: pending.credentialId, recipientKey: confirmed.recipientKey } +} + +/** An entry anyone with a live key of the owner could write, sealed to a passkey of the owner. */ +async function plant(keys: SlotKey[], authKeyId = keys[0]!.keyId) { + const created = await adapter.create({ rpId: RP, rpName: 'x', userHandle: userHandleFor(OWNER, id32(14)), userName: 'x', prfInput: vault.prfInput, exclude: [] }) + const recipientKey = recipientFromPrf(adapter.prfOf(created.credentialId, vault.prfInput)).publicKey + const entry = sealEntry(FORGE_VAULT_PROFILE, { + contractId: id32(14), + ownerId: OWNER, + credentialId: created.credentialId, + recipientKey, + bundle: { format: FORGE_BUNDLE_FORMAT, keys }, + codec: FORGE_BUNDLE_CODEC, + authKeyId, + }) + port.plant(OWNER, entry) + adapter.choose(created.credentialId) + return { credentialId: created.credentialId, recipientKey } +} + +describe('a Forge passkey', () => { + it('holds the main key and the live wallet grants, and signs in with them after the chain check', async () => { + const keys = [key(0, { securityLevel: SecurityLevel.MASTER, data: pub(1) }), limited(5), grant(6, 12), grant(7, 13)] + const secret: VaultSecret = { identityId: IDENTITY, keyId: 5, wif: wifOf(5), extra: [{ contractId: FORGE.collab, keyId: 6, wif: wifOf(6) }, { contractId: FORGE.community, keyId: 7, wif: wifOf(7) }] } + const { credentialId } = await enrolAndStore(secret, keys) + const opened = await vault.open() + expect(opened.credentialId).toEqual(credentialId) + expect(opened.result).toMatchObject({ keyId: 5, wif: wifOf(5), keyIds: [5, 6, 7], dropped: 0, encryption: null }) + expect(opened.result.extra).toEqual([ + { contractId: FORGE.collab, keyId: 6, wif: wifOf(6) }, + { contractId: FORGE.community, keyId: 7, wif: wifOf(7) }, + ]) + // The PRF output is wiped unless the caller keeps it (the sign-in does, for the browser vault). + expect(opened.prfOutput).toBeNull() + const kept = await vault.open({ keepPrfOutput: true }) + expect(kept.prfOutput).toEqual(adapter.prfOf(credentialId, vault.prfInput)) + }) + + it('holds the encryption key only when given, and only the identity’s usable one', async () => { + const keys = [limited(5), encryptionKey(9), encryptionKey(10, { disabled: true })] + const secret: VaultSecret = { identityId: IDENTITY, keyId: 5, wif: wifOf(5) } + const given = sk(9) + await enrolAndStore(secret, keys, { keyId: 9, secret: given }) + // The caller's copy is its own: sealing did not wipe it. + expect(given).toEqual(sk(9)) + const opened = await vault.open() + expect(opened.result.encryption).toEqual({ keyId: 9, secret: sk(9) }) + expect(opened.result.keyIds).toEqual([5, 9]) + expect(() => sealableSession({ ownerId: OWNER, secret, keys, forge: FORGE, now: NOW, encryption: { keyId: 10, secret: sk(10) } })).toThrow(PlatformPasskeyError) + expect(() => sealableSession({ ownerId: OWNER, secret, keys, forge: FORGE, now: NOW, encryption: { keyId: 9, secret: sk(8) } })).toThrow(/isn't your identity's current one/) + }) + + it.each([ + ['a key with no bounds', key(5, { totalBudget: 1n, expiresAt: NOW + DAY })], + ['a shipped wallet’s one-contract key', grant(5, 11)], + ['a group-bound key without a budget', limited(5, { totalBudget: undefined })], + ['a group-bound key without an expiry', limited(5, { expiresAt: undefined })], + ['a key of another group', limited(5, { contractBounds: { kind: 'contractGroup', groupId: id32(99) } })], + ['a CRITICAL key', limited(5, { securityLevel: SecurityLevel.CRITICAL })], + ['a disabled key', limited(5, { disabled: true })], + ['a key in its last minutes', limited(5, { expiresAt: NOW + 60_000 })], + ['a key with no budget left', limited(5, { remainingBudget: 0n })], + ])('never seals %s as the main key', (_what, main) => { + const secret: VaultSecret = { identityId: IDENTITY, keyId: 5, wif: wifOf(5) } + expect(() => sealableSession({ ownerId: OWNER, secret, keys: [main], forge: FORGE, now: NOW })).toThrow(expect.objectContaining({ code: 'ineligible' })) + }) + + it('never seals a pasted tab-only key, nor a key the stored private key does not control', () => { + const keys = [limited(5)] + expect(() => sealableSession({ ownerId: OWNER, secret: { identityId: IDENTITY, keyId: -1, wif: wifOf(5) }, keys, forge: FORGE, now: NOW })).toThrow(PlatformPasskeyError) + expect(() => sealableSession({ ownerId: OWNER, secret: { identityId: IDENTITY, keyId: 5, wif: wifOf(6) }, keys, forge: FORGE, now: NOW })).toThrow(PlatformPasskeyError) + }) + + it('leaves out grants without a spending limit or an expiry, and counts them for the UI', () => { + const keys = [limited(5), grant(6, 12), unlimitedGrant(7, 13), grant(8, 11, { totalBudget: undefined, remainingBudget: undefined }), grant(9, 11, { expiresAt: undefined })] + const extra = [6, 7, 8, 9].map((n, i) => ({ contractId: [FORGE.collab, FORGE.community, FORGE.core, FORGE.core][i]!, keyId: n, wif: wifOf(n) })) + const s = sealableSession({ ownerId: OWNER, secret: { identityId: IDENTITY, keyId: 5, wif: wifOf(5), extra }, keys, forge: FORGE, now: NOW }) + expect(s.keys.map((k) => k.keyId)).toEqual([5, 6]) + expect(s.leftOut).toBe(3) + // Nothing left out: nothing to say. + const all = sealableSession({ ownerId: OWNER, secret: { identityId: IDENTITY, keyId: 5, wif: wifOf(5), extra: extra.slice(0, 1) }, keys, forge: FORGE, now: NOW }) + expect(all.leftOut).toBeUndefined() + // Held-only and disabled keys are not "left out for a missing limit": they were never going in. + const held = sealableSession({ ownerId: OWNER, secret: { identityId: IDENTITY, keyId: 5, wif: wifOf(5), extra: [{ ...extra[1]!, holdOnly: true as const }] }, keys, forge: FORGE, now: NOW }) + expect(held.leftOut).toBeUndefined() + for (const x of [s, all, held]) wipeSession(x) + }) + + it('leaves out held-only, unbounded, foreign, disabled, uncontrolled and surplus grants', () => { + const keys = [limited(5), grant(6, 12), key(7), grant(8, 99), grant(9, 13), grant(10, 11), grant(20, 11), grant(21, 11), grant(22, 11), grant(23, 11), grant(24, 11)] + keys[4] = { ...keys[4]!, disabled: true } + const extra = [ + { contractId: FORGE.collab, keyId: 6, wif: wifOf(6), holdOnly: true as const }, + { contractId: FORGE.core, keyId: 7, wif: wifOf(7) }, + { contractId: FORGE.core, keyId: 8, wif: wifOf(8) }, + { contractId: FORGE.community, keyId: 9, wif: wifOf(9) }, + { contractId: FORGE.core, keyId: 10, wif: wifOf(11) }, + ...[20, 21, 22, 23, 24].map((n) => ({ contractId: FORGE.core, keyId: n, wif: wifOf(n) })), + ] + const s = sealableSession({ ownerId: OWNER, secret: { identityId: IDENTITY, keyId: 5, wif: wifOf(5), extra }, keys, forge: FORGE, now: NOW }) + // Slot 0 and four grants (one per Forge contract), then the encryption key: six slots. + expect(s.keys.map((k) => k.keyId)).toEqual([5, 20, 21, 22, 23]) + const withEnc = sealableSession({ ownerId: OWNER, secret: { identityId: IDENTITY, keyId: 5, wif: wifOf(5), extra }, keys: [...keys, encryptionKey(30)], forge: FORGE, now: NOW, encryption: { keyId: 30, secret: sk(30) } }) + expect(withEnc.keys.map((k) => k.keyId)).toEqual([5, 20, 21, 22, 23, 30]) + wipeSession(s) + expect(s.keys.every((k) => k.privateKey.every((b) => b === 0))).toBe(true) + }) +}) + +describe('signing in with a passkey refuses a planted entry', () => { + const refused = async (keys: SlotKey[], onChain: OnChainKey[], why: RegExp) => { + port.setKeys(OWNER, onChain) + await plant(keys) + const e = await vault.open().catch((x: unknown) => x) + expect(e).toBeInstanceOf(VaultError) + expect(e).toMatchObject({ code: 'refused' }) + expect(platformPasskeyError(e)).toMatchObject({ code: 'refused', message: expect.stringMatching(why) }) + } + + it('a key not on the identity', () => refused([slot(limited(5))], [limited(4)], /doesn't show the key/)) + it('a disabled key', () => refused([slot(limited(5))], [limited(5, { disabled: true })], /was disabled/)) + it('an expired key', () => refused([slot(limited(5))], [limited(5, { expiresAt: NOW - 1 })], /has expired.*don't recover an account/)) + it('a key with no budget left', () => refused([slot(limited(5))], [limited(5, { remainingBudget: 0n })], /no budget left/)) + it('an unbounded key', () => refused([slot(key(5))], [key(5, { totalBudget: 1n, expiresAt: NOW + DAY })], /doesn't sign in with/)) + it('a key of a foreign group', () => refused([slot(limited(5))], [limited(5, { contractBounds: { kind: 'contractGroup', groupId: id32(99) } })], /doesn't sign in with/)) + it('a key without a budget', () => refused([slot(limited(5))], [limited(5, { totalBudget: undefined, remainingBudget: undefined })], /doesn't sign in with/)) + it('a private key that is not the key’s', () => refused([slot(limited(5), sk(6))], [limited(5)], /doesn't sign in with/)) + + it('drops planted grants and encryption keys, keeping the main key', async () => { + port.setKeys(OWNER, [limited(5), key(7), encryptionKey(9, { contractBounds: { kind: 'contractGroup', groupId: id32(15) } }), grant(10, 12)]) + await plant([slot(limited(5)), slot(grant(6, 12)), slot(key(7)), slot(grant(10, 12), sk(11)), slot(encryptionKey(9))]) + const opened = await vault.open() + expect(opened.result).toMatchObject({ keyId: 5, extra: [], encryption: null, keyIds: [5], dropped: 4 }) + }) + + it('drops a planted grant with no spending limit or no expiry, even when the key is the identity’s', async () => { + port.setKeys(OWNER, [limited(5), unlimitedGrant(6, 12), grant(7, 13, { expiresAt: undefined }), grant(8, 11)]) + await plant([slot(limited(5)), slot(unlimitedGrant(6, 12)), slot(grant(7, 13)), slot(grant(8, 11))]) + const opened = await vault.open() + expect(opened.result).toMatchObject({ keyId: 5, keyIds: [5, 8], dropped: 2 }) + expect(opened.result.extra).toEqual([{ contractId: FORGE.core, keyId: 8, wif: wifOf(8) }]) + }) + + it('returns copies: the bundle the core wipes takes nothing the sign-in keeps', () => { + const bundle = { format: FORGE_BUNDLE_FORMAT, keys: [slot(limited(5)), slot(encryptionKey(9))] } + const opened = verifyBundle(bundle, [limited(5), encryptionKey(9)], { forge: FORGE, network: NET, now: NOW }) + FORGE_BUNDLE_CODEC.wipe(bundle) + expect(bundle.keys[1]!.privateKey.every((b) => b === 0)).toBe(true) + expect(opened.encryption?.secret).toEqual(sk(9)) + expect(opened.wif).toBe(wifOf(5)) + }) +}) + +describe('a passkey that is not one of this vault’s', () => { + it('a browser-only passkey (a random 32-byte handle) only unlocks the browser that made it', async () => { + port.setKeys(OWNER, [limited(5)]) + await plant([slot(limited(5))]) + adapter.overrideNextHandle(new Uint8Array(32).fill(1)) + const e = await vault.open().catch((x: unknown) => x) + expect(e).toBeInstanceOf(PasskeyError) + expect(platformPasskeyError(e)).toMatchObject({ code: 'not-vault', message: expect.stringMatching(/only unlocks the browser that made it/) }) + }) + + it('a passkey for another network’s vault', async () => { + port.setKeys(OWNER, [limited(5)]) + await plant([slot(limited(5))]) + adapter.overrideNextHandle(userHandleFor(OWNER, id32(42))) + expect(platformPasskeyError(await vault.open().catch((x: unknown) => x))).toMatchObject({ code: 'other-vault' }) + }) +}) + +describe('the passkeys of one identity', () => { + it('are capped at 10', async () => { + port.setKeys(OWNER, [limited(5)]) + for (let i = 0; i < 10; i++) await plant([slot(limited(5))]) + const e = await vault.enroll(blank, { userName: 'x' }).catch((x: unknown) => x) + expect(platformPasskeyError(e)).toMatchObject({ code: 'too-many' }) + expect(adapter.calls.create).toHaveLength(10) + }) + + it('list as this device’s only with this device’s recipient key, and say which need an update', async () => { + const keys = [limited(5), limited(4, { disabled: true }), grant(6, 12)] + const mine = await plant([slot(limited(5)), slot(grant(6, 12))]) + const other = await plant([slot(limited(4))]) + const replaced = await plant([slot(limited(5))]) + const markers: PasskeyMarker[] = [ + { credentialId: mine.credentialId, recipientKey: mine.recipientKey, keyIds: [5, 6], addedAt: 1 }, + // An entry replaced since (another recipient key): not this device's any more. + { credentialId: replaced.credentialId, recipientKey: id32(1), keyIds: [5], addedAt: 1 }, + ] + const rows = passkeyRows({ entries: await port.list(OWNER), markers, keys, authIds: [5, 6], usableEncryptionId: null, now: NOW }) + const row = (c: Uint8Array) => rows.find((r) => r.id === credentialName(c)) + expect(row(mine.credentialId)).toMatchObject({ thisDevice: true, keyId: 5, keyState: 'live', current: true, needsUpdate: false }) + expect(row(other.credentialId)).toMatchObject({ thisDevice: false, keyId: 4, keyState: 'disabled', current: false, needsUpdate: true }) + expect(row(replaced.credentialId)).toMatchObject({ thisDevice: false, current: true, needsUpdate: false }) + // The session now holds another grant: this device's entry needs a re-seal. + expect(passkeyRows({ entries: await port.list(OWNER), markers, keys, authIds: [5], usableEncryptionId: null, now: NOW }).find((r) => r.thisDevice)?.needsUpdate).toBe(true) + }) + + it('need a re-seal for a new main key, other grants or a replaced encryption key', () => { + const m: PasskeyMarker = { credentialId: id32(1), recipientKey: id32(2), keyIds: [5, 6, 9], encryptionKeyId: 9, addedAt: 1 } + expect(needsReseal({ authKeyId: 5 }, m, [5, 6], 9)).toBe(false) + expect(needsReseal({ authKeyId: 4 }, m, [5, 6], 9)).toBe(true) + expect(needsReseal({ authKeyId: 5 }, m, [5], 9)).toBe(true) + expect(needsReseal({ authKeyId: 5 }, m, [5, 6], 10)).toBe(true) + expect(needsReseal({ authKeyId: 5 }, null, [5, 6], null)).toBe(false) + }) +}) + +describe('a WebAuthn failure', () => { + it('keeps its code through the browser adapter, in the browser vault’s words', () => { + const closed = vaultPasskeyFailure(new DOMException('The operation either timed out or was not allowed. See: https://www.w3.org/TR/webauthn-2/', 'NotAllowedError'), 'get') + expect(closed).toBeInstanceOf(PasskeyError) + expect(closed.code).toBe('cancelled') + expect(closed.message).not.toMatch(/w3\.org/) + expect(vaultPasskeyFailure(new DOMException('x', 'InvalidStateError'), 'create').code).toBe('exists') + expect(vaultPasskeyFailure(new DOMException('x', 'SecurityError'), 'create').code).toBe('unsupported') + expect(platformPasskeyError(vaultPasskeyFailure(new DOMException('x', 'SecurityError'), 'get'))).toMatchObject({ code: 'unavailable' }) + const own = new PasskeyError('no prf', 'no-prf') + expect(vaultPasskeyFailure(own, 'get')).toBe(own) + }) + + it('drops a new passkey only when it can never hold the key', () => { + expect(passkeyIsUseless(new PasskeyError('x', 'no-prf'))).toBe(true) + expect(passkeyIsUseless(new VaultError('x', 'mismatch'))).toBe(true) + expect(passkeyIsUseless(new PasskeyError('x', 'cancelled'))).toBe(false) + expect(passkeyIsUseless(new PasskeyError('x', 'timeout'))).toBe(false) + expect(passkeyIsUseless(new Error('network'))).toBe(false) + }) +}) diff --git a/forge-web/lib/auth/passkey-vault/service.ts b/forge-web/lib/auth/passkey-vault/service.ts new file mode 100644 index 000000000..b65a29991 --- /dev/null +++ b/forge-web/lib/auth/passkey-vault/service.ts @@ -0,0 +1,543 @@ +/** + * Forge's passkey vault (PLAN-passkey-vault.md §3): the vendored core's {@link PasskeyVault} with + * Forge's rules for what a passkey may hold and what an opened one may give a sign-in. + * + * What goes in a bundle, slot by slot: + * - slot 0, the session's main key: AUTHENTICATION / HIGH, bound to the dash-forge contract group, + * with a budget and an expiry (a Forge limited key, or an App Connect v2 wallet key). A key with + * no bounds, no budget or no expiry, or bound to one contract (a shipped wallet's) is never + * sealed: a passkey moves a capped session to another device, nothing more; + * - then the live per-contract wallet grants this browser holds that are budgeted AND expiring + * (never one held only to be disabled later). Entry ciphertexts are public on chain for good, so + * a leaked passkey must never yield a key with no spending limit or no expiry: a v1 wallet's + * unlimited one-contract grant stays on the device that holds it; + * - then, only when the user chose it, the identity's usable encryption key. It cannot be taken + * back from an entry already written: removing the passkey does not lock its holder out. + * Never MASTER, CRITICAL or TRANSFER keys, and never a pasted tab-only key. + * + * Opening checks every slot against the identity read fresh with proofs (`checkSlots`): HPKE + * authenticates nobody, and any live key of the owner can write an entry. A slot 0 that fails + * refuses the sign-in; a grant or encryption key that fails is dropped. + */ + +import { decodeIdentifier, base58Encode } from '../base58' +import type { Network } from '../../constants' +import { forgeContractIds, type ForgeIds } from '../../deployments' +import { APP_CONNECT_SIGNING_EXPIRY_MARGIN_MS } from '../../vendor/platform-auth/app-connect' +import { + bytesEqual, + checkSlots, + defaultPasskeyError, + KeyPurpose, + KeyType, + matchKey, + PasskeyError, + PasskeyVault, + SecurityLevel, + VaultCryptoError, + VaultError, + wipe, + type CeremonyKind, + type DropReason, + type OnChainKey, + type PasskeyAdapter, + type SlotBundle, + type SlotKey, + type VaultEntryRecord, + type VaultPort, +} from '../../vendor/platform-auth/passkey-vault' +import { passkeyFailure, type ExtraKey, type VaultSecret } from '../vault' +import { decodeWif, encodeWif } from '../wif' +import { ownMarkerFor, type PasskeyMarker } from './markers' +import { FORGE_BUNDLE_CODEC, FORGE_BUNDLE_FORMAT, FORGE_BUNDLE_MAX_KEYS, FORGE_VAULT_PROFILE, PASSKEY_VAULT_RP_NAME } from './profile' +import { credentialName } from './port' + +/** + * A key that expires within this margin is not sealed and does not sign in: a session opened on + * it could not sign anything (App Connect's last-minutes rule, `controller.ts` `writeAuth`). + */ +const PASSKEY_EXPIRY_MARGIN_MS = APP_CONNECT_SIGNING_EXPIRY_MARGIN_MS + +/** A Forge network with forge-meta, where `vaultEntry` lives. */ +export type VaultForgeIds = ForgeIds & { readonly meta: string } + +/** What the vault seals for a session: the owner and copies of its keys in slot order. */ +export interface SealableSession { + readonly ownerId: Uint8Array + readonly keys: readonly SlotKey[] + /** + * How many live wallet grants this browser holds that were left out only because they have no + * budget or no expiry (they stay on this device); the UI says so. + */ + readonly leftOut?: number +} + +/** Overwrite every private key a {@link SealableSession} holds. */ +export function wipeSession(s: SealableSession): void { + for (const k of s.keys) wipe(k.privateKey) +} + +/** What an opened passkey gives a sign-in, after the chain check: copies the caller owns. */ +export interface OpenedKeys { + /** Slot 0: the main key. */ + readonly keyId: number + readonly wif: string + /** The wallet grants that passed, each under the Forge contract it covers. */ + readonly extra: readonly ExtraKey[] + /** The encryption key, when it was sealed and passed. The caller wipes `secret`. */ + readonly encryption: { readonly keyId: number; readonly secret: Uint8Array } | null + /** Every key id that passed, in slot order (what this device's marker records). */ + readonly keyIds: readonly number[] + /** How many slots the chain check dropped (a grant since disabled, say). */ + readonly dropped: number +} + +/** Overwrite the encryption key an {@link OpenedKeys} holds (the WIFs are strings and cannot be). */ +export function wipeOpened(o: OpenedKeys | null | undefined): void { + if (o?.encryption) wipe(o.encryption.secret) +} + +/** Why a passkey flow stopped, with a stable code for the UI and copy a user can act on. */ +export type PlatformPasskeyErrorCode = + /** Not offered here (`./policy`), or the network has no forge-meta. */ + | 'unavailable' + /** This session's key may not be sealed (no budget, not group-bound, a pasted key). */ + | 'ineligible' + /** A browser-only passkey (its handle is not a vault's): unlock with it in the browser that made it. */ + | 'not-vault' + | 'other-vault' + | 'no-prf' + | 'cancelled' + | 'exists' + | 'too-many' + | 'no-entry' + /** The entry or its keys failed the checks: sign in another way. */ + | 'refused' + /** This browser already keeps a key for the identity: unlock it instead. */ + | 'held' + /** Written (or maybe written) but not visible yet: check again. */ + | 'pending' + | 'failed' + +export class PlatformPasskeyError extends Error { + constructor( + message: string, + readonly code: PlatformPasskeyErrorCode, + ) { + super(message) + this.name = 'PlatformPasskeyError' + } +} + +const SIGN_IN_ANOTHER_WAY = 'Sign in another way (your identity file, recovery phrase or wallet), then add the passkey again.' + +/** Copy for a slot 0 that failed, by why. */ +function slotZeroMessage(reason: DropReason | KeyProblem): string { + switch (reason) { + case 'missing': + return "Platform doesn't show the key this passkey holds on its identity. Try again in a minute, or sign in another way." + case 'disabled': + return `The key this passkey holds was disabled. ${SIGN_IN_ANOTHER_WAY}` + case 'expired': + return `The key this passkey holds has expired: passkeys move a session to another device, they don't recover an account. ${SIGN_IN_ANOTHER_WAY}` + case 'spent': + return `The key this passkey holds has no budget left. ${SIGN_IN_ANOTHER_WAY}` + default: + return `This passkey holds a key Dash Forge doesn't sign in with. ${SIGN_IN_ANOTHER_WAY}` + } +} + +/** + * The browser adapter's `mapError`: a WebAuthn rejection as the core's {@link PasskeyError}, so its + * code survives (a closed prompt is 'cancelled', an excluded authenticator 'exists'), worded as + * the browser vault words it (`passkeyFailure`). + */ +export function vaultPasskeyFailure(e: unknown, kind: CeremonyKind): PasskeyError { + if (e instanceof PasskeyError) return e + const coded = defaultPasskeyError(e) + const worded = passkeyFailure(e, kind) + return new PasskeyError(worded instanceof Error && worded !== e ? worded.message : coded.message, coded.code) +} + +/** + * Whether a failed confirm proves the new passkey can never hold the key (no PRF, another + * identity's or vault's handle, another credential answered): it is dropped. Anything else (a closed + * prompt, a timeout) keeps it for "Check again". + */ +export function passkeyIsUseless(e: unknown): boolean { + if (e instanceof PasskeyError) return e.code === 'no-prf' || e.code === 'not-vault' || e.code === 'other-vault' + return e instanceof VaultError && (e.code === 'mismatch' || e.code === 'other-identity') +} + +/** The core's errors in Forge's words. Anything else passes through (a failed read stays one). */ +export function platformPasskeyError(e: unknown): unknown { + if (e instanceof PlatformPasskeyError) return e + if (e instanceof PasskeyError) { + switch (e.code) { + case 'not-vault': + return new PlatformPasskeyError('This passkey only unlocks the browser that made it. Use it there, or sign in another way.', 'not-vault') + case 'other-vault': + return new PlatformPasskeyError('This passkey is for Dash Forge on another network.', 'other-vault') + case 'no-prf': + return new PlatformPasskeyError("This passkey's provider can't keep a key with it (it has no PRF support). Use another passkey provider, or sign in another way.", 'no-prf') + case 'exists': + return new PlatformPasskeyError('This device already holds a passkey for this identity.', 'exists') + case 'cancelled': + case 'timeout': + return new PlatformPasskeyError(e.message, 'cancelled') + case 'unsupported': + return new PlatformPasskeyError(e.message, 'unavailable') + default: + return new PlatformPasskeyError(e.message, 'failed') + } + } + if (e instanceof VaultError) { + switch (e.code) { + case 'too-many': + return new PlatformPasskeyError(e.message, 'too-many') + case 'no-entry': + return new PlatformPasskeyError(e.message, 'no-entry') + case 'not-visible': + return new PlatformPasskeyError("The passkey was added, but Platform doesn't show it yet. Check again in a minute.", 'pending') + case 'unknown-identity': + return new PlatformPasskeyError(`Platform doesn't show the identity this passkey names. ${SIGN_IN_ANOTHER_WAY}`, 'refused') + default: + return new PlatformPasskeyError(e.message, 'refused') + } + } + if (e instanceof VaultCryptoError) { + return new PlatformPasskeyError(`This passkey doesn't open its entry on Platform. ${SIGN_IN_ANOTHER_WAY}`, 'refused') + } + return e +} + +// --------------------------------------------------------------------------- +// Forge's key rules +// --------------------------------------------------------------------------- + +/** Why a key may not be slot 0, beyond the core's shared checks. */ +type KeyProblem = 'shape' | 'missing' | 'disabled' | 'expired' | 'spent' | 'unbound' | 'unlimited' + +const isSigningType = (type: number): boolean => type === KeyType.ECDSA_SECP256K1 || type === KeyType.ECDSA_HASH160 + +/** The shape of a key Forge signs with: AUTHENTICATION / HIGH, secp256k1 or its hash160. */ +const authShape = (k: OnChainKey): boolean => k.purpose === KeyPurpose.AUTHENTICATION && k.securityLevel === SecurityLevel.HIGH && isSigningType(k.type) + +/** Its budget is known to be spent (an unknown one is not). */ +const isSpent = (k: OnChainKey): boolean => k.remainingBudget !== undefined && k.remainingBudget <= 0n + +function groupBound(k: OnChainKey, forge: ForgeIds): boolean { + return k.contractBounds?.kind === 'contractGroup' && bytesEqual(k.contractBounds.groupId, decodeIdentifier(forge.group)) +} + +/** A budget and an expiry were set on the key: the only extra keys a passkey may hold. */ +const isLimited = (k: OnChainKey): boolean => k.totalBudget !== undefined && k.expiresAt !== undefined + +const expiring = (k: OnChainKey, now: number): boolean => k.expiresAt !== undefined && k.expiresAt - now <= PASSKEY_EXPIRY_MARGIN_MS + +/** + * Why `k` cannot be a passkey's main key (slot 0), or null: a live AUTHENTICATION / HIGH key bound + * to Forge's contract group, with a budget left and an expiry still ahead. + */ +function mainKeyProblem(k: OnChainKey | undefined, forge: ForgeIds, now: number): KeyProblem | null { + if (k === undefined) return 'missing' + if (!authShape(k)) return 'shape' + if (k.disabled) return 'disabled' + if (k.totalBudget === undefined || k.expiresAt === undefined) return 'unlimited' + if (!groupBound(k, forge)) return 'unbound' + if (expiring(k, now)) return 'expired' + if (isSpent(k)) return 'spent' + return null +} + +/** + * The Forge contract (base58) a wallet grant signs for, or null when it may not be sealed: bound + * to one Forge contract (a shipped wallet's grant) or to Forge's group. Never an unbounded key, nor + * one bound to a document type or to another app's contract. + */ +function grantContract(k: OnChainKey, forge: ForgeIds): string | null { + const b = k.contractBounds + if (b?.kind === 'contractGroup') return groupBound(k, forge) ? forge.core : null + if (b?.kind !== 'singleContract') return null + const id = base58Encode(b.contractId) + return forgeContractIds(forge).includes(id) ? id : null +} + +/** + * Whether `k` is an encryption key Forge's private repos use (`../encryption-key` + * `isUsableEncryptionKey`): ENCRYPTION / MEDIUM, secp256k1, enabled, unbound or bound to forge-core. + */ +function usableEncryption(k: OnChainKey, forge: ForgeIds): boolean { + if (k.purpose !== KeyPurpose.ENCRYPTION || k.securityLevel !== SecurityLevel.MEDIUM || k.type !== KeyType.ECDSA_SECP256K1 || k.disabled) return false + const b = k.contractBounds + return b === undefined || (b.kind !== 'contractGroup' && base58Encode(b.contractId) === forge.core) +} + +/** The identity's usable encryption key (the highest id, as writers pick it), or null. */ +export function usableEncryptionKeyOf(keys: readonly OnChainKey[], forge: ForgeIds): OnChainKey | null { + return keys.filter((k) => usableEncryption(k, forge)).reduce((best, k) => (best === null || k.id > best.id ? k : best), null) +} + +/** Forge's rule for a slot that passed the core's checks (shape, live, unexpired, budget, match). */ +function acceptSlot(slot: Readonly, k: OnChainKey, index: number, forge: ForgeIds, now: number): boolean { + if (index === 0) return mainKeyProblem(k, forge, now) === null + if (slot.purpose === KeyPurpose.AUTHENTICATION) return authShape(k) && isLimited(k) && grantContract(k, forge) !== null + return usableEncryption(k, forge) +} + +/** + * The chain check of an opened bundle: every slot against the owner's keys read with proofs. A + * slot 0 that fails throws (`VaultError` 'refused', in Forge's words); anything else that fails is + * dropped. Returns copies: the core wipes the bundle as soon as this returns. + */ +export function verifyBundle(bundle: SlotBundle, keys: readonly OnChainKey[], o: { forge: ForgeIds; network: Network; now: number }): OpenedKeys { + const { forge, network, now } = o + const { accepted, dropped } = checkSlots(bundle.keys, keys, { now, expiryMarginMs: PASSKEY_EXPIRY_MARGIN_MS, accept: (slot, k, index) => acceptSlot(slot, k, index, forge, now) }) + const main = accepted.find((a) => a.index === 0) + if (main === undefined) { + const failed = dropped.find((d) => d.index === 0) + const onChain = keys.find((k) => k.id === bundle.keys[0]?.keyId) + const reason = failed?.reason === 'rule' ? (mainKeyProblem(onChain, forge, now) ?? 'shape') : (failed?.reason ?? 'missing') + throw new VaultError(slotZeroMessage(reason), 'refused') + } + const extra: ExtraKey[] = [] + let encryption: OpenedKeys['encryption'] = null + try { + for (const a of accepted) { + if (a.index === 0) continue + if (a.slot.purpose === KeyPurpose.ENCRYPTION) encryption = { keyId: a.slot.keyId, secret: a.slot.privateKey.slice() } + else extra.push({ contractId: grantContract(a.key, forge)!, keyId: a.slot.keyId, wif: encodeWif(a.slot.privateKey, network) }) + } + return { + keyId: main.slot.keyId, + wif: encodeWif(main.slot.privateKey, network), + extra, + encryption, + keyIds: accepted.map((a) => a.slot.keyId), + dropped: dropped.length, + } + } catch (error) { + wipe(encryption?.secret) + throw error + } +} + +// --------------------------------------------------------------------------- +// What a session seals +// --------------------------------------------------------------------------- + +/** Copy for a main key that may not be sealed, by why. */ +function ineligibleMessage(problem: KeyProblem): string { + switch (problem) { + case 'unbound': + return "This sign-in's key isn't bound to Dash Forge's current contracts, so it can't be kept with a passkey. Renew it with your identity file or recovery phrase, then try again." + case 'unlimited': + return "This sign-in's key has no spending limit or expiry, so it can't be kept with a passkey. Renew it with your identity file or recovery phrase, or sign in with a wallet that grants a limited key, then try again." + case 'expired': + case 'spent': + return "This sign-in's key has expired or has no budget left. Renew or top it up first." + case 'missing': + return "Platform doesn't show this sign-in's key yet. Try again in a minute." + default: + return "This sign-in's key can't be kept with a passkey." + } +} + +/** + * The wallet grants one bundle holds: one per Forge contract. With slot 0 and the encryption key + * that fills the format's six slots. + */ +const MAX_GRANTS = FORGE_BUNDLE_MAX_KEYS - 2 + +/** The private key of `wif`, when it is `k`'s; null (and nothing left in memory) otherwise. */ +function privateKeyOf(wif: string, k: OnChainKey): Uint8Array | null { + let sk: Uint8Array + try { + sk = decodeWif(wif).privateKey + } catch { + return null + } + if (matchKey(sk, k)) return sk + wipe(sk) + return null +} + +const slotOf = (k: OnChainKey, privateKey: Uint8Array): SlotKey => ({ purpose: k.purpose, securityLevel: k.securityLevel, keyType: k.type, keyId: k.id, privateKey }) + +/** + * The keys a session seals, checked against the identity's keys read just now: slot 0 the main + * key (throws {@link PlatformPasskeyError} 'ineligible' when it may not be), then each live wallet + * grant this browser holds that Forge would sign with and that has a budget and an expiry (at most + * {@link MAX_GRANTS}, in the vault's order, newest first), then the encryption key when given (it must be the identity's usable one). The caller wipes the + * result ({@link wipeSession}) and its own `encryption.secret`. + */ +export function sealableSession(o: { + readonly ownerId: Uint8Array + readonly secret: VaultSecret + readonly keys: readonly OnChainKey[] + readonly forge: ForgeIds + readonly now: number + readonly encryption?: { readonly keyId: number; readonly secret: Uint8Array } | null +}): SealableSession { + const { secret, keys, forge, now } = o + const byId = (id: number) => keys.find((k) => k.id === id) + const main = byId(secret.keyId) + const problem = secret.keyId < 0 ? 'shape' : mainKeyProblem(main, forge, now) + if (problem !== null || main === undefined) throw new PlatformPasskeyError(ineligibleMessage(problem ?? 'missing'), 'ineligible') + const mainSk = privateKeyOf(secret.wif, main) + if (mainSk === null) throw new PlatformPasskeyError(ineligibleMessage('shape'), 'ineligible') + const slots: SlotKey[] = [slotOf(main, mainSk)] + let encryption: SlotKey | null = null + let leftOut = 0 + try { + if (o.encryption) { + const k = byId(o.encryption.keyId) + const usable = usableEncryptionKeyOf(keys, forge) + const sk = o.encryption.secret.slice() + if (k === undefined || usable?.id !== k.id || !matchKey(sk, k)) { + wipe(sk) + throw new PlatformPasskeyError("The encryption key this browser holds isn't your identity's current one, so it can't be added. Import the current one in Settings first.", 'ineligible') + } + encryption = slotOf(k, sk) + } + for (const e of secret.extra ?? []) { + if (slots.length > MAX_GRANTS || e.holdOnly) continue + const k = byId(e.keyId) + if (k === undefined || slots.some((s) => s.keyId === k.id)) continue + if (!authShape(k) || k.disabled || expiring(k, now) || isSpent(k) || grantContract(k, forge) === null) continue + // Budgeted AND expiring only: this entry's ciphertext is public for good. + if (!isLimited(k)) { + leftOut += 1 + continue + } + const sk = privateKeyOf(e.wif, k) + if (sk !== null) slots.push(slotOf(k, sk)) + } + } catch (error) { + for (const s of slots) wipe(s.privateKey) + wipe(encryption?.privateKey) + throw error + } + return { ownerId: o.ownerId.slice(), keys: encryption ? [...slots, encryption] : slots, ...(leftOut > 0 ? { leftOut } : {}) } +} + +// --------------------------------------------------------------------------- +// The vault +// --------------------------------------------------------------------------- + +export type ForgePasskeyVault = PasskeyVault + +export interface ForgePasskeyVaultOptions { + readonly port: VaultPort + readonly adapter: PasskeyAdapter + readonly rpId: string + readonly forge: VaultForgeIds + readonly network: Network + readonly now?: () => number + readonly sleep?: (ms: number) => Promise +} + +/** Forge's passkey vault: entries in forge-meta, Forge's profile, Forge's chain check. */ +export function forgePasskeyVault(o: ForgePasskeyVaultOptions): ForgePasskeyVault { + const now = o.now ?? Date.now + return new PasskeyVault({ + profile: FORGE_VAULT_PROFILE, + codec: FORGE_BUNDLE_CODEC, + port: o.port, + adapter: o.adapter, + rpId: o.rpId, + rpName: PASSKEY_VAULT_RP_NAME, + contractId: decodeIdentifier(o.forge.meta), + ownerOf: (s) => s.ownerId, + bundleFor: (s) => ({ format: FORGE_BUNDLE_FORMAT, keys: s.keys.map((k) => ({ ...k, privateKey: k.privateKey.slice() })) }), + verify: (bundle, keys, ctx) => verifyBundle(bundle, keys, { forge: o.forge, network: o.network, now: ctx.now }), + now, + ...(o.sleep ? { sleep: o.sleep } : {}), + }) +} + +// --------------------------------------------------------------------------- +// Listing +// --------------------------------------------------------------------------- + +/** The state of the key an entry names, as the identity shows it now. */ +export type PasskeyKeyState = 'live' | 'disabled' | 'expired' | 'missing' + +/** One passkey of the identity, for Settings → Devices & keys. No key material. */ +export interface PlatformPasskeyRow { + /** The credential id, base64url: what remove and re-seal take. */ + readonly id: string + /** When the entry was written (ms), when Platform says. */ + readonly addedAt: number | null + readonly updatedAt: number | null + /** This device made it, or signed in with it. */ + readonly thisDevice: boolean + /** The key it holds (slot 0). */ + readonly keyId: number + readonly keyState: PasskeyKeyState + /** It holds this session's key. */ + readonly current: boolean + /** It holds an older key or other keys than this session's: re-seal it ("Needs update"). */ + readonly needsUpdate: boolean + /** It also holds the encryption key (known for this device's passkeys only). */ + readonly encryptionKey: boolean +} + +function keyState(k: OnChainKey | undefined, now: number): PasskeyKeyState { + if (k === undefined) return 'missing' + if (k.disabled) return 'disabled' + return k.expiresAt !== undefined && k.expiresAt <= now ? 'expired' : 'live' +} + +const sameIds = (a: readonly number[], b: readonly number[]): boolean => a.length === b.length && a.every((x, i) => x === b[i]) + +/** The auth key ids a marker recorded (its encryption key left out). */ +const markedAuthIds = (m: PasskeyMarker): number[] => m.keyIds.filter((id) => id !== m.encryptionKeyId) + +/** + * Whether this device's own entry should be re-sealed for the session that now holds `authIds` + * (slot 0 first): it names another main key, holds other grants, or holds an encryption key that + * is no longer the identity's usable one. + */ +export function needsReseal(entry: Pick, marker: PasskeyMarker | null, authIds: readonly number[], usableEncryptionId: number | null): boolean { + if (entry.authKeyId !== authIds[0]) return true + if (marker === null) return false + return !sameIds(markedAuthIds(marker), authIds) || (marker.encryptionKeyId !== undefined && marker.encryptionKeyId !== usableEncryptionId) +} + +/** + * The rows for the identity's entries: `markers` say which are this device's (only when their + * recipient key is the entry's: a replaced entry is no longer the passkey this device made), and + * `authIds` are the key ids this session would seal (slot 0 first), or just its main key's when + * the rest is locked. + */ +export function passkeyRows(o: { + readonly entries: readonly VaultEntryRecord[] + readonly markers: readonly PasskeyMarker[] + readonly keys: readonly OnChainKey[] + readonly authIds: readonly number[] + /** Only `authIds[0]` is known (the rest of the vault is locked): only the main key is compared. */ + readonly mainOnly?: boolean + readonly usableEncryptionId: number | null + readonly now: number +}): PlatformPasskeyRow[] { + return o.entries + .map((e) => { + const m = ownMarkerFor(o.markers, e) + return { + id: credentialName(e.credentialId), + addedAt: e.createdAt ?? null, + updatedAt: e.updatedAt ?? null, + thisDevice: m !== null, + keyId: e.authKeyId, + keyState: keyState( + o.keys.find((k) => k.id === e.authKeyId), + o.now, + ), + current: e.authKeyId === o.authIds[0], + needsUpdate: needsReseal(e, o.mainOnly === true ? null : m, o.authIds, o.usableEncryptionId), + encryptionKey: m?.encryptionKeyId !== undefined, + } + }) + .sort((a, b) => (b.addedAt ?? 0) - (a.addedAt ?? 0)) +} diff --git a/forge-web/lib/auth/vault.ts b/forge-web/lib/auth/vault.ts index 7fde6e102..5bf79d9a6 100644 --- a/forge-web/lib/auth/vault.ts +++ b/forge-web/lib/auth/vault.ts @@ -156,15 +156,17 @@ interface VaultRecord { /** * Where a stored key came from, when this browser did not register it with the master key: - * `dg` (`dg auth keys add --for-browser`, `./key-handoff`) or `app-connect` (a wallet's App - * Connect v2 grant, `./app-connect-v2`). A key this browser registers itself has none; storing - * one (a renewal with the identity file or recovery phrase) clears it. + * `dg` (`dg auth keys add --for-browser`, `./key-handoff`), `app-connect` (a wallet's App + * Connect v2 grant, `./app-connect-v2`) or `passkey` (restored from a passkey on Platform + * (`./passkey-vault`): a passkey does not say whether a wallet or the master key made the key, so + * it can be renewed either way). A key this browser registers itself has none; storing one (a + * renewal with the identity file or recovery phrase) clears it. */ -export type KeyOrigin = 'dg' | 'app-connect' +export type KeyOrigin = 'dg' | 'app-connect' | 'passkey' /** Whether a stored value is a {@link KeyOrigin} (records and kept hints are read back unchecked). */ export function isKeyOrigin(v: unknown): v is KeyOrigin { - return v === 'dg' || v === 'app-connect' + return v === 'dg' || v === 'app-connect' || v === 'passkey' } /** What the UI may know about a stored vault (no secrets). */ diff --git a/forge-web/lib/layout.test.ts b/forge-web/lib/layout.test.ts index dc13057f2..1047aed50 100644 --- a/forge-web/lib/layout.test.ts +++ b/forge-web/lib/layout.test.ts @@ -28,12 +28,19 @@ const OLD_HOME: Readonly> = { profile: 'COMMUNITY', follow: 'COMMUNITY', } +// UPDATE-2 (the passkey vault): in forge-meta only; the three-contract set has no home for it. +const FOUR_CONTRACT_ONLY: ReadonlySet = new Set(['vaultEntry']) describe('the layout follows the deployment record', () => { - it('forge-meta holds the seven moved types only on a four-contract set', () => { - expect([...META_TYPES].sort()).toEqual(Object.keys(OLD_HOME).sort()) + it('forge-meta holds the seven moved types, and vaultEntry, only on a four-contract set', () => { + expect([...META_TYPES].sort()).toEqual([...Object.keys(OLD_HOME), ...FOUR_CONTRACT_ONLY].sort()) for (const t of META_TYPES) { - expect(contractOf(THREE, t), t).toBe(OLD_HOME[t]) + if (FOUR_CONTRACT_ONLY.has(t)) { + expect(() => contractOf(THREE, t), t).toThrow(/no Forge contract holds/) + expect(contractKindOfType(t, THREE), t).toBeNull() + } else { + expect(contractOf(THREE, t), t).toBe(OLD_HOME[t]) + } expect(contractOf(FOUR, t), t).toBe('META') expect(writeContractKind(FOUR, t), t).toBe('meta') // Without the network's ids the answer is the three-contract home. diff --git a/forge-web/lib/layout.ts b/forge-web/lib/layout.ts index 7a018707d..0924ad4a7 100644 --- a/forge-web/lib/layout.ts +++ b/forge-web/lib/layout.ts @@ -8,7 +8,8 @@ * (`stamp_vis_for`, the contract check in `Collab::write`). * * DESIGN rev 4.1 D44 adds a fourth contract, forge-meta: `repoKey`, `ban`, `label`, `topic`, - * `packMirror`, `profile` and `follow` ({@link META_TYPES}) move there. The deployment record + * `packMirror`, `profile` and `follow` ({@link META_TYPES}) move there, and `vaultEntry` (UPDATE-2, + * the passkey vault) exists there only. The deployment record * says which layout a network has (`v2.forgeMeta`, `ForgeIds.meta`), so one build serves * sakura's three-contract set and four-contract sets: pass the network's ids to * {@link contractKindOfType}; without them it answers the three-contract home. @@ -69,10 +70,21 @@ export const COMMUNITY_TYPES: ReadonlySet = typesOf('community') /** * The types forge-meta holds on a four-contract set (D44). None is read by a rule, total or - * derived index of its old contract, so the move changes no consensus rule. Parity: forge-core + * derived index of its old contract, so the move changes no consensus rule. `vaultEntry` is the + * exception: it has no three-contract home (`build.py` builds it with the four-contract layout + * only), so on a network without forge-meta no contract holds it. Parity: forge-core * `layout::META_TYPES`. */ -export const META_TYPES: ReadonlySet = new Set(['repoKey', 'ban', 'label', 'topic', 'packMirror', 'profile', 'follow']) +export const META_TYPES: ReadonlySet = new Set([ + 'repoKey', + 'ban', + 'label', + 'topic', + 'packMirror', + 'profile', + 'follow', + 'vaultEntry', +]) /** * The contract that holds `type` on the network `forge` describes: forge-meta for diff --git a/forge-web/lib/repo/contract.ts b/forge-web/lib/repo/contract.ts index 829ce5e40..782374f1a 100644 --- a/forge-web/lib/repo/contract.ts +++ b/forge-web/lib/repo/contract.ts @@ -51,6 +51,8 @@ export const DOC = { profile: 'profile', runner: 'runner', topic: 'topic', + /** A passkey-sealed copy of a session's keys (forge-meta only; `lib/auth/passkey-vault`). */ + vaultEntry: 'vaultEntry', } as const export { withVis } from '../layout' diff --git a/forge-web/lib/sdk/cost.test.ts b/forge-web/lib/sdk/cost.test.ts index 93b0ed0b9..adb1eda46 100644 --- a/forge-web/lib/sdk/cost.test.ts +++ b/forge-web/lib/sdk/cost.test.ts @@ -367,3 +367,13 @@ describe('testnet ECON-05 refund previews', () => { expect(-previewDelete(type as string).credits).toBeLessThanOrEqual(refunded as number) }) }) + +describe('a passkey entry (vaultEntry, not measured yet)', () => { + // Yappr's sakura figures (PLAN-passkey-vault.md §2): 28–31M later, 46–50M first, refunds 23–35M; + // Forge's longer ciphertext adds about 2–4M. Re-measured by the live test. + it('is priced above the estimates and refunds no more than their low end', () => { + expect(previewCreate('vaultEntry', {}, S).credits).toBeGreaterThanOrEqual(31_000_000 + 4_000_000) + expect(previewCreate('vaultEntry', {}, { ...S, author: true }).credits).toBeGreaterThanOrEqual(50_000_000 + 4_000_000) + expect(-previewDelete('vaultEntry').credits).toBeLessThanOrEqual(23_000_000) + }) +}) diff --git a/forge-web/lib/sdk/cost.ts b/forge-web/lib/sdk/cost.ts index 5c402a23e..68b55b08d 100644 --- a/forge-web/lib/sdk/cost.ts +++ b/forge-web/lib/sdk/cost.ts @@ -136,6 +136,10 @@ export const BASE_CREDITS: Readonly> = { // ECON-05: short profile create 31.62M as the member's first forge-meta write. // Its contract nonce is priced separately by CONTRACT_FIRST_CREDITS. profile: 24_000_000, + // UPDATE-2 (the passkey vault): not measured yet. Yappr's entries on sakura paid 28–31M later and + // 46–50M first; Forge's 256-byte ciphertext is 80–160 bytes longer (≈2–4M). Its byte fields are + // in the base (they are not text). Re-measure with the live test. + vaultEntry: 34_000_000, } /** @@ -210,6 +214,8 @@ export const FIRST_WRITE_CREDITS: Readonly> = { protectedRefUpdate: { target: 7_000_000, repo: 23_000_000 }, packManifest: { repo: 47_000_000 }, packMirror: { repo: 16_000_000 }, + // The owner's first entry builds its `byCredential` subtree (Yappr: 46–50M first vs 28–31M). + vaultEntry: { author: 17_000_000 }, } /** @@ -288,6 +294,8 @@ export const DELETE_CREDITS: Readonly> = { webhook: -65_000_000, // ECON-05: a short profile delete refunded 17.25M. profile: -16_000_000, + // UPDATE-2: Yappr's entry deletes refunded about 23–35M; the low end until Forge's are measured. + vaultEntry: -23_000_000, } /** diff --git a/forge-web/lib/vendor/platform-auth/VENDORED.json b/forge-web/lib/vendor/platform-auth/VENDORED.json index 5d1f79989..208864758 100644 --- a/forge-web/lib/vendor/platform-auth/VENDORED.json +++ b/forge-web/lib/vendor/platform-auth/VENDORED.json @@ -30,6 +30,43 @@ "verify.ts": "sha256-5272d8263e7efe719fab01e114785a867580e0d6785e66fdd92baa0bc10e5f72" }, "ref": "feat/app-connect-module" + }, + "passkey-vault": { + "commit": "dbd9a4fd27f772051b1ec5853a298a6fb7a07f7e", + "dirty": false, + "externals": [ + "@noble/ciphers", + "@noble/curves", + "@noble/hashes" + ], + "files": { + "__fixtures__/fake-passkey.ts": "sha256-d043f81181bbb39d5c77e574283f2278c0de32fc6cfeaea128dc7d6c50022cad", + "__fixtures__/memory-port.ts": "sha256-05f63180216fc6ceb7e30605c715e10b9537eadb25c990d8284968bba68dca9c", + "__fixtures__/profiles.ts": "sha256-a4813c7f654cea974dcc01d3e109f73b74dd1ac82688dc76aaf312c1f53429e5", + "__fixtures__/vectors.ts": "sha256-4ecd01661c50f46ad3c02760ffdbb4984cbf734faa5f13f6860c6526580ea0f1", + "__vectors__/forge.json": "sha256-4aae584c5493d5cf1b20f7a82d587bf28dbd1fd38887c62f62652ed4081489e1", + "__vectors__/generate.py": "sha256-b222d5c1e15e4efdc633b5b92486d1205b8c8d3e76cf44093aa357b1cb2fed9d", + "__vectors__/govhub.json": "sha256-ce67759e25cd5e6f368d3a1c8978a3c0ec54df17d11d9376f5ec016721d402aa", + "__vectors__/yappr.json": "sha256-81d6a989761c6c5251010c0d6f2527cf6baef6714c8a20180223cd4cd40716a4", + "bytes.ts": "sha256-e24ad247ffff805318c6e193e487f4678f026b7b8ac53e7d13a4910ebc74cb86", + "codecs.test.ts": "sha256-0b9e989118dd844d0553a4c80adc752cefb216931f32b79e8e165dd0e8a7b441", + "codecs.ts": "sha256-27cae3d3fbba28d23b38a343df0936c135f7fa888a7b7a0fa58ee465cd1a8bc3", + "entry.test.ts": "sha256-bedd312f457347eb4e06eaa0870f7e24384f7ed358493e284dc255e2eeef8983", + "entry.ts": "sha256-8c955f8ab5813d608556e39a5767609ac86228558bc10f9e56d9a78b49e5953f", + "errors.ts": "sha256-2da40dc2c024022374ca671f9f1517078c0b473117279911fe0ea408d1ea6ba6", + "hpke.test.ts": "sha256-bbaca9878ecee0fb964fdb5af3c53d2e4aeec8f7f8b3441f24496dfe9a0731b7", + "hpke.ts": "sha256-2820e7d2884e9a6e3ba461f1205a6b7973d1dc7dfb9d98284a8c07cf8badb8ba", + "index.ts": "sha256-97cd1f5f666f7e8f9b954472de9756f6a8fc7fafa84194361113acf997a47606", + "port.ts": "sha256-3b13eac8fd82c486a7090adb9c6d6f08ae8eb91e863a579fd9517734f564afb2", + "profile.ts": "sha256-80b8691740f08d34d342c7f8e25f0778c867607919527bbea9661379e3da45c7", + "user-handle.ts": "sha256-d2520559afe26077e3e723ae17d2ebe3edc2429f15f0eb228cf1581ea40cada2", + "vault.test.ts": "sha256-7324d4e2232955034e61cc02ac01b24c0dc6a60d57d708e8991cd4c2fc7dc2f5", + "vault.ts": "sha256-7ba9d297e484f3afa6f0759e8b8ad61620afc293104e9356d1c8359e29464577", + "verify.ts": "sha256-9acfde947c3c82de07e655960e3efde3a03990a095cb5e77aba75c18eb45222b", + "webauthn.test.ts": "sha256-7fd846a4728959f37108ec160313145762ecbf36d9b65c14e3536a804d33327a", + "webauthn.ts": "sha256-636e14708d0113e5131ff2bbb9083f4dcfdb9363a029f0a884518a4cca9f09b3" + }, + "ref": "feat/passkey-vault" } }, "note": "Owned by this repo, free to diverge. Run platform-auth tools/vendor.mjs status .", diff --git a/forge-web/lib/vendor/platform-auth/passkey-vault/__fixtures__/fake-passkey.ts b/forge-web/lib/vendor/platform-auth/passkey-vault/__fixtures__/fake-passkey.ts new file mode 100644 index 000000000..aa272eff3 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/passkey-vault/__fixtures__/fake-passkey.ts @@ -0,0 +1,131 @@ +// A software authenticator for tests: PRF = HMAC-SHA256(credential secret, input). Discoverable credentials, exclude lists, +// allow lists, PRF at create or only at get, no PRF at all, and scripted failures. +import { hmac } from '@noble/hashes/hmac.js' +import { sha256 } from '@noble/hashes/sha2.js' +import { bytesEqual, randomBytes } from '../bytes' +import { PasskeyError } from '../errors' +import type { CreatePasskeyOptions, GetPasskeyOptions, PasskeyAdapter } from '../webauthn' + +export interface FakeCredential { + rpId: string + credentialId: Uint8Array + userHandle: Uint8Array + userName: string + secret: Uint8Array +} + +export interface FakePasskeyOptions { + /** The authenticator evaluates PRF at all (default true). */ + prf?: boolean + /** It also returns the PRF output at creation (default false: many only give it on get). */ + prfAtCreate?: boolean + /** Credential id length (default 32). */ + credentialIdLength?: number + /** + * Each create is on another authenticator (a phone, a laptop, a security key), all reachable from this browser: no exclude-list + * refusal and no replacement by user handle. Default false (one authenticator). + */ + multiDevice?: boolean +} + +export interface FakePasskeyAdapter extends PasskeyAdapter { + readonly credentials: FakeCredential[] + /** Credentials the adapter was told are unknown. */ + readonly signalled: Uint8Array[] + readonly calls: { create: CreatePasskeyOptions[]; get: GetPasskeyOptions[] } + /** The credential a discoverable get picks next (default: the last created for the RP). */ + choose(credentialId: Uint8Array | null): void + /** The next create or get rejects with this. */ + failNext(error: unknown): void + /** The next get returns this user handle instead of the credential's. */ + overrideNextHandle(handle: Uint8Array | null): void + /** The PRF output this credential gives for `input` (what the authenticator would). */ + prfOf(credentialId: Uint8Array, input: Uint8Array): Uint8Array + options: FakePasskeyOptions +} + +export function fakePasskeyAdapter(options: FakePasskeyOptions = {}): FakePasskeyAdapter { + const credentials: FakeCredential[] = [] + const signalled: Uint8Array[] = [] + const calls = { create: [] as CreatePasskeyOptions[], get: [] as GetPasskeyOptions[] } + let chosen: Uint8Array | null = null + let failure: { error: unknown } | null = null + let handleOverride: { handle: Uint8Array | null } | null = null + + const takeFailure = () => { + if (!failure) return + const { error } = failure + failure = null + throw error + } + const find = (id: Uint8Array) => credentials.find((c) => bytesEqual(c.credentialId, id)) + const prf = (c: FakeCredential, input: Uint8Array) => hmac(sha256, c.secret, input) + + const adapter: FakePasskeyAdapter = { + credentials, + signalled, + calls, + options, + choose(id) { + chosen = id + }, + failNext(error) { + failure = { error } + }, + overrideNextHandle(handle) { + handleOverride = { handle } + }, + prfOf(id, input) { + const c = find(id) + if (!c) throw new Error('no such credential') + return prf(c, input) + }, + + async create(o) { + calls.create.push(o) + takeFailure() + if (!options.multiDevice && credentials.some((c) => c.rpId === o.rpId && o.exclude.some((id) => bytesEqual(id, c.credentialId)))) { + throw new PasskeyError('This authenticator already holds a passkey for this account.', 'exists') + } + // providers replace a discoverable credential with the same RP and user handle + for (let i = credentials.length - 1; i >= 0 && !options.multiDevice; i -= 1) { + const c = credentials[i] + if (c && c.rpId === o.rpId && bytesEqual(c.userHandle, o.userHandle)) credentials.splice(i, 1) + } + const c: FakeCredential = { + rpId: o.rpId, + credentialId: randomBytes(options.credentialIdLength ?? 32), + userHandle: o.userHandle.slice(), + userName: o.userName, + secret: randomBytes(32), + } + credentials.push(c) + const supports = options.prf ?? true + return { + credentialId: c.credentialId.slice(), + prfOutput: supports && options.prfAtCreate ? prf(c, o.prfInput) : null, + prfEnabled: supports, + } + }, + + async get(o) { + calls.get.push(o) + takeFailure() + const candidates = credentials.filter((c) => c.rpId === o.rpId && (o.allow.length === 0 || o.allow.some((id) => bytesEqual(id, c.credentialId)))) + const c = (chosen && candidates.find((x) => bytesEqual(x.credentialId, chosen as Uint8Array))) || candidates[candidates.length - 1] + chosen = null + if (!c) throw new PasskeyError('The passkey prompt was closed or timed out.', 'cancelled') + if (!(options.prf ?? true)) throw new PasskeyError("This passkey's provider doesn't support the PRF extension.", 'no-prf', c.credentialId.slice()) + const userHandle = handleOverride ? handleOverride.handle : c.userHandle.slice() + handleOverride = null + return { credentialId: c.credentialId.slice(), userHandle, prfOutput: prf(c, o.prfInput) } + }, + + async signalUnknown(rpId, credentialId) { + signalled.push(credentialId.slice()) + const i = credentials.findIndex((c) => c.rpId === rpId && bytesEqual(c.credentialId, credentialId)) + if (i >= 0) credentials.splice(i, 1) + }, + } + return adapter +} diff --git a/forge-web/lib/vendor/platform-auth/passkey-vault/__fixtures__/memory-port.ts b/forge-web/lib/vendor/platform-auth/passkey-vault/__fixtures__/memory-port.ts new file mode 100644 index 000000000..c839012db --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/passkey-vault/__fixtures__/memory-port.ts @@ -0,0 +1,80 @@ +// An in-memory VaultPort with the contract's rules: one entry per (owner, credential), credentialId and recipientKey immutable, +// replace only the revision read. Optional read lag (a node a block behind) and a log of writes. +import { bytesEqual } from '../bytes' +import type { SealedVaultEntry } from '../entry' +import type { OnChainKey, VaultEntryRecord, VaultPort } from '../port' + +const hex = (b: Uint8Array) => Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('') +const clone = (e: VaultEntryRecord): VaultEntryRecord => ({ + ...e, + ownerId: e.ownerId.slice(), + credentialId: e.credentialId.slice(), + recipientKey: e.recipientKey.slice(), + enc: e.enc.slice(), + sealed: e.sealed.slice(), +}) + +export class MemoryVaultPort implements VaultPort { + entries: VaultEntryRecord[] = [] + readonly identities = new Map() + readonly writes: Array<{ op: 'create' | 'replace' | 'delete'; credentialId: Uint8Array }> = [] + /** byCredential misses this many reads after each write. */ + lag = 0 + #lagLeft = 0 + #clock = 1_700_000_000_000 + #ids = 0 + + setKeys(ownerId: Uint8Array, keys: OnChainKey[]): void { + this.identities.set(hex(ownerId), keys) + } + + /** Writes an entry directly, as any holder of a live key of the owner could (a planted entry). */ + plant(ownerId: Uint8Array, entry: SealedVaultEntry): VaultEntryRecord { + const record: VaultEntryRecord = { ...entry, ownerId: ownerId.slice(), documentId: `doc${++this.#ids}`, revision: 1, createdAt: this.#clock, updatedAt: this.#clock } + this.entries.push(record) + return clone(record) + } + + #find(ownerId: Uint8Array, credentialId: Uint8Array) { + return this.entries.find((e) => bytesEqual(e.ownerId, ownerId) && bytesEqual(e.credentialId, credentialId)) + } + + async list(ownerId: Uint8Array) { + return this.entries.filter((e) => bytesEqual(e.ownerId, ownerId)).map(clone) + } + + async byCredential(ownerId: Uint8Array, credentialId: Uint8Array) { + if (this.#lagLeft > 0) { + this.#lagLeft -= 1 + return null + } + const e = this.#find(ownerId, credentialId) + return e ? clone(e) : null + } + + async identityKeys(ownerId: Uint8Array) { + return this.identities.get(hex(ownerId))?.map((k) => ({ ...k })) ?? null + } + + async put(o: { ownerId: Uint8Array; entry: SealedVaultEntry; existing: VaultEntryRecord | null }) { + const current = this.#find(o.ownerId, o.entry.credentialId) + this.#clock += 1000 + if (!o.existing) { + if (current) throw new Error('duplicate unique index byCredential') + this.plant(o.ownerId, o.entry) + this.writes.push({ op: 'create', credentialId: o.entry.credentialId.slice() }) + } else { + if (!current || current.revision !== o.existing.revision) throw new Error('the document changed since it was read') + if (!bytesEqual(current.recipientKey, o.entry.recipientKey)) throw new Error('recipientKey is immutable') + Object.assign(current, { ...o.entry, ownerId: current.ownerId, revision: (current.revision ?? 1) + 1, updatedAt: this.#clock }) + this.writes.push({ op: 'replace', credentialId: o.entry.credentialId.slice() }) + } + this.#lagLeft = this.lag + } + + async remove(o: { ownerId: Uint8Array; entry: VaultEntryRecord }) { + const before = this.entries.length + this.entries = this.entries.filter((e) => !(bytesEqual(e.ownerId, o.ownerId) && bytesEqual(e.credentialId, o.entry.credentialId))) + if (this.entries.length !== before) this.writes.push({ op: 'delete', credentialId: o.entry.credentialId.slice() }) + } +} diff --git a/forge-web/lib/vendor/platform-auth/passkey-vault/__fixtures__/profiles.ts b/forge-web/lib/vendor/platform-auth/passkey-vault/__fixtures__/profiles.ts new file mode 100644 index 000000000..2c6c5c353 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/passkey-vault/__fixtures__/profiles.ts @@ -0,0 +1,93 @@ +// The three apps' profiles, as the test vectors pin them. Yappr's and govhub's reproduce the bytes those apps write today; Forge's is +// the new one (PLAN-passkey-vault.md §1). The `allow`/`check` rules are each app's own and do not change any bytes; the ids, lengths, +// key counts and labels do. +import { slotKeysCodec, seedCodec, votingKeysCodec, type SeedBundle, type SlotBundle, type SlotKey, type VotingKeysBundle } from '../codecs' +import { KeyPurpose, KeyType, SecurityLevel } from '../port' +import { defineProfile } from '../profile' + +type KeyShape = Readonly> + +const signInType = (k: KeyShape) => k.keyType === KeyType.ECDSA_SECP256K1 || k.keyType === KeyType.ECDSA_HASH160 +const isAuth = (k: KeyShape) => k.purpose === KeyPurpose.AUTHENTICATION + +// ---- Yappr (lib/crypto/passkey-vault.ts) ---- + +const YAPPR_RAW = 1 +const YAPPR_RING = 2 + +/** Yappr `keyAllowed` plus "slot 0 must be the sign-in key". */ +function yapprAllow(k: KeyShape, slot: number, format: number): boolean { + if (isAuth(k)) return (k.securityLevel === SecurityLevel.CRITICAL || k.securityLevel === SecurityLevel.HIGH) && signInType(k) + if (slot === 0) return false + const purposeOk = k.purpose === KeyPurpose.ENCRYPTION || (format === YAPPR_RING && k.purpose === KeyPurpose.DECRYPTION) + return purposeOk && k.securityLevel === SecurityLevel.MEDIUM && k.keyType === KeyType.ECDSA_SECP256K1 +} + +export const yapprRaw = slotKeysCodec({ + id: YAPPR_RAW, + length: 80, + maxKeys: 2, + allow: yapprAllow, + check: (keys) => (keys.filter(isAuth).length === 1 ? null : 'a raw-key bundle holds one sign-in key'), +}) +export const yapprRing = slotKeysCodec({ id: YAPPR_RING, length: 160, maxKeys: 4, allow: yapprAllow }) + +export const yapprProfile = defineProfile({ + prfLabel: 'yappr/passkey-vault/v1/prf', + infoLabel: 'yappr/passkey-vault/v1', + aadDocType: 'vaultEntry', + entryVersion: 1, + formats: [yapprRaw, yapprRing], + strictSealedLength: false, +}) + +// ---- govhub (packages/auth/src/vault/bundle.ts) ---- + +export const govhubSeed = seedCodec({ id: 1, length: 240 }) +export const govhubKey = slotKeysCodec({ + id: 2, + length: 240, + maxKeys: 1, + allow: (k) => isAuth(k) && (k.securityLevel === SecurityLevel.HIGH || k.securityLevel === SecurityLevel.CRITICAL) && signInType(k), +}) +export const govhubVoting = votingKeysCodec({ id: 3, length: 240, maxKeys: 7 }) + +export type GovhubBundle = SeedBundle | SlotBundle | VotingKeysBundle + +export const govhubProfile = defineProfile({ + prfLabel: 'govhub/vault/v1/prf', + infoLabel: 'govhub/vault/v1', + aadDocType: 'vault', + entryVersion: 1, + formats: [govhubSeed, govhubKey, govhubVoting], + strictSealedLength: true, +}) + +// ---- Forge (new) ---- + +/** + * Slot 0: the session's main key, AUTHENTICATION at HIGH (secp256k1 or hash160). Slots 1 and up: per-contract wallet grants (the + * same shape) and at most one ENCRYPTION key at MEDIUM. Never MASTER, CRITICAL or TRANSFER. The chain check (bounds, budget, + * expiry) is the service's, not the codec's. + */ +function forgeAllow(k: KeyShape, slot: number): boolean { + if (isAuth(k)) return k.securityLevel === SecurityLevel.HIGH && signInType(k) + return slot > 0 && k.purpose === KeyPurpose.ENCRYPTION && k.securityLevel === SecurityLevel.MEDIUM && k.keyType === KeyType.ECDSA_SECP256K1 +} + +export const forgeSlots = slotKeysCodec({ + id: 1, + length: 240, + maxKeys: 6, + allow: forgeAllow, + check: (keys) => (keys.filter((k) => k.purpose === KeyPurpose.ENCRYPTION).length <= 1 ? null : 'a bundle holds one encryption key at most'), +}) + +export const forgeProfile = defineProfile({ + prfLabel: 'dash-forge/passkey-vault/v1/prf', + infoLabel: 'dash-forge/passkey-vault/v1', + aadDocType: 'vaultEntry', + entryVersion: 1, + formats: [forgeSlots], + strictSealedLength: true, +}) diff --git a/forge-web/lib/vendor/platform-auth/passkey-vault/__fixtures__/vectors.ts b/forge-web/lib/vendor/platform-auth/passkey-vault/__fixtures__/vectors.ts new file mode 100644 index 000000000..5bdf27db2 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/passkey-vault/__fixtures__/vectors.ts @@ -0,0 +1,61 @@ +// Loads the JSON vectors (read from disk so no tsconfig needs resolveJsonModule) and turns their keys into codec input. +import { readFileSync } from 'node:fs' +import { hexToBytes } from '@noble/hashes/utils.js' +import type { SlotBundle, SlotKey } from '../codecs' + +export interface VectorKey { + purpose: number + securityLevel: number + keyType: number + keyId: number + privateKey: string + label?: string +} + +export interface Vector { + name: string + format?: number + credentialId: string + prfOutput: string + ephemeralIkm: string + keys: VectorKey[] + prfInput?: string + recipientSk?: string + recipientKey?: string + info?: string + authKeyId?: number + aad?: string + bundle?: string + enc?: string + sealed?: string +} + +export interface VectorFile { + contractId: string + ownerId: string + vectors: Vector[] +} + +export interface GovhubFile { + contractId: string + ownerId: string + vector: Vector & { + snapshot: { enc: string; sealedHead: string; tag: string } + derived: Required> + } +} + +export function loadVectors(name: 'yappr' | 'govhub' | 'forge'): T { + return JSON.parse(readFileSync(new URL(`../__vectors__/${name}.json`, import.meta.url), 'utf8')) as T +} + +const slotKeys = (keys: readonly VectorKey[]): SlotKey[] => + keys.map((k) => ({ purpose: k.purpose, securityLevel: k.securityLevel, keyType: k.keyType, keyId: k.keyId, privateKey: hexToBytes(k.privateKey) })) + +export const slotBundle = (format: number, keys: readonly VectorKey[]): SlotBundle => ({ format, keys: slotKeys(keys) }) + +/** A field of a vector that must be present. */ +export function req(value: T | undefined, what: string): T { + if (value === undefined) throw new Error(`the vector has no ${what}`) + return value +} diff --git a/forge-web/lib/vendor/platform-auth/passkey-vault/__vectors__/forge.json b/forge-web/lib/vendor/platform-auth/passkey-vault/__vectors__/forge.json new file mode 100644 index 000000000..7031b5c36 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/passkey-vault/__vectors__/forge.json @@ -0,0 +1,147 @@ +{ + "about": "Forge passkey-vault vectors, written by generate.py (Python cryptography, independent of the TypeScript module). Ids and keys are sha256 of the labels. Regenerate with `python3 generate.py`; never edit by hand.", + "profile": { + "prfLabel": "dash-forge/passkey-vault/v1/prf", + "infoLabel": "dash-forge/passkey-vault/v1", + "aadDocType": "vaultEntry", + "entryVersion": 1, + "strictSealedLength": true, + "formats": [ + { + "id": 1, + "codec": "slotKeys", + "length": 240, + "maxKeys": 6 + } + ] + }, + "contractIdLabel": "forge test vector: forge-meta contract id", + "ownerIdLabel": "forge test vector: owner identity id", + "contractId": "58123f77f7851633356b6dec97c0b26359ca39c9d86fdd016bea4f07a0274b03", + "ownerId": "7a0ec0e390673ac8520d3e0d2ad8c65a26954fabafba252545aef97d165f77c8", + "vectors": [ + { + "name": "main key only", + "credentialId": "970f60fd85d4119d06f699423794f529", + "prfOutput": "dfe5eba137393d1bbea0a40d835230b6d4b88da1baa179c321a6527fc0d8b4af", + "ephemeralIkm": "8c22d040b709512d7ca1754d2d5f1f893eb1db107b8b10e655cd571446a60604", + "keys": [ + { + "purpose": 0, + "securityLevel": 2, + "keyType": 0, + "keyId": 3, + "privateKey": "2fe2c172eaaf0f27a617ec536bf66a115cc39d317870293a74e0f5d3f06a81b2", + "label": "forge test vector: limited key" + } + ], + "prfInput": "646173682d666f7267652f706173736b65792d7661756c742f76312f70726658123f77f7851633356b6dec97c0b26359ca39c9d86fdd016bea4f07a0274b03", + "recipientSk": "8a3b987fc9541c04d50ade6df9d1bba326e927a183e5253311fc5a4437b25a63", + "recipientKey": "9cf4b41f50a127d46e27dc60fd3b42b83da7fa8efb63aade30d80b9dc7b4af1a", + "authKeyId": 3, + "info": "646173682d666f7267652f706173736b65792d7661756c742f76310058123f77f7851633356b6dec97c0b26359ca39c9d86fdd016bea4f07a0274b037a0ec0e390673ac8520d3e0d2ad8c65a26954fabafba252545aef97d165f77c8", + "aad": "7661756c74456e747279000110970f60fd85d4119d06f699423794f5299cf4b41f50a127d46e27dc60fd3b42b83da7fa8efb63aade30d80b9dc7b4af1a00000003", + "bundle": "0101000200000000032fe2c172eaaf0f27a617ec536bf66a115cc39d317870293a74e0f5d3f06a81b200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "enc": "d4bce45f1571a8434e51874b83d6a019b8bd05723dac8f1ca07a7ea8e8d87b0c", + "sealed": "65f8cbb5971f17fa396779f09d4f2c68532694ae3c0880b247b3d74cf7124a3c6d2dcf19a137bdae531d21001d0e507a0faa48a0e2d0b0ccabbedc037b103f674cbd1b8f95b3d26c09bbbd19f151b504d89cd15bf7fec1d3431dc9e0f9931201cb185ab9ff6ee84347d5ef35e34c5889618c8a1a7194ede30bf44444a2eea7cb9bdafe572dbe6a59e9307a8b2c3ed46c32ef25cf3e0375d9bf4fcb6750d13352da18706f37b15e59a86f651c4204191056015b4e4fff4b0a23f9abb739227c0f601448bea43665229ee22cc5ca590b414c5d37f62db40e32f0a547653b631e9355bf77a36dd2bfa34d5a6b44ccd4d9891f97e9d054ab723de88638405b5e9742" + }, + { + "name": "main key, four wallet grants and the encryption key (full)", + "credentialId": "f6fad0916237e1c59a19d691682460a88f85234428e0b819d99d7bcefb5a22fa", + "prfOutput": "30d366155bea77e3f3e01adc7d5c411b5f00c986a5aa4c4910be774cb096d76f", + "ephemeralIkm": "6d1bee6c1af203c75b26097529756913c30896d8a82564bceb030b943c801d27", + "keys": [ + { + "purpose": 0, + "securityLevel": 2, + "keyType": 0, + "keyId": 5, + "privateKey": "a56b839fbdb3036781d09cfb3ef89922707a526599bf0bc74246d701bc10ed40", + "label": "forge test vector: group-bound wallet key" + }, + { + "purpose": 0, + "securityLevel": 2, + "keyType": 0, + "keyId": 6, + "privateKey": "d4bed0f106f228b84b9a956df53f634b4773170dd109f2f23b626fc9087c638e", + "label": "forge test vector: grant forge-core" + }, + { + "purpose": 0, + "securityLevel": 2, + "keyType": 2, + "keyId": 7, + "privateKey": "1abf8cbff7de2d411d2bd98b44fa767ae7052ef5c81c7f2b9bf51a885fe84927", + "label": "forge test vector: grant forge-collab" + }, + { + "purpose": 0, + "securityLevel": 2, + "keyType": 0, + "keyId": 8, + "privateKey": "6991491f145f2b60ce8de6cb52b7e63d34ebaecbb427f29495b313e78aaee72b", + "label": "forge test vector: grant forge-meta" + }, + { + "purpose": 0, + "securityLevel": 2, + "keyType": 0, + "keyId": 9, + "privateKey": "bd5befa762280ff54b7d58efeef2799807daf6bf3a13f9b5aecadafb2b7773cb", + "label": "forge test vector: grant forge-community" + }, + { + "purpose": 1, + "securityLevel": 3, + "keyType": 0, + "keyId": 10, + "privateKey": "9fa5142e7f06fb0986bafaa2d3af75a312364eb5c72f7e83e5a7e58a7b9f5ebc", + "label": "forge test vector: encryption key" + } + ], + "prfInput": "646173682d666f7267652f706173736b65792d7661756c742f76312f70726658123f77f7851633356b6dec97c0b26359ca39c9d86fdd016bea4f07a0274b03", + "recipientSk": "7f709d0ffca1248ac62bc3a9e00a63c2d7e31ec1473a088f0e75f6d03d27405a", + "recipientKey": "f54b25aeab8a706c874f806d5f2bec34ade111e2751cc9dd3a84d95bc4882422", + "authKeyId": 5, + "info": "646173682d666f7267652f706173736b65792d7661756c742f76310058123f77f7851633356b6dec97c0b26359ca39c9d86fdd016bea4f07a0274b037a0ec0e390673ac8520d3e0d2ad8c65a26954fabafba252545aef97d165f77c8", + "aad": "7661756c74456e747279000120f6fad0916237e1c59a19d691682460a88f85234428e0b819d99d7bcefb5a22faf54b25aeab8a706c874f806d5f2bec34ade111e2751cc9dd3a84d95bc488242200000005", + "bundle": "010600020000000005a56b839fbdb3036781d09cfb3ef89922707a526599bf0bc74246d701bc10ed4000020000000006d4bed0f106f228b84b9a956df53f634b4773170dd109f2f23b626fc9087c638e000202000000071abf8cbff7de2d411d2bd98b44fa767ae7052ef5c81c7f2b9bf51a885fe84927000200000000086991491f145f2b60ce8de6cb52b7e63d34ebaecbb427f29495b313e78aaee72b00020000000009bd5befa762280ff54b7d58efeef2799807daf6bf3a13f9b5aecadafb2b7773cb0103000000000a9fa5142e7f06fb0986bafaa2d3af75a312364eb5c72f7e83e5a7e58a7b9f5ebc00000000", + "enc": "a0856d600f87b0c7a08f373ed607a4b56723573ad43505cc9347bd862d76cc55", + "sealed": "54eaf5f71ce932ddc6a5cff152463c96ebb44f89a9cab57fd173ba6c11230228468df398cfa07b743e564901192e1bacf93407b4428729ff6908a7795bc90b2312662e7ee32fd3ceb8d2aca1fa06748fbde2bdc06da532b6dca0cf1a7637c72cc82f0ab90058658946c63399397b994f77772dc48fb4a8183525370c8d12ab49f82229f3f005ec960c97a96e0a22952629542a208aa1c5b84bf2917f032d8f507a9bf856e727bfbfd93118dd044e2233f8d54f17274577b42646d1d3f44d1cf559d4298686582559361c0f14f612e7d1871d772c7b1e68f1e621e6c402b7e76a3f2c3ff61b232c41dd256a7c2e124055e40d963f780c5d84d390c8178e245dd4" + }, + { + "name": "hash160 main key and the encryption key, 255-byte credential id, key id above 2^31", + "credentialId": "30cfa8828f583f03336992b8410c7ea53aefb85f11990c16ea440a77fb98d47c30cfa8828f583f03336992b8410c7ea53aefb85f11990c16ea440a77fb98d47c30cfa8828f583f03336992b8410c7ea53aefb85f11990c16ea440a77fb98d47c30cfa8828f583f03336992b8410c7ea53aefb85f11990c16ea440a77fb98d47c30cfa8828f583f03336992b8410c7ea53aefb85f11990c16ea440a77fb98d47c30cfa8828f583f03336992b8410c7ea53aefb85f11990c16ea440a77fb98d47c30cfa8828f583f03336992b8410c7ea53aefb85f11990c16ea440a77fb98d47c30cfa8828f583f03336992b8410c7ea53aefb85f11990c16ea440a77fb98d4", + "prfOutput": "a7c849a36e9496e2bd590216491575ef459c5120df43729e7a2f77e6b626e332", + "ephemeralIkm": "62611bc9dd7fd94912dc4e2909b74c036865edbf04b4ceacf254455a77a1b5be", + "keys": [ + { + "purpose": 0, + "securityLevel": 2, + "keyType": 2, + "keyId": 2147483649, + "privateKey": "abbd3887ec0338247c2728ab29cba93edc4ee89ba6c76bbb13b4f6d8be62ebd6", + "label": "forge test vector: hash160 key" + }, + { + "purpose": 1, + "securityLevel": 3, + "keyType": 0, + "keyId": 4, + "privateKey": "be474a945859bf51e3ba1aeb605193f123b5daffd170aaa6b2e2fbff3786fab2", + "label": "forge test vector: encryption key 3" + } + ], + "prfInput": "646173682d666f7267652f706173736b65792d7661756c742f76312f70726658123f77f7851633356b6dec97c0b26359ca39c9d86fdd016bea4f07a0274b03", + "recipientSk": "2957804d733d05671169394799f86c636af46837c7558372d3c67713dff51c5f", + "recipientKey": "ab22962c40d0bb93fd0c49ccaee36ad8a3423e0df2d2db67ac8dacc05288e752", + "authKeyId": 2147483649, + "info": "646173682d666f7267652f706173736b65792d7661756c742f76310058123f77f7851633356b6dec97c0b26359ca39c9d86fdd016bea4f07a0274b037a0ec0e390673ac8520d3e0d2ad8c65a26954fabafba252545aef97d165f77c8", + "aad": "7661756c74456e7472790001ff30cfa8828f583f03336992b8410c7ea53aefb85f11990c16ea440a77fb98d47c30cfa8828f583f03336992b8410c7ea53aefb85f11990c16ea440a77fb98d47c30cfa8828f583f03336992b8410c7ea53aefb85f11990c16ea440a77fb98d47c30cfa8828f583f03336992b8410c7ea53aefb85f11990c16ea440a77fb98d47c30cfa8828f583f03336992b8410c7ea53aefb85f11990c16ea440a77fb98d47c30cfa8828f583f03336992b8410c7ea53aefb85f11990c16ea440a77fb98d47c30cfa8828f583f03336992b8410c7ea53aefb85f11990c16ea440a77fb98d47c30cfa8828f583f03336992b8410c7ea53aefb85f11990c16ea440a77fb98d4ab22962c40d0bb93fd0c49ccaee36ad8a3423e0df2d2db67ac8dacc05288e75280000001", + "bundle": "010200020280000001abbd3887ec0338247c2728ab29cba93edc4ee89ba6c76bbb13b4f6d8be62ebd601030000000004be474a945859bf51e3ba1aeb605193f123b5daffd170aaa6b2e2fbff3786fab200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "enc": "ca787346f2b0bdf397657a4212b606e9c3d971409bd461bbbc1241c19926b000", + "sealed": "ab8dc167406ec144dc30c0458627e1b6d6bfe3bc1064d85714aa33639997a9d140aee3858e89474fec50d713295d0c531ff72d74a83e13d6683cb0acf241f519f16e8c10b7485f23fa8521560462a155dc2964ba29bb77fe40b2c51f6577081cab92e871fa64a379c1bf6dc39902a64eb16d8482bf27760a8ad5a939955ea9e0d1c0b7d08cad04cab68a253d53aba87e07aa0c98918eda9cdb6a60604815c4efe30396d2ae96f2e722e292c58cb0c9513e1345b806abb2b1beccc7bfa3ef017819b269b08f3dce23505b3adfe7213899a66743d8e0735d361be5d8aad9f28ec4f3c0d5dbe3d0f7b593b8320e0242c3ec3b2429f83438946ba0944c64f54d53e6" + } + ] +} diff --git a/forge-web/lib/vendor/platform-auth/passkey-vault/__vectors__/generate.py b/forge-web/lib/vendor/platform-auth/passkey-vault/__vectors__/generate.py new file mode 100644 index 000000000..d455fe45e --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/passkey-vault/__vectors__/generate.py @@ -0,0 +1,289 @@ +#!/usr/bin/env python3 +"""Independent generator and checker for the passkey vault's test vectors. + +Written from RFC 9180 and the format spec (docs/passkey-vault.md), sharing no code with the TypeScript module: HKDF is built +on Python's hmac, X25519 and ChaCha20-Poly1305 come from `cryptography`. It + + 1. checks its HPKE against RFC 9180 Appendix A.2.1, + 2. reproduces Yappr's RAW and RING vectors (yappr.json, copied from Yappr lib/crypto/passkey-vault.test.ts), + 3. reproduces govhub's fixed vector and checks it against govhub's snapshot (govhub.json), filling in the full bytes, + 4. writes the Forge vectors (forge.json). + +Usage: python3 generate.py rewrite govhub.json's derived bytes and forge.json + python3 generate.py --check fail if either file differs from what this script computes +""" +import hashlib +import hmac +import json +import sys +from pathlib import Path + +from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey +from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 +from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat + +HERE = Path(__file__).resolve().parent + +# --------------------------------------------------------------------------------------------------------------------------- +# RFC 9180: DHKEM(X25519, HKDF-SHA256) / HKDF-SHA256 / ChaCha20-Poly1305, base mode, single shot +# --------------------------------------------------------------------------------------------------------------------------- + +KEM_SUITE = b"KEM" + (0x0020).to_bytes(2, "big") +HPKE_SUITE = b"HPKE" + (0x0020).to_bytes(2, "big") + (0x0001).to_bytes(2, "big") + (0x0003).to_bytes(2, "big") + + +def hkdf_extract(salt: bytes, ikm: bytes) -> bytes: + return hmac.new(salt if salt else b"\x00" * 32, ikm, hashlib.sha256).digest() + + +def hkdf_expand(prk: bytes, info: bytes, length: int) -> bytes: + out, block, counter = b"", b"", 1 + while len(out) < length: + block = hmac.new(prk, block + info + bytes([counter]), hashlib.sha256).digest() + out += block + counter += 1 + return out[:length] + + +def labeled_extract(suite: bytes, salt: bytes, label: bytes, ikm: bytes) -> bytes: + return hkdf_extract(salt, b"HPKE-v1" + suite + label + ikm) + + +def labeled_expand(suite: bytes, prk: bytes, label: bytes, info: bytes, length: int) -> bytes: + return hkdf_expand(prk, length.to_bytes(2, "big") + b"HPKE-v1" + suite + label + info, length) + + +def raw_pub(sk: bytes) -> bytes: + return X25519PrivateKey.from_private_bytes(sk).public_key().public_bytes(Encoding.Raw, PublicFormat.Raw) + + +def derive_key_pair(ikm: bytes): + assert len(ikm) >= 32 + prk = labeled_extract(KEM_SUITE, b"", b"dkp_prk", ikm) + sk = labeled_expand(KEM_SUITE, prk, b"sk", b"", 32) + # cryptography clamps internally; report the unclamped sk as RFC 9180 does + return sk, raw_pub(sk) + + +def dh(sk: bytes, pk: bytes) -> bytes: + shared = X25519PrivateKey.from_private_bytes(sk).exchange(X25519PublicKey.from_public_bytes(pk)) + assert shared != b"\x00" * 32 + return shared + + +def kem_shared(dh_out: bytes, kem_context: bytes) -> bytes: + prk = labeled_extract(KEM_SUITE, b"", b"eae_prk", dh_out) + return labeled_expand(KEM_SUITE, prk, b"shared_secret", kem_context, 32) + + +def key_schedule(shared: bytes, info: bytes): + psk_id_hash = labeled_extract(HPKE_SUITE, b"", b"psk_id_hash", b"") + info_hash = labeled_extract(HPKE_SUITE, b"", b"info_hash", info) + context = b"\x00" + psk_id_hash + info_hash + secret = labeled_extract(HPKE_SUITE, shared, b"secret", b"") + return labeled_expand(HPKE_SUITE, secret, b"key", context, 32), labeled_expand(HPKE_SUITE, secret, b"base_nonce", context, 12) + + +def seal_base(pk_r: bytes, info: bytes, aad: bytes, pt: bytes, ikm_e: bytes): + sk_e, pk_e = derive_key_pair(ikm_e) + shared = kem_shared(dh(sk_e, pk_r), pk_e + pk_r) + key, nonce = key_schedule(shared, info) + return pk_e, ChaCha20Poly1305(key).encrypt(nonce, pt, aad) + + +def open_base(enc: bytes, sk_r: bytes, info: bytes, aad: bytes, ct: bytes) -> bytes: + shared = kem_shared(dh(sk_r, enc), enc + raw_pub(sk_r)) + key, nonce = key_schedule(shared, info) + return ChaCha20Poly1305(key).decrypt(nonce, ct, aad) + + +def check_rfc9180_a2(): + h = bytes.fromhex + sk_e, pk_e = derive_key_pair(h("909a9b35d3dc4713a5e72a4da274b55d3d3821a37e5d099e74a647db583a904b")) + sk_r, pk_r = derive_key_pair(h("1ac01f181fdf9f352797655161c58b75c656a6cc2716dcb66372da835542e1df")) + assert sk_e.hex() == "f4ec9b33b792c372c1d2c2063507b684ef925b8c75a42dbcbf57d63ccd381600" + assert pk_e.hex() == "1afa08d3dec047a643885163f1180476fa7ddb54c6a8029ea33f95796bf2ac4a" + assert sk_r.hex() == "8057991eef8f1f1af18f4a9491d16a1ce333f695d4db8e38da75975c4478e0fb" + assert pk_r.hex() == "4310ee97d88cc1f088a5576c77ab0cf5c3ac797f3d95139c6c84b5429c59662a" + info, aad = h("4f6465206f6e2061204772656369616e2055726e"), h("436f756e742d30") + pt = h("4265617574792069732074727574682c20747275746820626561757479") + enc, ct = seal_base(pk_r, info, aad, pt, h("909a9b35d3dc4713a5e72a4da274b55d3d3821a37e5d099e74a647db583a904b")) + assert enc == pk_e + assert ct.hex() == "1c5250d8034ec2b784ba2cfd69dbdb8af406cfe3ff938e131f0def8c8b60b4db21993c62ce81883d2dd1b51a28" + assert open_base(enc, sk_r, info, aad, ct) == pt + + +# --------------------------------------------------------------------------------------------------------------------------- +# The vault format (docs/passkey-vault.md) +# --------------------------------------------------------------------------------------------------------------------------- + +SECP256K1_N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 + + +def sha(label: str) -> bytes: + return hashlib.sha256(label.encode()).digest() + + +def prf_input(profile, contract: bytes) -> bytes: + return profile["prfLabel"].encode() + contract + + +def hpke_info(profile, contract: bytes, owner: bytes) -> bytes: + return profile["infoLabel"].encode() + b"\x00" + contract + owner + + +def entry_aad(profile, version: int, cred: bytes, recipient: bytes, auth_key_id: int) -> bytes: + assert 16 <= len(cred) <= 255 and len(recipient) == 32 + return profile["aadDocType"].encode() + bytes([0, version, len(cred)]) + cred + recipient + auth_key_id.to_bytes(4, "big") + + +def slot_bundle(fmt: int, length: int, max_keys: int, keys) -> bytes: + assert 1 <= len(keys) <= max_keys + out = bytes([fmt, len(keys)]) + for k in keys: + sk = bytes.fromhex(k["privateKey"]) + assert len(sk) == 32 and 0 < int.from_bytes(sk, "big") < SECP256K1_N + out += bytes([k["purpose"], k["securityLevel"], k["keyType"]]) + k["keyId"].to_bytes(4, "big") + sk + assert len(out) <= length + return out + b"\x00" * (length - len(out)) + + +def build(profile, contract: bytes, owner: bytes, v, fmt): + """Every derived field of one vector, from its inputs.""" + cred, prf, ikm = bytes.fromhex(v["credentialId"]), bytes.fromhex(v["prfOutput"]), bytes.fromhex(v["ephemeralIkm"]) + sk_r, pk_r = derive_key_pair(prf) + auth_key_id = v["keys"][0]["keyId"] + info = hpke_info(profile, contract, owner) + aad = entry_aad(profile, profile["entryVersion"], cred, pk_r, auth_key_id) + bundle = slot_bundle(fmt["id"], fmt["length"], fmt["maxKeys"], v["keys"]) + enc, sealed = seal_base(pk_r, info, aad, bundle, ikm) + assert open_base(enc, sk_r, info, aad, sealed) == bundle + assert len(sealed) == fmt["length"] + 16 + return { + "prfInput": prf_input(profile, contract).hex(), + "recipientSk": sk_r.hex(), + "recipientKey": pk_r.hex(), + "authKeyId": auth_key_id, + "info": info.hex(), + "aad": aad.hex(), + "bundle": bundle.hex(), + "enc": enc.hex(), + "sealed": sealed.hex(), + } + + +def check_yappr(): + data = json.loads((HERE / "yappr.json").read_text()) + profile, contract, owner = data["profile"], bytes.fromhex(data["contractId"]), bytes.fromhex(data["ownerId"]) + assert contract == sha(data["contractIdLabel"]) and owner == sha(data["ownerIdLabel"]) + for v in data["vectors"]: + fmt = next(f for f in profile["formats"] if f["id"] == v["format"]) + got = build(profile, contract, owner, v, fmt) + for field, value in got.items(): + if field in v: + assert v[field] == value, f"yappr {v['name']}: {field} differs" + assert v["enc"] == got["enc"] and v["sealed"] == got["sealed"] + + +def govhub(check: bool) -> bool: + path = HERE / "govhub.json" + data = json.loads(path.read_text()) + profile, contract, owner = data["profile"], bytes.fromhex(data["contractId"]), bytes.fromhex(data["ownerId"]) + v = data["vector"] + fmt = next(f for f in profile["formats"] if f["id"] == v["format"]) + got = build(profile, contract, owner, v, fmt) + snap = v["snapshot"] + assert got["enc"] == snap["enc"], "govhub enc differs from the snapshot" + assert got["sealed"][:32] == snap["sealedHead"] and got["sealed"][-32:] == snap["tag"], "govhub sealed differs from the snapshot" + want = dict(data) + want["vector"] = {**v, "derived": got} + return write_or_check(path, want, check) + + +FORGE_PROFILE = { + "prfLabel": "dash-forge/passkey-vault/v1/prf", + "infoLabel": "dash-forge/passkey-vault/v1", + "aadDocType": "vaultEntry", + "entryVersion": 1, + "strictSealedLength": True, + "formats": [{"id": 1, "codec": "slotKeys", "length": 240, "maxKeys": 6}], +} + + +def key(purpose, level, key_type, key_id, label): + return {"purpose": purpose, "securityLevel": level, "keyType": key_type, "keyId": key_id, "privateKey": sha(label).hex(), "label": label} + + +def forge(check: bool) -> bool: + contract_label, owner_label = "forge test vector: forge-meta contract id", "forge test vector: owner identity id" + contract, owner = sha(contract_label), sha(owner_label) + fmt = FORGE_PROFILE["formats"][0] + cases = [ + { + "name": "main key only", + "credentialId": sha("forge test vector: credential 1")[:16].hex(), + "prfOutput": sha("forge test vector: prf output 1").hex(), + "ephemeralIkm": sha("forge test vector: ephemeral 1").hex(), + "keys": [key(0, 2, 0, 3, "forge test vector: limited key")], + }, + { + "name": "main key, four wallet grants and the encryption key (full)", + "credentialId": sha("forge test vector: credential 2").hex(), + "prfOutput": sha("forge test vector: prf output 2").hex(), + "ephemeralIkm": sha("forge test vector: ephemeral 2").hex(), + "keys": [ + key(0, 2, 0, 5, "forge test vector: group-bound wallet key"), + key(0, 2, 0, 6, "forge test vector: grant forge-core"), + key(0, 2, 2, 7, "forge test vector: grant forge-collab"), + key(0, 2, 0, 8, "forge test vector: grant forge-meta"), + key(0, 2, 0, 9, "forge test vector: grant forge-community"), + key(1, 3, 0, 10, "forge test vector: encryption key"), + ], + }, + { + "name": "hash160 main key and the encryption key, 255-byte credential id, key id above 2^31", + "credentialId": (sha("forge test vector: credential 3a") * 8)[:255].hex(), + "prfOutput": sha("forge test vector: prf output 3").hex(), + "ephemeralIkm": sha("forge test vector: ephemeral 3").hex(), + "keys": [ + key(0, 2, 2, 0x80000001, "forge test vector: hash160 key"), + key(1, 3, 0, 4, "forge test vector: encryption key 3"), + ], + }, + ] + vectors = [{**c, **build(FORGE_PROFILE, contract, owner, c, fmt)} for c in cases] + want = { + "about": "Forge passkey-vault vectors, written by generate.py (Python cryptography, independent of the TypeScript module). " + "Ids and keys are sha256 of the labels. Regenerate with `python3 generate.py`; never edit by hand.", + "profile": FORGE_PROFILE, + "contractIdLabel": contract_label, + "ownerIdLabel": owner_label, + "contractId": contract.hex(), + "ownerId": owner.hex(), + "vectors": vectors, + } + return write_or_check(HERE / "forge.json", want, check) + + +def write_or_check(path: Path, want, check: bool) -> bool: + text = json.dumps(want, indent=2) + "\n" + if check: + ok = path.exists() and path.read_text() == text + if not ok: + print(f"{path.name} is out of date: run python3 generate.py", file=sys.stderr) + return ok + path.write_text(text) + return True + + +def main() -> int: + check = "--check" in sys.argv[1:] + check_rfc9180_a2() + check_yappr() + ok = govhub(check) & forge(check) + print("RFC 9180 A.2, Yappr RAW/RING and govhub's snapshot reproduced;", "vectors up to date" if check else "vectors written") + return 0 if ok else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/forge-web/lib/vendor/platform-auth/passkey-vault/__vectors__/govhub.json b/forge-web/lib/vendor/platform-auth/passkey-vault/__vectors__/govhub.json new file mode 100644 index 000000000..7c1c5db94 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/passkey-vault/__vectors__/govhub.json @@ -0,0 +1,64 @@ +{ + "about": "govhub's fixed vault vector (packages/auth/test/vault.test.ts 'a fixed vector stays stable'). `snapshot` is govhub's committed snapshot (test/__snapshots__/vault.test.ts.snap: enc, the first 16 sealed bytes, the 16-byte tag); `derived` is every byte, written by generate.py and checked against the snapshot.", + "source": "govhub packages/auth/test/vault.test.ts, test/__snapshots__/vault.test.ts.snap", + "profile": { + "prfLabel": "govhub/vault/v1/prf", + "infoLabel": "govhub/vault/v1", + "aadDocType": "vault", + "entryVersion": 1, + "strictSealedLength": true, + "formats": [ + { + "id": 1, + "codec": "seed", + "length": 240 + }, + { + "id": 2, + "codec": "slotKeys", + "length": 240, + "maxKeys": 1 + }, + { + "id": 3, + "codec": "votingKeys", + "length": 240, + "maxKeys": 7 + } + ] + }, + "contractId": "0101010101010101010101010101010101010101010101010101010101010101", + "ownerId": "0202020202020202020202020202020202020202020202020202020202020202", + "vector": { + "name": "KEY", + "format": 2, + "credentialId": "03030303030303030303030303030303", + "prfOutput": "0404040404040404040404040404040404040404040404040404040404040404", + "ephemeralIkm": "0505050505050505050505050505050505050505050505050505050505050505", + "keys": [ + { + "purpose": 0, + "securityLevel": 2, + "keyType": 0, + "keyId": 2, + "privateKey": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20" + } + ], + "snapshot": { + "enc": "402802aae25501861e6da002ef9f3e105b9296c3e3c90c92e600ec9a0ff52657", + "sealedHead": "b1021c93b4b4aa9b82ec7474a82e12d6", + "tag": "b3607e2dddcdfae70904dd8593c01387" + }, + "derived": { + "prfInput": "676f766875622f7661756c742f76312f7072660101010101010101010101010101010101010101010101010101010101010101", + "recipientSk": "07fdc0807e06d7a00a4fd605ddea2632de3fd740fe3625807f4590233333e296", + "recipientKey": "008d4fd6c00663955bf73dc152fe43bcf13c97453924872458a229f46c808012", + "authKeyId": 2, + "info": "676f766875622f7661756c742f76310001010101010101010101010101010101010101010101010101010101010101010202020202020202020202020202020202020202020202020202020202020202", + "aad": "7661756c7400011003030303030303030303030303030303008d4fd6c00663955bf73dc152fe43bcf13c97453924872458a229f46c80801200000002", + "bundle": "0201000200000000020102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f2000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "enc": "402802aae25501861e6da002ef9f3e105b9296c3e3c90c92e600ec9a0ff52657", + "sealed": "b1021c93b4b4aa9b82ec7474a82e12d647f4874d4b25ca08089965606b05fbb74e9cf572041c89d753134dcc48e9de01be32979f859d3a8b63ad7cf5c4065509da5a0e594f456743918ae82f87761e011256647c07331900225152130302637ca059611cccc25484ae8d2ae0adae5a2dfc86111bdbfd9d13138ee6eeba58dba57fc9dd5e1049404c8abbe6e545557c1b872ce8509f247b2238f4ad0ae582916bf46f4c5e6293203f583e54274bacf38059204717d1ac215bef6181eae3043fb8778a57b726803db403d34dfc391367f5ad44812153059801a93334a8d5ec8fc8b9998afd3bb1f97d2f5e4b1962385722b3607e2dddcdfae70904dd8593c01387" + } + } +} diff --git a/forge-web/lib/vendor/platform-auth/passkey-vault/__vectors__/yappr.json b/forge-web/lib/vendor/platform-auth/passkey-vault/__vectors__/yappr.json new file mode 100644 index 000000000..9c89ab4d2 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/passkey-vault/__vectors__/yappr.json @@ -0,0 +1,104 @@ +{ + "about": "Yappr passkey-vault v1 vectors, copied byte for byte from yappr lib/crypto/passkey-vault.test.ts (RAW: the design's vector from the independent prototype; RING: computed with the prototype's HPKE). Ids and keys are sha256 of the labels.", + "source": "yappr lib/crypto/passkey-vault.test.ts, docs/PASSKEY_VAULT.md \u00a73", + "profile": { + "prfLabel": "yappr/passkey-vault/v1/prf", + "infoLabel": "yappr/passkey-vault/v1", + "aadDocType": "vaultEntry", + "entryVersion": 1, + "strictSealedLength": false, + "formats": [ + { + "id": 1, + "codec": "slotKeys", + "length": 80, + "maxKeys": 2 + }, + { + "id": 2, + "codec": "slotKeys", + "length": 160, + "maxKeys": 4 + } + ] + }, + "contractIdLabel": "test vector: vault contract id", + "ownerIdLabel": "test vector: owner identity id", + "contractId": "fa2bc2b200af11d4d4dd2729b60599127d5832f2ef3eb004c9309a3c2980fa00", + "ownerId": "6b768e30fd4ad6f04f750159a4344d4c596f086eef5516a0187cfc010ea16579", + "vectors": [ + { + "name": "RAW", + "format": 1, + "credentialId": "68822693f2d21d39673258a62fc08dbfbb38744f", + "prfInput": "79617070722f706173736b65792d7661756c742f76312f707266fa2bc2b200af11d4d4dd2729b60599127d5832f2ef3eb004c9309a3c2980fa00", + "prfOutput": "387bc63059d4cd29b909e6fc4624b6875f9363e5e51e1a966c3060b3dd3a49e8", + "recipientSk": "3fa5cbc53c1620e6f9978b89ef5b14ca1c758393aa47f998084a38199e1e90a1", + "recipientKey": "f025f799ad8a214af13fb0e3ac29a51780deef4a2bf700181f3e787caa42d81a", + "ephemeralIkm": "30eddaf9393d591ec746b547b445832cec1ca31c42688488e95d577f9d929afe", + "info": "79617070722f706173736b65792d7661756c742f763100fa2bc2b200af11d4d4dd2729b60599127d5832f2ef3eb004c9309a3c2980fa006b768e30fd4ad6f04f750159a4344d4c596f086eef5516a0187cfc010ea16579", + "authKeyId": 2, + "aad": "7661756c74456e74727900011468822693f2d21d39673258a62fc08dbfbb38744ff025f799ad8a214af13fb0e3ac29a51780deef4a2bf700181f3e787caa42d81a00000002", + "keys": [ + { + "purpose": 0, + "securityLevel": 2, + "keyType": 0, + "keyId": 2, + "privateKey": "819462ac0a37da9dbc59ae82ed7e308d489e828080b6f9f8151183bb7a1a756c", + "label": "test vector: HIGH auth key" + }, + { + "purpose": 1, + "securityLevel": 3, + "keyType": 0, + "keyId": 6, + "privateKey": "b64ad618cc6d0027175787a5d901b0d61cf3d6e3d92bed45875cffbcd0111265", + "label": "test vector: encryption key" + } + ], + "bundle": "010200020000000002819462ac0a37da9dbc59ae82ed7e308d489e828080b6f9f8151183bb7a1a756c01030000000006b64ad618cc6d0027175787a5d901b0d61cf3d6e3d92bed45875cffbcd0111265", + "enc": "7baf4e67c9b049608cd7f6a0c4b00f53dcfe4f5ab74bbedc5860d451aa282b06", + "sealed": "e967f4c860290fcd0e701db258dc2256d448aa68184d9a96648c50b2e20bf59bbe089c1665d2086b3501016520ce572010ba81faa7e1134ff6f6958452dffea3b8645e13442f8b16da3bd2a6b36756e1846c63804a5c2fdbf8a62a7a186f640a" + }, + { + "name": "RING", + "format": 2, + "credentialId": "e2b9adaf79bb4b1982a17a143c4ea844cd8f329c524bc953c807e5e8430de348", + "prfOutput": "f8449c57a6b3009084290a4a906cbea2af72781b4b3acfa37fcc157f2a912c2c", + "recipientKey": "59d33f0d132b5036f05cfd72262b784f403bc610611e6562a8a79da4760bc326", + "ephemeralIkm": "a69a781cfc8bc13f019b6e56556ab67542dfa478d7008ee7a22bd547b3f2bd02", + "authKeyId": 7, + "aad": "7661756c74456e747279000120e2b9adaf79bb4b1982a17a143c4ea844cd8f329c524bc953c807e5e8430de34859d33f0d132b5036f05cfd72262b784f403bc610611e6562a8a79da4760bc32600000007", + "keys": [ + { + "purpose": 0, + "securityLevel": 1, + "keyType": 0, + "keyId": 7, + "privateKey": "1daa6fb6c6d1be6e7c70a0cdfd7810b6f62ad4e04066bcc0dcf1750f7db6f756", + "label": "test vector: App Connect group key" + }, + { + "purpose": 0, + "securityLevel": 2, + "keyType": 2, + "keyId": 8, + "privateKey": "53652d68e339fb2c0b5661e0489075259a3414d8e943832f9b1ded0b432584a7", + "label": "test vector: App Connect DashPay profile key" + }, + { + "purpose": 1, + "securityLevel": 3, + "keyType": 0, + "keyId": 9, + "privateKey": "fcc1b65f8a7190fb5b26ecb4c397dd15ef9c7bcca4179b3f76e6047c00fe604f", + "label": "test vector: App Connect anchor encryption key" + } + ], + "bundle": "0203000100000000071daa6fb6c6d1be6e7c70a0cdfd7810b6f62ad4e04066bcc0dcf1750f7db6f7560002020000000853652d68e339fb2c0b5661e0489075259a3414d8e943832f9b1ded0b432584a701030000000009fcc1b65f8a7190fb5b26ecb4c397dd15ef9c7bcca4179b3f76e6047c00fe604f0000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "enc": "e3574544df37f6dc5b18a3c384cbd59d7b8b073f2a001c3bcc25ac7a6e85d02d", + "sealed": "ae9aa24062af9e21df934690960f7b542f7fb9c31091796490428add088821b1f14e7001dea399cc901cca5ca6af2f40da04686b5e3ebc1e7dd5b991b2fb31976f695576cc7c2481d1d5638bd3bad1221571306bb975f7ea5217083fe392cf3dd0289521be6ac8a70dd0c089be0b8a4c99fbfafa9682a12ccc691aa91909e3e0d66269d3fb7869abbb9e950bf26db118cb227274e938e9dee242ff04f231d4ee68464e5c983ca51dccab4e92f4c2a7db" + } + ] +} diff --git a/forge-web/lib/vendor/platform-auth/passkey-vault/bytes.ts b/forge-web/lib/vendor/platform-auth/passkey-vault/bytes.ts new file mode 100644 index 000000000..d73c07b58 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/passkey-vault/bytes.ts @@ -0,0 +1,48 @@ +// Byte helpers for the passkey vault. Self-contained so the module can be vendored without the rest of platform-auth. + +export function concatBytes(...parts: readonly Uint8Array[]): Uint8Array { + let length = 0 + for (const p of parts) length += p.length + const out = new Uint8Array(length) + let offset = 0 + for (const p of parts) { + out.set(p, offset) + offset += p.length + } + return out +} + +/** Equal length and contents. Runs over the whole input whatever the first difference (the inputs are public here). */ +export function bytesEqual(a: Uint8Array, b: Uint8Array): boolean { + if (a.length !== b.length) return false + let diff = 0 + for (let i = 0; i < a.length; i += 1) diff |= (a[i] ?? 0) ^ (b[i] ?? 0) + return diff === 0 +} + +export const isU32 = (value: number): boolean => Number.isInteger(value) && value >= 0 && value <= 0xffffffff + +export function u32be(value: number): Uint8Array { + if (!isU32(value)) throw new RangeError('u32 out of range') + return new Uint8Array([(value >>> 24) & 0xff, (value >>> 16) & 0xff, (value >>> 8) & 0xff, value & 0xff]) +} + +export function readU32be(bytes: Uint8Array, offset: number): number { + if (offset < 0 || offset + 4 > bytes.length) throw new RangeError('read past the end') + return (((bytes[offset] ?? 0) << 24) >>> 0) + ((bytes[offset + 1] ?? 0) << 16) + ((bytes[offset + 2] ?? 0) << 8) + (bytes[offset + 3] ?? 0) +} + +/** Overwrites secret bytes. Best effort: copies made by libraries and the engine are out of reach. */ +export function wipe(...arrays: ReadonlyArray): void { + for (const a of arrays) a?.fill(0) +} + +/** Cryptographically secure random bytes (Web Crypto). */ +export function randomBytes(n: number): Uint8Array { + const out = new Uint8Array(n) + globalThis.crypto.getRandomValues(out) + return out +} + +/** True when every byte from `from` to the end is zero. */ +export const zeroFrom = (bytes: Uint8Array, from: number): boolean => bytes.subarray(from).every((b) => b === 0) diff --git a/forge-web/lib/vendor/platform-auth/passkey-vault/codecs.test.ts b/forge-web/lib/vendor/platform-auth/passkey-vault/codecs.test.ts new file mode 100644 index 000000000..f1f1356a0 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/passkey-vault/codecs.test.ts @@ -0,0 +1,259 @@ +import { describe, expect, it } from 'vitest' +import { sha256 } from '@noble/hashes/sha2.js' +import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js' +import { bytesEqual, concatBytes, readU32be, u32be, wipe } from './bytes' +import { isValidPrivateKey, seedCodec, slotKeysCodec, votingKeysCodec, type SlotBundle, type SlotKey } from './codecs' +import { VaultCryptoError } from './errors' +import { defineProfile, sealedLengths } from './profile' +import { forgeProfile, forgeSlots, govhubKey, govhubProfile, govhubSeed, govhubVoting, yapprProfile, yapprRaw, yapprRing } from './__fixtures__/profiles' + +const H = (label: string) => sha256(new TextEncoder().encode(label)) +const key = (over: Partial = {}): SlotKey => ({ purpose: 0, securityLevel: 2, keyType: 0, keyId: 2, privateKey: H(`key ${over.keyId ?? 2}`), ...over }) +const ENC: SlotKey = { purpose: 1, securityLevel: 3, keyType: 0, keyId: 6, privateKey: H('encryption key') } +const flip = (bytes: Uint8Array, index: number) => { + const copy = bytes.slice() + copy[index] = (copy[index] ?? 0) ^ 1 + return copy +} +const N = hexToBytes('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141') + +describe('bytes', () => { + it('u32be round-trips and refuses out-of-range values', () => { + for (const v of [0, 1, 0x7fffffff, 0x80000001, 0xffffffff]) expect(readU32be(u32be(v), 0)).toBe(v) + expect(() => u32be(-1)).toThrow(RangeError) + expect(() => u32be(2 ** 32)).toThrow(RangeError) + expect(() => u32be(1.5)).toThrow(RangeError) + expect(() => readU32be(new Uint8Array(3), 0)).toThrow(RangeError) + }) + + it('concat, equal, wipe', () => { + const a = concatBytes(Uint8Array.of(1), Uint8Array.of(2, 3)) + expect(Array.from(a)).toEqual([1, 2, 3]) + expect(bytesEqual(a, Uint8Array.of(1, 2, 3))).toBe(true) + expect(bytesEqual(a, Uint8Array.of(1, 2))).toBe(false) + expect(bytesEqual(a, Uint8Array.of(1, 2, 4))).toBe(false) + wipe(a, null, undefined) + expect(Array.from(a)).toEqual([0, 0, 0]) + }) + + it('secp256k1 private key validity: [1, n)', () => { + expect(isValidPrivateKey(H('x'))).toBe(true) + expect(isValidPrivateKey(new Uint8Array(32))).toBe(false) + expect(isValidPrivateKey(N)).toBe(false) + expect(isValidPrivateKey(flip(N, 31).fill(0xff, 31))).toBe(false) + const nMinus1 = N.slice() + nMinus1[31] = 0x40 + expect(isValidPrivateKey(nMinus1)).toBe(true) + expect(isValidPrivateKey(new Uint8Array(31).fill(1))).toBe(false) + }) +}) + +describe('slotKeysCodec', () => { + it('lays out format, count and 39-byte slots, zero-padded to the length', () => { + const k = key({ purpose: 0, securityLevel: 2, keyType: 2, keyId: 0x01020304 }) + const out = yapprRaw.encode({ format: 1, keys: [k] }) + expect(out.length).toBe(80) + expect(Array.from(out.subarray(0, 9))).toEqual([1, 1, 0, 2, 2, 1, 2, 3, 4]) + expect(bytesToHex(out.subarray(9, 41))).toBe(bytesToHex(k.privateKey)) + expect(out.subarray(41).every((b) => b === 0)).toBe(true) + }) + + it("is govhub's KEY layout with one slot: purpose at 2, level at 3, type at 4, key id at 5, key at 9", () => { + const out = govhubKey.encode({ format: 2, keys: [key()] }) + expect(out.length).toBe(240) + expect([out[0], out[1], out[2], out[3], out[4], readU32be(out, 5)]).toEqual([2, 1, 0, 2, 0, 2]) + expect(bytesToHex(out.subarray(9, 41))).toBe(bytesToHex(key().privateKey)) + }) + + it('round-trips, and decode returns copies', () => { + const bundle: SlotBundle = { format: 1, keys: [key(), ENC] } + const bytes = yapprRaw.encode(bundle) + const back = yapprRaw.decode(bytes, 2) + expect(back).toEqual(bundle) + bytes.fill(0) + expect(back.keys[0]!.privateKey).toEqual(key().privateKey) + expect(yapprRaw.authKeyIdOf?.(back)).toBe(2) + yapprRaw.wipe(back) + expect(back.keys.every((k) => k.privateKey.every((b) => b === 0))).toBe(true) + }) + + it('refuses counts, repeats, bad keys and ids out of range (encode)', () => { + const enc = (keys: SlotKey[]) => () => yapprRing.encode({ format: 2, keys }) + expect(enc([])).toThrow(/1 to 4 keys/) + expect(enc([key(), key({ keyId: 3 }), key({ keyId: 4 }), key({ keyId: 5 }), key({ keyId: 9 })])).toThrow(/1 to 4 keys/) + expect(enc([key(), { ...ENC, keyId: 2 }])).toThrow(/appears twice/) + expect(enc([key({ privateKey: new Uint8Array(31) })])).toThrow(/32 bytes/) + expect(enc([key({ privateKey: new Uint8Array(32) })])).toThrow(/valid secp256k1/) + expect(enc([key({ privateKey: N })])).toThrow(/valid secp256k1/) + expect(enc([key({ keyId: 2 ** 32 })])).toThrow(/out of range/) + expect(() => yapprRing.encode({ format: 1, keys: [key()] })).toThrow(/not of this format/) + }) + + it('refuses on decode: wrong length or format byte, count, padding, slot 0 not the entry key', () => { + const bytes = yapprRaw.encode({ format: 1, keys: [key()] }) + const code = (fn: () => unknown) => { + try { + fn() + } catch (e) { + return e instanceof VaultCryptoError ? e.code : 'other' + } + return 'none' + } + expect(code(() => yapprRaw.decode(bytes.slice(0, 79), 2))).toBe('format') + expect(code(() => yapprRaw.decode(concatBytes(bytes, Uint8Array.of(0)), 2))).toBe('format') + const relabelled = bytes.slice() + relabelled[0] = 2 + expect(code(() => yapprRaw.decode(relabelled, 2))).toBe('format') + expect(() => yapprRaw.decode(flip(bytes, 79), 2)).toThrow(/padding/) + expect(() => yapprRaw.decode(flip(bytes, 41), 2)).toThrow(/padding/) + expect(() => yapprRaw.decode(bytes, 6)).toThrow(/slot 0 is not/) + const zero = bytes.slice() + zero[1] = 0 + expect(() => yapprRaw.decode(zero, 2)).toThrow(/key count/) + const three = bytes.slice() + three[1] = 3 + expect(() => yapprRaw.decode(three, 2)).toThrow(/key count/) + }) + + it('wipes the keys it decoded when a rule refuses the bundle', () => { + let seen: readonly SlotKey[] = [] + const spy = slotKeysCodec({ + id: 7, + length: 80, + maxKeys: 2, + allow: () => true, + check: (keys) => { + seen = keys as readonly SlotKey[] + return 'refused by check' + }, + }) + const bytes = new Uint8Array(80) + bytes.set([7, 1, 0, 2, 0, 0, 0, 0, 2]) + bytes.set(H('k'), 9) + expect(() => spy.decode(bytes, 2)).toThrow(/refused by check/) + expect(seen).toHaveLength(1) + expect(seen[0]!.privateKey.every((b) => b === 0)).toBe(true) + }) + + it('checks its own shape at construction', () => { + const allow = () => true + expect(() => slotKeysCodec({ id: 1, length: 79, maxKeys: 2, allow })).toThrow(/at least 80/) + expect(() => slotKeysCodec({ id: 0, length: 80, maxKeys: 2, allow })).toThrow(/1 to 255/) + expect(() => slotKeysCodec({ id: 1, length: 80, maxKeys: 0, allow })).toThrow(/maxKeys/) + expect(forgeSlots.length).toBeGreaterThanOrEqual(2 + 6 * 39) + }) +}) + +describe("Yappr's rules", () => { + const raw = (keys: SlotKey[]) => () => yapprRaw.encode({ format: 1, keys }) + const ring = (keys: SlotKey[]) => () => yapprRing.encode({ format: 2, keys }) + + it('never a MASTER or TRANSFER key, nor a messaging key at another level; slot 0 is the sign-in key', () => { + expect(raw([key({ securityLevel: 0 })])).toThrow(/slot 0 may not/) + expect(raw([key({ purpose: 3, securityLevel: 1 })])).toThrow(/slot 0 may not/) + expect(raw([ENC])).toThrow(/slot 0 may not/) + expect(raw([key(), { ...ENC, purpose: 3 }])).toThrow(/slot 1 may not/) + expect(raw([key(), { ...ENC, securityLevel: 2 }])).toThrow(/slot 1 may not/) + expect(raw([key(), { ...ENC, purpose: 2 }])).toThrow(/slot 1 may not/) + expect(ring([key(), { ...ENC, purpose: 2 }])).not.toThrow() + expect(ring([key({ securityLevel: 1, keyId: 7 }), key({ securityLevel: 0, keyId: 8 })])).toThrow(/slot 1 may not/) + }) + + it('one sign-in key per raw bundle; CRITICAL taken at the codec', () => { + expect(raw([key(), key({ keyId: 3 })])).toThrow(/one sign-in key/) + expect(raw([key({ securityLevel: 1 })])).not.toThrow() + expect(ring([key(), key({ keyId: 3 }), ENC])).not.toThrow() + }) +}) + +describe("govhub's formats", () => { + it('SEED: format ‖ len ‖ u32be index ‖ entropy, refuses bad lengths, index and padding', () => { + const entropy = H('seed').slice(0, 16) + const bytes = govhubSeed.encode({ format: 1, identityIndex: 3, entropy }) + expect(bytes.length).toBe(240) + expect(Array.from(bytes.subarray(0, 6))).toEqual([1, 16, 0, 0, 0, 3]) + expect(govhubSeed.decode(bytes, 0)).toEqual({ format: 1, identityIndex: 3, entropy }) + expect(govhubSeed.decode(govhubSeed.encode({ format: 1, identityIndex: 0, entropy: H('32') }), 0).entropy.length).toBe(32) + expect(() => govhubSeed.encode({ format: 1, identityIndex: 0, entropy: new Uint8Array(20) })).toThrow(/entropy/) + expect(() => govhubSeed.encode({ format: 1, identityIndex: 0x80000000, entropy })).toThrow(/identity index/) + expect(() => govhubSeed.decode(flip(bytes, 200), 0)).toThrow(/padding/) + const len = bytes.slice() + len[1] = 20 + expect(() => govhubSeed.decode(len, 0)).toThrow(/entropy/) + const seed = govhubSeed.decode(bytes, 0) + govhubSeed.wipe(seed) + expect(seed.entropy.every((b) => b === 0)).toBe(true) + }) + + it('VOTING_KEYS: 1 to 7 distinct valid keys', () => { + const keys = [H('v1'), H('v2')] + const bytes = govhubVoting.encode({ format: 3, keys }) + expect(govhubVoting.decode(bytes, 0)).toEqual({ format: 3, keys }) + expect(() => govhubVoting.encode({ format: 3, keys: Array.from({ length: 8 }, (_, i) => H(`v${i}`)) })).toThrow(/1 to 7/) + expect(() => govhubVoting.encode({ format: 3, keys: [H('v1'), H('v1')] })).toThrow(/twice/) + expect(() => govhubVoting.encode({ format: 3, keys: [new Uint8Array(32)] })).toThrow(/invalid/) + expect(() => govhubVoting.decode(flip(bytes, 100), 0)).toThrow(/padding/) + }) + + it('KEY: only HIGH or CRITICAL authentication, never MASTER, MEDIUM or TRANSFER; the key must be the entry key', () => { + const enc = (k: SlotKey) => () => govhubKey.encode({ format: 2, keys: [k] }) + expect(enc(key({ securityLevel: 0, keyId: 0 }))).toThrow(VaultCryptoError) + expect(enc(key({ purpose: 3, securityLevel: 1, keyId: 3 }))).toThrow(VaultCryptoError) + expect(enc(key({ securityLevel: 3 }))).toThrow(VaultCryptoError) + expect(enc(key({ securityLevel: 1 }))).not.toThrow() + const e = govhubKey.encode({ format: 2, keys: [key()] }) + expect(() => govhubKey.decode(e, 1)).toThrow(/slot 0/) + const forged = e.slice() + forged[3] = 0 + expect(() => govhubKey.decode(forged, 2)).toThrow(VaultCryptoError) + expect(() => govhubKey.encode({ format: 2, keys: [key(), key({ keyId: 3 })] })).toThrow(/1 to 1 keys/) + }) +}) + +describe("Forge's rules", () => { + const enc = (keys: SlotKey[]) => () => forgeSlots.encode({ format: 1, keys }) + const grants = [3, 4, 5, 7].map((keyId) => key({ keyId })) + + it('holds the main key, four grants and the encryption key in 236 of 240 bytes', () => { + const bytes = forgeSlots.encode({ format: 1, keys: [key(), ...grants, ENC] }) + expect(bytes[1]).toBe(6) + expect(bytes.subarray(236).every((b) => b === 0)).toBe(true) + expect(bytes[235]).not.toBe(0) + expect(enc([key(), ...grants, ENC, key({ keyId: 9 })])).toThrow(/1 to 6 keys/) + }) + + it('never MASTER, CRITICAL, TRANSFER; HIGH authentication in slot 0; one MEDIUM encryption key at most', () => { + expect(enc([key({ securityLevel: 0 })])).toThrow(/slot 0/) + expect(enc([key({ securityLevel: 1 })])).toThrow(/slot 0/) + expect(enc([key({ purpose: 3, securityLevel: 1 })])).toThrow(/slot 0/) + expect(enc([ENC])).toThrow(/slot 0/) + expect(enc([key(), key({ keyId: 3, securityLevel: 1 })])).toThrow(/slot 1/) + expect(enc([key(), { ...ENC, securityLevel: 2 }])).toThrow(/slot 1/) + expect(enc([key(), { ...ENC, purpose: 2 }])).toThrow(/slot 1/) + expect(enc([key({ keyType: 1 })])).toThrow(/slot 0/) + expect(enc([key(), ENC, { ...ENC, keyId: 7 }])).toThrow(/one encryption key/) + expect(enc([key({ keyType: 2 }), ENC])).not.toThrow() + }) +}) + +describe('defineProfile', () => { + const base = { prfLabel: 'a/prf', infoLabel: 'a', aadDocType: 'vaultEntry', entryVersion: 1 as const, strictSealedLength: false } + + it('pins the three profiles', () => { + expect(sealedLengths(yapprProfile)).toEqual([96, 176]) + expect(sealedLengths(govhubProfile)).toEqual([256]) + expect(sealedLengths(forgeProfile)).toEqual([256]) + expect(Object.isFrozen(forgeProfile)).toBe(true) + }) + + it('refuses duplicate ids, mixed lengths in a strict profile, odd labels and no formats', () => { + expect(() => defineProfile({ ...base, formats: [yapprRaw, yapprRaw] })).toThrow(/unique/) + expect(() => defineProfile({ ...base, strictSealedLength: true, formats: [yapprRaw, yapprRing] })).toThrow(/one length/) + expect(() => defineProfile({ ...base, formats: [] })).toThrow(/at least one/) + expect(() => defineProfile({ ...base, prfLabel: 'has space', formats: [yapprRaw] })).toThrow(/printable/) + expect(() => defineProfile({ ...base, infoLabel: 'a/prf', formats: [yapprRaw] })).toThrow(/differ/) + expect(() => defineProfile({ ...base, entryVersion: 2 as unknown as 1, formats: [yapprRaw] })).toThrow(/version 1/) + expect(() => seedCodec({ id: 1, length: 37 })).toThrow() + expect(() => votingKeysCodec({ id: 1, length: 2 + 7 * 32 - 1, maxKeys: 7 })).toThrow() + }) +}) diff --git a/forge-web/lib/vendor/platform-auth/passkey-vault/codecs.ts b/forge-web/lib/vendor/platform-auth/passkey-vault/codecs.ts new file mode 100644 index 000000000..cf38b1589 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/passkey-vault/codecs.ts @@ -0,0 +1,247 @@ +// Bundle codecs: the plaintext an entry seals. A codec owns one format byte and one padded length; the profile lists the codecs a +// vault accepts. Every codec writes `format u8` first, pads with zeros to its length, and refuses non-zero padding on decode. +// +// slotKeysCodec is Yappr's slot layout (formats 1 and 2) and, with maxKeys 1, govhub's KEY format: +// format u8 ‖ n u8 ‖ n × (purpose u8 ‖ securityLevel u8 ‖ keyType u8 ‖ keyId u32be ‖ privateKey[32]) ‖ zero padding +// seedCodec and votingKeysCodec are govhub's SEED and VOTING_KEYS formats. +import { isU32, readU32be, u32be, wipe, zeroFrom } from './bytes' +import { need, VaultCryptoError } from './errors' + +export interface BundleCodec { + /** The format byte (byte 0 of the plaintext). */ + readonly id: number + /** The padded plaintext length (the sealed length is this + 16). */ + readonly length: number + encode(bundle: B): Uint8Array + /** Decodes and checks a plaintext of exactly `length` bytes; refuses a bundle that does not belong to entry key id `authKeyId`. */ + decode(bytes: Uint8Array, authKeyId: number): B + /** The entry key id a bundle implies (slot 0's key id), when the format has one. */ + authKeyIdOf?(bundle: B): number + /** Overwrites every secret in the bundle. */ + wipe(bundle: B): void +} + +const SECP256K1_N = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n + +/** A 32-byte secp256k1 private key in [1, n). */ +export function isValidPrivateKey(sk: Uint8Array): boolean { + if (sk.length !== 32) return false + let v = 0n + for (const b of sk) v = (v << 8n) | BigInt(b) + return v > 0n && v < SECP256K1_N +} + +function checkCodecShape(id: number, length: number, minLength: number): void { + need(Number.isInteger(id) && id >= 1 && id <= 255, 'a codec id must be 1 to 255') + need(Number.isInteger(length) && length >= minLength && length <= 4096, `a codec of this layout needs at least ${minLength} bytes`) +} + +function checkMaxKeys(maxKeys: number): void { + need(Number.isInteger(maxKeys) && maxKeys >= 1 && maxKeys <= 255, 'maxKeys must be 1 to 255') +} + +function checkPadding(bytes: Uint8Array, used: number): void { + need(zeroFrom(bytes, used), "the bundle's padding is not zero", 'bundle') +} + +function checkHeader(bytes: Uint8Array, id: number, length: number): void { + need(bytes.length === length && bytes[0] === id, 'the bundle does not match its format', 'format') +} + +// --------------------------------------------------------------------------------------------------------------------------------- +// Slot keys +// --------------------------------------------------------------------------------------------------------------------------------- + +export const SLOT_LENGTH = 39 + +export interface SlotKey { + purpose: number + securityLevel: number + keyType: number + keyId: number + /** 32-byte secp256k1 private key (ECDSA_SECP256K1 or ECDSA_HASH160 identity keys). */ + privateKey: Uint8Array +} + +export interface SlotBundle { + format: number + /** Slot 0 is the entry's key (`authKeyId`). */ + keys: SlotKey[] +} + +export interface SlotKeysCodecOptions { + id: number + length: number + maxKeys: number + /** Whether `slotIndex` of a bundle of format `format` may hold `key`. Called on encode and on decode. */ + allow(key: Readonly>, slotIndex: number, format: number): boolean + /** A whole-bundle rule (say, one encryption key at most): a reason to refuse, or null. Called on encode and on decode. */ + check?(keys: readonly Readonly>[]): string | null +} + +export function slotKeysCodec(o: SlotKeysCodecOptions): BundleCodec { + checkMaxKeys(o.maxKeys) + checkCodecShape(o.id, o.length, 2 + o.maxKeys * SLOT_LENGTH) + const { id, length, maxKeys } = o + + const checkKeys = (keys: readonly SlotKey[]): void => { + need(keys.length >= 1 && keys.length <= maxKeys, `a bundle of this format holds 1 to ${maxKeys} keys`, 'bundle') + keys.forEach((key, index) => { + need(isU32(key.keyId), 'a key id is out of range', 'bundle') + need(key.privateKey.length === 32, 'a private key must be 32 bytes', 'bundle') + need( + o.allow({ purpose: key.purpose, securityLevel: key.securityLevel, keyType: key.keyType, keyId: key.keyId }, index, id), + `slot ${index} may not hold a key of purpose ${key.purpose} at level ${key.securityLevel} of type ${key.keyType}`, + 'bundle', + ) + need(isValidPrivateKey(key.privateKey), 'a private key is not a valid secp256k1 key', 'bundle') + }) + need(new Set(keys.map((key) => key.keyId)).size === keys.length, 'a key appears twice', 'bundle') + const reason = o.check?.(keys) + if (reason) throw new VaultCryptoError(reason, 'bundle') + } + + return { + id, + length, + encode(bundle) { + need(bundle.format === id, 'the bundle is not of this format') + checkKeys(bundle.keys) + const out = new Uint8Array(length) + out[0] = id + out[1] = bundle.keys.length + bundle.keys.forEach((key, index) => { + const offset = 2 + index * SLOT_LENGTH + out.set([key.purpose, key.securityLevel, key.keyType], offset) + out.set(u32be(key.keyId), offset + 3) + out.set(key.privateKey, offset + 7) + }) + return out + }, + decode(bytes, authKeyId) { + checkHeader(bytes, id, length) + const count = bytes[1] ?? 0 + need(count >= 1 && count <= maxKeys, "the bundle's key count is out of range", 'bundle') + const keys: SlotKey[] = [] + for (let index = 0; index < count; index += 1) { + const offset = 2 + index * SLOT_LENGTH + keys.push({ + purpose: bytes[offset] ?? 0, + securityLevel: bytes[offset + 1] ?? 0, + keyType: bytes[offset + 2] ?? 0, + keyId: readU32be(bytes, offset + 3), + privateKey: bytes.slice(offset + 7, offset + SLOT_LENGTH), + }) + } + try { + checkKeys(keys) + checkPadding(bytes, 2 + count * SLOT_LENGTH) + need(keys[0]?.keyId === authKeyId, "slot 0 is not the entry's key", 'bundle') + } catch (error) { + for (const key of keys) wipe(key.privateKey) + throw error + } + return { format: id, keys } + }, + authKeyIdOf: (bundle) => { + const first = bundle.keys[0] + need(first !== undefined, 'the bundle holds no key', 'bundle') + return first.keyId + }, + wipe: (bundle) => { + for (const key of bundle.keys) wipe(key.privateKey) + }, + } +} + +// --------------------------------------------------------------------------------------------------------------------------------- +// Seed (govhub SEED): format u8 ‖ len u8 ‖ identityIndex u32be ‖ entropy[len] ‖ zero padding +// --------------------------------------------------------------------------------------------------------------------------------- + +export interface SeedBundle { + format: number + /** DIP-13 identity index, below 2^31. */ + identityIndex: number + /** BIP39 entropy, 16 or 32 bytes. */ + entropy: Uint8Array +} + +export function seedCodec(o: { id: number; length: number }): BundleCodec { + checkCodecShape(o.id, o.length, 6 + 32) + const { id, length } = o + const checkFields = (identityIndex: number, entropyLength: number): void => { + need(entropyLength === 16 || entropyLength === 32, 'seed entropy must be 16 or 32 bytes', 'bundle') + need(isU32(identityIndex) && identityIndex < 0x80000000, 'identity index out of range', 'bundle') + } + return { + id, + length, + encode(bundle) { + need(bundle.format === id, 'the bundle is not of this format') + checkFields(bundle.identityIndex, bundle.entropy.length) + const out = new Uint8Array(length) + out[0] = id + out[1] = bundle.entropy.length + out.set(u32be(bundle.identityIndex), 2) + out.set(bundle.entropy, 6) + return out + }, + decode(bytes) { + checkHeader(bytes, id, length) + const entropyLength = bytes[1] ?? 0 + const identityIndex = readU32be(bytes, 2) + checkFields(identityIndex, entropyLength) + checkPadding(bytes, 6 + entropyLength) + return { format: id, identityIndex, entropy: bytes.slice(6, 6 + entropyLength) } + }, + wipe: (bundle) => wipe(bundle.entropy), + } +} + +// --------------------------------------------------------------------------------------------------------------------------------- +// Voting keys (govhub VOTING_KEYS): format u8 ‖ n u8 ‖ n × privateKey[32] ‖ zero padding +// --------------------------------------------------------------------------------------------------------------------------------- + +export interface VotingKeysBundle { + format: number + keys: Uint8Array[] +} + +export function votingKeysCodec(o: { id: number; length: number; maxKeys: number }): BundleCodec { + checkMaxKeys(o.maxKeys) + checkCodecShape(o.id, o.length, 2 + o.maxKeys * 32) + const { id, length, maxKeys } = o + const checkKeys = (keys: readonly Uint8Array[]): void => { + need(keys.length >= 1 && keys.length <= maxKeys, `a voting-key bundle holds 1 to ${maxKeys} keys`, 'bundle') + need(keys.every(isValidPrivateKey), 'invalid voting key', 'bundle') + need(new Set(keys.map((k) => k.join(','))).size === keys.length, 'a voting key appears twice', 'bundle') + } + return { + id, + length, + encode(bundle) { + need(bundle.format === id, 'the bundle is not of this format') + checkKeys(bundle.keys) + const out = new Uint8Array(length) + out[0] = id + out[1] = bundle.keys.length + bundle.keys.forEach((k, i) => out.set(k, 2 + i * 32)) + return out + }, + decode(bytes) { + checkHeader(bytes, id, length) + const count = bytes[1] ?? 0 + need(count >= 1 && count <= maxKeys, 'voting key count out of range', 'bundle') + const keys = Array.from({ length: count }, (_, i) => bytes.slice(2 + i * 32, 34 + i * 32)) + try { + checkKeys(keys) + checkPadding(bytes, 2 + count * 32) + } catch (error) { + wipe(...keys) + throw error + } + return { format: id, keys } + }, + wipe: (bundle) => wipe(...bundle.keys), + } +} diff --git a/forge-web/lib/vendor/platform-auth/passkey-vault/entry.test.ts b/forge-web/lib/vendor/platform-auth/passkey-vault/entry.test.ts new file mode 100644 index 000000000..57b6f9906 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/passkey-vault/entry.test.ts @@ -0,0 +1,308 @@ +import { execFileSync } from 'node:child_process' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' +import { sha256 } from '@noble/hashes/sha2.js' +import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js' +import type { SlotBundle } from './codecs' +import { entryAad, hpkeInfo, openEntry, prfInput, recipientFromPrf, sealEntry, type SealedVaultEntry } from './entry' +import { VaultCryptoError } from './errors' +import { sealBase } from './hpke' +import type { VaultProfile } from './profile' +import { forgeProfile, forgeSlots, govhubKey, govhubProfile, govhubSeed, yapprProfile, yapprRaw, yapprRing } from './__fixtures__/profiles' +import { loadVectors, req, slotBundle, type GovhubFile, type Vector, type VectorFile } from './__fixtures__/vectors' + +const H = (label: string) => sha256(new TextEncoder().encode(label)) +const hex = bytesToHex +const flip = (bytes: Uint8Array, index: number) => { + const copy = bytes.slice() + copy[index] = (copy[index] ?? 0) ^ 1 + return copy +} +const code = (fn: () => unknown): string => { + try { + fn() + } catch (e) { + if (e instanceof VaultCryptoError) return e.code + throw e + } + throw new Error('did not throw') +} + +/** Every derived field of a slot-keys vector, and the seal/open round trip, against `profile`. */ +function checkVector(profile: VaultProfile, file: { contractId: string; ownerId: string }, v: Vector, codec = profile.formats[0]!) { + const contractId = hexToBytes(file.contractId) + const ownerId = hexToBytes(file.ownerId) + const credentialId = hexToBytes(v.credentialId) + const prf = hexToBytes(v.prfOutput) + const recipient = recipientFromPrf(prf) + if (v.prfInput) expect(hex(prfInput(profile, contractId))).toBe(v.prfInput) + if (v.recipientSk) expect(hex(recipient.privateKey)).toBe(v.recipientSk) + expect(hex(recipient.publicKey)).toBe(req(v.recipientKey, 'recipientKey')) + if (v.info) expect(hex(hpkeInfo(profile, contractId, ownerId))).toBe(v.info) + const authKeyId = req(v.authKeyId, 'authKeyId') + expect(hex(entryAad(profile, { version: 1, credentialId, recipientKey: recipient.publicKey, authKeyId }))).toBe(req(v.aad, 'aad')) + expect(hex(codec.encode(slotBundle(codec.id, v.keys)))).toBe(req(v.bundle, 'bundle')) + + const bundle = slotBundle(codec.id, v.keys) + const entry = sealEntry(profile, { contractId, ownerId, credentialId, recipientKey: recipient.publicKey, bundle, codec, ephemeralIkm: hexToBytes(v.ephemeralIkm) }) + expect(entry.authKeyId).toBe(authKeyId) + expect(hex(entry.enc)).toBe(req(v.enc, 'enc')) + expect(hex(entry.sealed)).toBe(req(v.sealed, 'sealed')) + // the caller's bundle is untouched by sealing + expect(bundle).toEqual(slotBundle(codec.id, v.keys)) + + const opened = openEntry(profile, { contractId, ownerId, entry, prfOutput: prf }) + expect(opened.codec).toBe(codec) + expect(opened.bundle).toEqual(slotBundle(codec.id, v.keys)) + // the PRF output belongs to the caller + expect(hex(prf)).toBe(v.prfOutput) + return entry +} + +describe('Yappr vectors (yappr lib/crypto/passkey-vault.test.ts), byte for byte', () => { + const file = loadVectors('yappr') + const raw = file.vectors.find((v) => v.name === 'RAW')! + const ring = file.vectors.find((v) => v.name === 'RING')! + + it('the ids are sha256 of the labels', () => { + expect(file.contractId).toBe(hex(H('test vector: vault contract id'))) + expect(file.ownerId).toBe(hex(H('test vector: owner identity id'))) + }) + + it('RAW: PRF input, recipient, info, aad, bundle, enc and sealed', () => { + const entry = checkVector(yapprProfile, file, raw, yapprRaw) + expect(entry.sealed.length).toBe(96) + }) + + it('RING: aad, bundle, enc and sealed (176 bytes)', () => { + const entry = checkVector(yapprProfile, file, ring, yapprRing) + expect(entry.sealed.length).toBe(176) + }) + + it('opens the stored RING entry back to the group, profile and encryption keys', () => { + const entry: SealedVaultEntry = { + version: 1, + credentialId: hexToBytes(ring.credentialId), + recipientKey: hexToBytes(req(ring.recipientKey, 'recipientKey')), + authKeyId: 7, + enc: hexToBytes(req(ring.enc, 'enc')), + sealed: hexToBytes(req(ring.sealed, 'sealed')), + } + const { bundle } = openEntry(yapprProfile, { contractId: hexToBytes(file.contractId), ownerId: hexToBytes(file.ownerId), entry, prfOutput: hexToBytes(ring.prfOutput) }) + expect(bundle.format).toBe(2) + expect(bundle.keys.map((k) => [k.keyId, k.securityLevel, k.keyType])).toEqual([[7, 1, 0], [8, 2, 2], [9, 3, 0]]) + }) + + it('pads a one-key raw bundle to the same 96-byte ciphertext, freshly each time', () => { + const seal = () => + sealEntry(yapprProfile, { + contractId: hexToBytes(file.contractId), + ownerId: hexToBytes(file.ownerId), + credentialId: hexToBytes(raw.credentialId), + recipientKey: hexToBytes(req(raw.recipientKey, 'recipientKey')), + bundle: slotBundle(1, raw.keys.slice(0, 1)), + codec: yapprRaw, + }) + const a = seal() + const b = seal() + expect(a.sealed.length).toBe(96) + expect(hex(a.enc)).not.toBe(hex(b.enc)) + expect(hex(a.sealed)).not.toBe(hex(b.sealed)) + }) +}) + +describe("govhub's fixed vector (govhub test/__snapshots__/vault.test.ts.snap)", () => { + const file = loadVectors('govhub') + const v = file.vector + const contractId = hexToBytes(file.contractId) + const ownerId = hexToBytes(file.ownerId) + + it('uses the inputs the snapshot was taken with', () => { + expect(file.contractId).toBe('01'.repeat(32)) + expect(file.ownerId).toBe('02'.repeat(32)) + expect(v.credentialId).toBe('03'.repeat(16)) + expect(v.prfOutput).toBe('04'.repeat(32)) + expect(v.ephemeralIkm).toBe('05'.repeat(32)) + expect(v.keys).toEqual([{ purpose: 0, securityLevel: 2, keyType: 0, keyId: 2, privateKey: hex(Uint8Array.from({ length: 32 }, (_, i) => i + 1)) }]) + }) + + it('seals a KEY bundle to the snapshot (enc, first 16 bytes, tag) and to the generator\'s full bytes; strict 256 B', () => { + const entry = sealEntry(govhubProfile, { + contractId, + ownerId, + credentialId: hexToBytes(v.credentialId), + recipientKey: recipientFromPrf(hexToBytes(v.prfOutput)).publicKey, + authKeyId: 2, + bundle: slotBundle(2, v.keys), + codec: govhubKey, + ephemeralIkm: hexToBytes(v.ephemeralIkm), + }) + expect(entry.sealed.length).toBe(256) + expect({ enc: hex(entry.enc), sealedHead: hex(entry.sealed.subarray(0, 16)), tag: hex(entry.sealed.subarray(-16)) }).toEqual(v.snapshot) + expect(hex(entry.sealed)).toBe(v.derived.sealed) + expect(hex(entryAad(govhubProfile, entry))).toBe(v.derived.aad) + expect(hex(hpkeInfo(govhubProfile, contractId, ownerId))).toBe(v.derived.info) + expect(hex(prfInput(govhubProfile, contractId))).toBe(v.derived.prfInput) + expect(new TextDecoder().decode(prfInput(govhubProfile, contractId).subarray(0, 19))).toBe('govhub/vault/v1/prf') + const { codec, bundle } = openEntry(govhubProfile, { contractId, ownerId, entry, prfOutput: hexToBytes(v.prfOutput) }) + expect(codec).toBe(govhubKey) + expect(bundle).toEqual(slotBundle(2, v.keys)) + }) + + it('pads every govhub format to 256 sealed bytes and picks the codec by the format byte', () => { + const prf = H('govhub other prf') + const recipientKey = recipientFromPrf(prf).publicKey + const credentialId = H('govhub cred').slice(0, 20) + const seed = { format: 1, identityIndex: 3, entropy: H('entropy').slice(0, 16) } + const entry = sealEntry(govhubProfile, { contractId, ownerId, credentialId, recipientKey, authKeyId: 2, bundle: seed, codec: govhubSeed }) + expect(entry.sealed.length).toBe(256) + const opened = openEntry(govhubProfile, { contractId, ownerId, entry, prfOutput: prf }) + expect(opened.codec).toBe(govhubSeed) + expect(opened.bundle).toEqual(seed) + }) +}) + +describe('Forge vectors (forge.json, from the independent Python generator)', () => { + const file = loadVectors('forge') + + it('pins the Forge profile', () => { + const contractId = hexToBytes(file.contractId) + expect(new TextDecoder().decode(prfInput(forgeProfile, contractId).subarray(0, 31))).toBe('dash-forge/passkey-vault/v1/prf') + expect(forgeProfile.formats).toEqual([forgeSlots]) + expect([forgeSlots.id, forgeSlots.length]).toEqual([1, 240]) + expect(file.vectors).toHaveLength(3) + }) + + for (const v of file.vectors) { + it(`${v.name}: every field, and 256 sealed bytes`, () => { + const entry = checkVector(forgeProfile, file, v) + expect(entry.sealed.length).toBe(256) + }) + } +}) + +describe('refusals', () => { + const file = loadVectors('forge') + const v = file.vectors[1]! + const contractId = hexToBytes(file.contractId) + const ownerId = hexToBytes(file.ownerId) + const prf = hexToBytes(v.prfOutput) + const recipientKey = recipientFromPrf(prf).publicKey + const credentialId = hexToBytes(v.credentialId) + const entry = sealEntry(forgeProfile, { contractId, ownerId, credentialId, recipientKey, bundle: slotBundle(1, v.keys), codec: forgeSlots }) + const open = (e: SealedVaultEntry, over: { prf?: Uint8Array; contract?: Uint8Array; owner?: Uint8Array } = {}) => + openEntry(forgeProfile, { contractId: over.contract ?? contractId, ownerId: over.owner ?? ownerId, entry: e, prfOutput: over.prf ?? prf }) + + /** Seals arbitrary plaintext with the right info and aad: what a malicious writer could do. */ + const sealRaw = (plaintext: Uint8Array, authKeyId = entry.authKeyId): SealedVaultEntry => { + const fields = { version: 1, credentialId, recipientKey, authKeyId } + const { enc, ciphertext } = sealBase(recipientKey, hpkeInfo(forgeProfile, contractId, ownerId), entryAad(forgeProfile, fields), plaintext) + return { ...fields, enc, sealed: ciphertext } + } + + it('refuses another passkey before decrypting (even a ciphertext that would not decrypt)', () => { + expect(code(() => open(entry, { prf: H('another PRF output') }))).toBe('wrong-passkey') + expect(code(() => open({ ...entry, sealed: new Uint8Array(256) }, { prf: H('another PRF output') }))).toBe('wrong-passkey') + expect(() => open(entry, { prf: H('x') })).toThrow(/does not open this entry/) + }) + + it('fails the tag for another identity, contract, credential or key id', () => { + expect(code(() => open(entry, { owner: H('another owner') }))).toBe('decrypt') + expect(code(() => open(entry, { contract: H('another contract') }))).toBe('decrypt') + expect(code(() => open({ ...entry, credentialId: H('another credential').slice(0, 20) }))).toBe('decrypt') + expect(code(() => open({ ...entry, authKeyId: entry.authKeyId + 1 }))).toBe('decrypt') + }) + + it('fails on any flipped ciphertext byte or a changed encapsulated key', () => { + for (const i of [0, 1, 40, 127, 239, 240, 255]) expect(code(() => open({ ...entry, sealed: flip(entry.sealed, i) }))).toBe('decrypt') + expect(code(() => open({ ...entry, enc: flip(entry.enc, 5) }))).toBe('decrypt') + expect(code(() => open({ ...entry, enc: new Uint8Array(32) }))).toBe('decrypt') + }) + + it('refuses an unknown version, a short enc, and a length no format has, before the passkey check', () => { + expect(code(() => open({ ...entry, version: 2 }))).toBe('version') + expect(code(() => open({ ...entry, enc: entry.enc.slice(0, 31) }))).toBe('format') + expect(code(() => open({ ...entry, sealed: entry.sealed.slice(0, 255) }, { prf: H('wrong') }))).toBe('format') + expect(code(() => open({ ...entry, sealed: new Uint8Array(96) }, { prf: H('wrong') }))).toBe('format') + // malformed fields read from the chain are the entry's fault + expect(code(() => open({ ...entry, credentialId: new Uint8Array(8) }))).toBe('format') + expect(code(() => open({ ...entry, recipientKey: new Uint8Array(31) }))).toBe('format') + // Yappr (not strict) still accepts only its two lengths + const y = loadVectors('yappr').vectors[0]! + const yEntry = { version: 1, credentialId: hexToBytes(y.credentialId), recipientKey: hexToBytes(req(y.recipientKey, 'rk')), authKeyId: 2, enc: hexToBytes(req(y.enc, 'enc')), sealed: new Uint8Array(100) } + expect(code(() => openEntry(yapprProfile, { contractId, ownerId, entry: yEntry, prfOutput: H('wrong') }))).toBe('format') + }) + + it('refuses an unknown format byte, non-zero padding and a slot 0 that is not the entry key, inside a valid ciphertext', () => { + const good = forgeSlots.encode(slotBundle(1, v.keys)) + const unknown = good.slice() + unknown[0] = 9 + expect(code(() => open(sealRaw(unknown)))).toBe('format') + expect(code(() => open(sealRaw(flip(good, 239))))).toBe('bundle') + expect(() => open(sealRaw(good, 99))).toThrow(/slot 0/) + const empty = good.slice() + empty[1] = 0 + expect(code(() => open(sealRaw(empty)))).toBe('bundle') + }) + + it('opens a forged bundle sealed to the right recipient: only the chain check can refuse it', () => { + const forged = sealEntry(forgeProfile, { + contractId, + ownerId, + credentialId, + recipientKey, + bundle: { format: 1, keys: [{ purpose: 0, securityLevel: 2, keyType: 0, keyId: 5, privateKey: H('attacker key') }] }, + codec: forgeSlots, + }) + expect(hex(open(forged).bundle.keys[0]!.privateKey)).toBe(hex(H('attacker key'))) + }) + + it('seals only with a codec of the profile, with an entry key id that agrees with slot 0', () => { + const base = { contractId, ownerId, credentialId, recipientKey, bundle: slotBundle(1, v.keys) } + expect(() => sealEntry(forgeProfile, { ...base, codec: yapprRaw })).toThrow(/not one of the profile/) + expect(() => sealEntry(forgeProfile, { ...base, codec: forgeSlots, authKeyId: 6 })).toThrow(/slot 0/) + expect(sealEntry(forgeProfile, { ...base, codec: forgeSlots, authKeyId: 5 }).authKeyId).toBe(5) + expect(() => sealEntry(govhubProfile, { ...base, bundle: { format: 1, identityIndex: 0, entropy: new Uint8Array(16) }, codec: govhubSeed })).toThrow(/key id/) + }) + + it('refuses malformed ids, recipient keys, PRF outputs and credential ids', () => { + expect(() => prfInput(forgeProfile, new Uint8Array(31))).toThrow(/32 bytes/) + expect(() => hpkeInfo(forgeProfile, contractId, new Uint8Array(33))).toThrow(/32 bytes/) + expect(() => recipientFromPrf(new Uint8Array(16))).toThrow(/32 bytes/) + expect(() => entryAad(forgeProfile, { version: 1, credentialId: new Uint8Array(15), recipientKey, authKeyId: 1 })).toThrow(/16 to 255/) + expect(() => entryAad(forgeProfile, { version: 1, credentialId: new Uint8Array(256), recipientKey, authKeyId: 1 })).toThrow(/16 to 255/) + expect(() => entryAad(forgeProfile, { version: 0, credentialId, recipientKey, authKeyId: 1 })).toThrow(/version/) + expect(() => entryAad(forgeProfile, { version: 1, credentialId, recipientKey, authKeyId: 2 ** 32 })).toThrow(/key id/) + expect(() => entryAad(forgeProfile, { version: 1, credentialId, recipientKey: new Uint8Array(31), authKeyId: 1 })).toThrow(/recipient/) + }) + + it('profiles give different bytes for the same inputs (labels are domain separation)', () => { + const forgeInfo = hex(hpkeInfo(forgeProfile, contractId, ownerId)) + expect(forgeInfo).not.toBe(hex(hpkeInfo(yapprProfile, contractId, ownerId))) + expect(hex(prfInput(forgeProfile, contractId))).not.toBe(hex(prfInput(yapprProfile, contractId))) + const fields = { version: 1, credentialId, recipientKey, authKeyId: 1 } + expect(hex(entryAad(govhubProfile, fields))).not.toBe(hex(entryAad(forgeProfile, fields))) + // Yappr and Forge share the doc type, so only info and the PRF input separate them + expect(hex(entryAad(yapprProfile, fields))).toBe(hex(entryAad(forgeProfile, fields))) + expect(code(() => openEntry(yapprProfile, { contractId, ownerId, entry, prfOutput: prf }))).toBe('format') + }) +}) + +describe('the independent generator', () => { + const python = (() => { + try { + execFileSync('python3', ['-c', 'import cryptography'], { stdio: 'ignore' }) + return true + } catch { + return false + } + })() + + // CI sets PASSKEY_VAULT_REQUIRE_PYTHON=1 so the cross-check cannot be skipped silently there + const required = process.env.PASSKEY_VAULT_REQUIRE_PYTHON === '1' + + it.skipIf(!python && !required)('reproduces RFC 9180 A.2, Yappr and govhub, and forge.json/govhub.json are what it writes', () => { + const script = fileURLToPath(new URL('./__vectors__/generate.py', import.meta.url)) + expect(execFileSync('python3', ['-I', script, '--check'], { encoding: 'utf8' })).toMatch(/up to date/) + }) +}) diff --git a/forge-web/lib/vendor/platform-auth/passkey-vault/entry.ts b/forge-web/lib/vendor/platform-auth/passkey-vault/entry.ts new file mode 100644 index 000000000..c0a894c4b --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/passkey-vault/entry.ts @@ -0,0 +1,151 @@ +// Sealing and opening one vault entry (Yappr docs/PASSKEY_VAULT.md §3; govhub vault/bundle.ts), parameterised by a profile: +// +// PRF input UTF8(prfLabel) ‖ contractId +// recipient (skR, pkR) = HPKE DeriveKeyPair(prfOutput) pkR is the entry's `recipientKey` +// info UTF8(infoLabel) ‖ 0x00 ‖ contractId ‖ ownerId +// AAD UTF8(aadDocType) ‖ 0x00 ‖ u8 version ‖ u8 len(credentialId) ‖ credentialId ‖ recipientKey ‖ u32be authKeyId +// +// HPKE has no sender authentication: anyone can seal to a public recipient key, and anyone who once held a live key of the owner +// can write an entry. An opened bundle proves nothing until the app checks it against the owner's keys read with proofs. +import { bytesEqual, concatBytes, isU32, u32be, wipe } from './bytes' +import type { BundleCodec } from './codecs' +import { need, VaultCryptoError } from './errors' +import { deriveKeyPair, openBase, sealBase, type HpkeKeyPair } from './hpke' +import { TAG_LENGTH, type VaultProfile } from './profile' + +export const MIN_CREDENTIAL_ID_LENGTH = 16 +export const MAX_CREDENTIAL_ID_LENGTH = 255 + +/** The fields of an entry the crypto binds, plus the HPKE output. Mirrors the on-chain document. */ +export interface SealedVaultEntry { + version: number + credentialId: Uint8Array + recipientKey: Uint8Array + authKeyId: number + enc: Uint8Array + sealed: Uint8Array +} + +export type EntryAadFields = Pick + +const te = new TextEncoder() +const is32 = (b: Uint8Array) => b.length === 32 + +export const isCredentialIdLength = (length: number): boolean => length >= MIN_CREDENTIAL_ID_LENGTH && length <= MAX_CREDENTIAL_ID_LENGTH + +export function prfInput(p: VaultProfile, contractId: Uint8Array): Uint8Array { + need(is32(contractId), 'the vault contract id must be 32 bytes') + return concatBytes(te.encode(p.prfLabel), contractId) +} + +export function recipientFromPrf(prfOutput: Uint8Array): HpkeKeyPair { + need(is32(prfOutput), 'the PRF output must be 32 bytes') + return deriveKeyPair(prfOutput) +} + +export function hpkeInfo(p: VaultProfile, contractId: Uint8Array, ownerId: Uint8Array): Uint8Array { + need(is32(contractId) && is32(ownerId), 'the contract and owner ids must be 32 bytes') + return concatBytes(te.encode(p.infoLabel), Uint8Array.of(0), contractId, ownerId) +} + +export function entryAad(p: VaultProfile, e: EntryAadFields): Uint8Array { + need(Number.isInteger(e.version) && e.version >= 1 && e.version <= 255, 'the entry version is out of range') + need(isCredentialIdLength(e.credentialId.length), 'the credential id must be 16 to 255 bytes') + need(is32(e.recipientKey), 'the recipient key must be 32 bytes') + need(isU32(e.authKeyId), 'the key id is out of range') + return concatBytes( + te.encode(p.aadDocType), + Uint8Array.of(0, e.version, e.credentialId.length), + e.credentialId, + e.recipientKey, + u32be(e.authKeyId), + ) +} + +export interface SealEntryInput { + contractId: Uint8Array + ownerId: Uint8Array + credentialId: Uint8Array + recipientKey: Uint8Array + bundle: B + /** One of the profile's formats. */ + codec: BundleCodec + /** Required when the codec has no `authKeyIdOf`; must agree with it when it has. */ + authKeyId?: number + /** Test vectors only: fixes the HPKE ephemeral key. */ + ephemeralIkm?: Uint8Array +} + +/** Seals `bundle` to a passkey's recipient key. Needs no passkey ceremony. Does not wipe the bundle (the caller owns it). */ +export function sealEntry(p: VaultProfile, o: SealEntryInput): SealedVaultEntry { + need(p.formats.includes(o.codec), "the codec is not one of the profile's formats") + const implied = o.codec.authKeyIdOf?.(o.bundle) + const authKeyId = o.authKeyId ?? implied + need(authKeyId !== undefined, 'the entry needs a key id') + need(implied === undefined || implied === authKeyId, "slot 0 is not the entry's key") + const fields: EntryAadFields = { version: p.entryVersion, credentialId: o.credentialId, recipientKey: o.recipientKey, authKeyId } + const aad = entryAad(p, fields) + const info = hpkeInfo(p, o.contractId, o.ownerId) + const plaintext = o.codec.encode(o.bundle) + try { + need(plaintext.length === o.codec.length && plaintext[0] === o.codec.id, 'the codec wrote a bundle of the wrong shape') + const { enc, ciphertext } = sealBase(o.recipientKey, info, aad, plaintext, o.ephemeralIkm) + return { ...fields, credentialId: o.credentialId.slice(), recipientKey: o.recipientKey.slice(), enc, sealed: ciphertext } + } finally { + wipe(plaintext) + } +} + +export interface OpenEntryInput { + contractId: Uint8Array + ownerId: Uint8Array + entry: SealedVaultEntry + prfOutput: Uint8Array +} + +export interface OpenedBundle { + codec: BundleCodec + bundle: B +} + +/** + * Opens an entry with its passkey's PRF output. In order: the version, the encapsulated key's and the ciphertext's lengths (a length + * no format has is refused before any work), the passkey (its derived key must be the entry's `recipientKey`, before decrypting), + * the tag, the format byte, then the codec's rules. Wipes the derived secret key and the plaintext. Does not wipe `prfOutput`. + */ +export function openEntry(p: VaultProfile, o: OpenEntryInput): OpenedBundle { + const e = o.entry + need(e.version === p.entryVersion, 'unknown entry version', 'version') + need(is32(e.enc), "the entry's encapsulated key must be 32 bytes", 'format') + // fields read from the chain: malformed ones are the entry's fault, not the caller's + need( + isCredentialIdLength(e.credentialId.length) && is32(e.recipientKey) && isU32(e.authKeyId), + "the entry's credential id, recipient key or key id is malformed", + 'format', + ) + const candidates = p.formats.filter((c) => c.length + TAG_LENGTH === e.sealed.length) + need(candidates.length > 0, "the entry's ciphertext has the wrong length", 'format') + need(!p.strictSealedLength || candidates.length === p.formats.length, "the profile's formats do not share one length") + const info = hpkeInfo(p, o.contractId, o.ownerId) + const aad = entryAad(p, e) + const recipient = recipientFromPrf(o.prfOutput) + try { + need(bytesEqual(recipient.publicKey, e.recipientKey), 'this passkey does not open this entry', 'wrong-passkey') + let plaintext: Uint8Array + try { + plaintext = openBase(e.enc, recipient.privateKey, info, aad, e.sealed) + } catch (error) { + if (error instanceof VaultCryptoError) throw error + throw new VaultCryptoError('the entry does not decrypt', 'decrypt') + } + try { + const codec = candidates.find((c) => c.id === plaintext[0]) + need(codec !== undefined, 'unknown bundle format', 'format') + return { codec, bundle: codec.decode(plaintext, e.authKeyId) } + } finally { + wipe(plaintext) + } + } finally { + wipe(recipient.privateKey) + } +} diff --git a/forge-web/lib/vendor/platform-auth/passkey-vault/errors.ts b/forge-web/lib/vendor/platform-auth/passkey-vault/errors.ts new file mode 100644 index 000000000..2983303ae --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/passkey-vault/errors.ts @@ -0,0 +1,82 @@ +// The module's errors. Each carries a stable `code` for the app to map to its own copy; messages are for logs. + +export type VaultCryptoErrorCode = + /** A caller passed a malformed id, key, label or option. */ + | 'input' + /** The entry's version is not the profile's. */ + | 'version' + /** The ciphertext's length or the bundle's format byte matches no format of the profile. */ + | 'format' + /** The passkey's derived recipient key is not the entry's: refused before decrypting. */ + | 'wrong-passkey' + /** The AEAD tag did not verify (another owner, contract, credential, key id, or a changed byte). */ + | 'decrypt' + /** The bundle broke a codec rule (slot rules, repeated key, padding, slot 0 not the entry's key id). */ + | 'bundle' + +export class VaultCryptoError extends Error { + constructor( + message: string, + readonly code: VaultCryptoErrorCode, + ) { + super(message) + this.name = 'VaultCryptoError' + } +} + +export type PasskeyErrorCode = + | 'unsupported' + | 'no-prf' + | 'cancelled' + | 'timeout' + /** The authenticator already holds one of the owner's passkeys (an `excludeCredentials` hit, `InvalidStateError`). */ + | 'exists' + | 'failed' + /** The user handle is not a 64-byte vault handle (null, or a local-only passkey's 32-byte random id). */ + | 'not-vault' + /** A vault handle for another vault contract (another network or deployment). */ + | 'other-vault' + +export class PasskeyError extends Error { + constructor( + message: string, + readonly code: PasskeyErrorCode, + /** The credential the failure concerns, when known (so a passkey with no PRF can be signalled unknown). */ + readonly credentialId?: Uint8Array, + ) { + super(message) + this.name = 'PasskeyError' + } +} + +export type VaultErrorCode = + /** The identity already has the profile's maximum number of passkeys. */ + | 'too-many' + /** No entry for this passkey (removed, or never written). */ + | 'no-entry' + /** The passkey or entry names another identity than the one expected. */ + | 'other-identity' + /** The identity could not be found (proved absent). */ + | 'unknown-identity' + /** A seal was asked for a recipient key this tab neither derived nor had a passkey confirm. */ + | 'untrusted-recipient' + /** The creation-time and assertion-time PRF outputs differ, or the assertion came from another credential. */ + | 'mismatch' + /** The written entry is not visible on Platform yet. */ + | 'not-visible' + /** The opened bundle failed the chain check: for the app's `verify` to throw. */ + | 'refused' + +export class VaultError extends Error { + constructor( + message: string, + readonly code: VaultErrorCode, + ) { + super(message) + this.name = 'VaultError' + } +} + +export function need(condition: boolean, message: string, code: VaultCryptoErrorCode = 'input'): asserts condition { + if (!condition) throw new VaultCryptoError(message, code) +} diff --git a/forge-web/lib/vendor/platform-auth/passkey-vault/hpke.test.ts b/forge-web/lib/vendor/platform-auth/passkey-vault/hpke.test.ts new file mode 100644 index 000000000..322cfe6c2 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/passkey-vault/hpke.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from 'vitest' +import { bytesToHex, hexToBytes } from '@noble/hashes/utils.js' +import { deriveKeyPair, openBase, sealBase } from './hpke' + +/** RFC 9180 Appendix A.2.1: DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, ChaCha20Poly1305, base mode, sequence number 0. */ +const A2 = { + info: '4f6465206f6e2061204772656369616e2055726e', + ikmE: '909a9b35d3dc4713a5e72a4da274b55d3d3821a37e5d099e74a647db583a904b', + pkEm: '1afa08d3dec047a643885163f1180476fa7ddb54c6a8029ea33f95796bf2ac4a', + skEm: 'f4ec9b33b792c372c1d2c2063507b684ef925b8c75a42dbcbf57d63ccd381600', + ikmR: '1ac01f181fdf9f352797655161c58b75c656a6cc2716dcb66372da835542e1df', + pkRm: '4310ee97d88cc1f088a5576c77ab0cf5c3ac797f3d95139c6c84b5429c59662a', + skRm: '8057991eef8f1f1af18f4a9491d16a1ce333f695d4db8e38da75975c4478e0fb', + pt: '4265617574792069732074727574682c20747275746820626561757479', + aad: '436f756e742d30', + ct: '1c5250d8034ec2b784ba2cfd69dbdb8af406cfe3ff938e131f0def8c8b60b4db21993c62ce81883d2dd1b51a28', +} + +describe('HPKE (RFC 9180 A.2.1)', () => { + it('derives the sender and recipient key pairs', () => { + const e = deriveKeyPair(hexToBytes(A2.ikmE)) + const r = deriveKeyPair(hexToBytes(A2.ikmR)) + expect(bytesToHex(e.privateKey)).toBe(A2.skEm) + expect(bytesToHex(e.publicKey)).toBe(A2.pkEm) + expect(bytesToHex(r.privateKey)).toBe(A2.skRm) + expect(bytesToHex(r.publicKey)).toBe(A2.pkRm) + }) + + it('seals sequence 0 to the RFC ciphertext and opens it again', () => { + const s = sealBase(hexToBytes(A2.pkRm), hexToBytes(A2.info), hexToBytes(A2.aad), hexToBytes(A2.pt), hexToBytes(A2.ikmE)) + expect(bytesToHex(s.enc)).toBe(A2.pkEm) + expect(bytesToHex(s.ciphertext)).toBe(A2.ct) + expect(bytesToHex(openBase(hexToBytes(A2.pkEm), hexToBytes(A2.skRm), hexToBytes(A2.info), hexToBytes(A2.aad), hexToBytes(A2.ct)))).toBe(A2.pt) + }) + + it('refuses a tampered ciphertext, aad or info', () => { + const open = (o: { ct?: string; aad?: string; info?: string }) => + openBase(hexToBytes(A2.pkEm), hexToBytes(A2.skRm), hexToBytes(o.info ?? A2.info), hexToBytes(o.aad ?? A2.aad), hexToBytes(o.ct ?? A2.ct)) + expect(() => open({ ct: `${A2.ct.slice(0, -2)}29` })).toThrow() + expect(() => open({ aad: '436f756e742d31' })).toThrow() + expect(() => open({ info: `${A2.info}00` })).toThrow() + }) + + it('refuses a small-order public key', () => { + expect(() => sealBase(new Uint8Array(32), new Uint8Array(0), new Uint8Array(0), new Uint8Array(1))).toThrow() + }) + + it('draws a fresh ephemeral key per seal and leaves a supplied one alone', () => { + const r = deriveKeyPair(hexToBytes(A2.ikmR)) + const a = sealBase(r.publicKey, new Uint8Array(0), new Uint8Array(0), new Uint8Array(16)) + const b = sealBase(r.publicKey, new Uint8Array(0), new Uint8Array(0), new Uint8Array(16)) + expect(bytesToHex(a.enc)).not.toBe(bytesToHex(b.enc)) + const ikm = hexToBytes(A2.ikmE) + sealBase(r.publicKey, new Uint8Array(0), new Uint8Array(0), new Uint8Array(16), ikm) + expect(bytesToHex(ikm)).toBe(A2.ikmE) + }) + + it('refuses key material shorter than 32 bytes', () => { + expect(() => deriveKeyPair(new Uint8Array(31))).toThrow() + }) +}) diff --git a/forge-web/lib/vendor/platform-auth/passkey-vault/hpke.ts b/forge-web/lib/vendor/platform-auth/passkey-vault/hpke.ts new file mode 100644 index 000000000..ce4d86b40 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/passkey-vault/hpke.ts @@ -0,0 +1,118 @@ +// RFC 9180 HPKE, one suite, base mode, single shot. Ported unchanged from govhub packages/auth/src/vault/hpke.ts (itself from Yappr +// lib/crypto/hpke.ts): KEM 0x0020 DHKEM(X25519, HKDF-SHA256), KDF 0x0001 HKDF-SHA256, AEAD 0x0003 ChaCha20-Poly1305. +// This is RFC 9180 Appendix A.2's suite; hpke.test.ts checks its vectors. Nothing is configurable on purpose. +import { chacha20poly1305 } from '@noble/ciphers/chacha.js' +import { x25519 } from '@noble/curves/ed25519.js' +import { expand, extract } from '@noble/hashes/hkdf.js' +import { sha256 } from '@noble/hashes/sha2.js' +import { concatBytes, randomBytes } from './bytes' + +const KEM_ID = 0x0020 +const KDF_ID = 0x0001 +const AEAD_ID = 0x0003 +const N_SECRET = 32 +const N_K = 32 +const N_N = 12 +const N_SK = 32 + +const enc = new TextEncoder() +const EMPTY = new Uint8Array(0) + +const i2osp = (value: number, width: number): Uint8Array => { + const out = new Uint8Array(width) + for (let i = width - 1, v = value; i >= 0; i--, v = Math.floor(v / 256)) out[i] = v & 0xff + return out +} + +const HPKE_V1 = enc.encode('HPKE-v1') +const SUITE_KEM = concatBytes(enc.encode('KEM'), i2osp(KEM_ID, 2)) +const SUITE_HPKE = concatBytes(enc.encode('HPKE'), i2osp(KEM_ID, 2), i2osp(KDF_ID, 2), i2osp(AEAD_ID, 2)) + +function labeledExtract(suite: Uint8Array, salt: Uint8Array, label: string, ikm: Uint8Array): Uint8Array { + const labeled = concatBytes(HPKE_V1, suite, enc.encode(label), ikm) + try { + return extract(sha256, labeled, salt) + } finally { + labeled.fill(0) + } +} + +const labeledExpand = (suite: Uint8Array, prk: Uint8Array, label: string, info: Uint8Array, length: number): Uint8Array => + expand(sha256, prk, concatBytes(i2osp(length, 2), HPKE_V1, suite, enc.encode(label), info), length) + +export interface HpkeKeyPair { + privateKey: Uint8Array + publicKey: Uint8Array +} + +/** RFC 9180 7.1.3 DeriveKeyPair for X25519. */ +export function deriveKeyPair(ikm: Uint8Array): HpkeKeyPair { + if (ikm.length < N_SK) throw new Error('HPKE: the key material must be at least 32 bytes') + const dkpPrk = labeledExtract(SUITE_KEM, EMPTY, 'dkp_prk', ikm) + try { + const privateKey = labeledExpand(SUITE_KEM, dkpPrk, 'sk', EMPTY, N_SK) + return { privateKey, publicKey: x25519.getPublicKey(privateKey) } + } finally { + dkpPrk.fill(0) + } +} + +/** X25519, refusing the all-zero output of a small-order point (RFC 9180 7.1.4). */ +function dh(privateKey: Uint8Array, publicKey: Uint8Array): Uint8Array { + const shared = x25519.getSharedSecret(privateKey, publicKey) + if (shared.every((b) => b === 0)) throw new Error('HPKE: the key exchange produced no secret') + return shared +} + +function extractAndExpand(dhOutput: Uint8Array, kemContext: Uint8Array): Uint8Array { + const prk = labeledExtract(SUITE_KEM, EMPTY, 'eae_prk', dhOutput) + try { + return labeledExpand(SUITE_KEM, prk, 'shared_secret', kemContext, N_SECRET) + } finally { + prk.fill(0) + dhOutput.fill(0) + } +} + +function keySchedule(sharedSecret: Uint8Array, info: Uint8Array): { key: Uint8Array; baseNonce: Uint8Array } { + const pskIdHash = labeledExtract(SUITE_HPKE, EMPTY, 'psk_id_hash', EMPTY) + const infoHash = labeledExtract(SUITE_HPKE, EMPTY, 'info_hash', info) + const context = concatBytes(new Uint8Array([0x00]), pskIdHash, infoHash) + const secret = labeledExtract(SUITE_HPKE, sharedSecret, 'secret', EMPTY) + try { + return { key: labeledExpand(SUITE_HPKE, secret, 'key', context, N_K), baseNonce: labeledExpand(SUITE_HPKE, secret, 'base_nonce', context, N_N) } + } finally { + secret.fill(0) + sharedSecret.fill(0) + } +} + +/** SealBase(pkR, info, aad, pt). `ephemeralIkm` is for test vectors only; production draws a fresh ephemeral key per seal. */ +export function sealBase(recipientPublicKey: Uint8Array, info: Uint8Array, aad: Uint8Array, plaintext: Uint8Array, ephemeralIkm?: Uint8Array): { enc: Uint8Array; ciphertext: Uint8Array } { + const ikm = ephemeralIkm ?? randomBytes(N_SK) + const ephemeral = deriveKeyPair(ikm) + if (!ephemeralIkm) ikm.fill(0) + try { + const shared = extractAndExpand(dh(ephemeral.privateKey, recipientPublicKey), concatBytes(ephemeral.publicKey, recipientPublicKey)) + const { key, baseNonce } = keySchedule(shared, info) + try { + return { enc: ephemeral.publicKey, ciphertext: chacha20poly1305(key, baseNonce, aad).encrypt(plaintext) } + } finally { + key.fill(0) + } + } finally { + ephemeral.privateKey.fill(0) + } +} + +/** OpenBase(enc, skR, info, aad, ct). Throws when the tag does not verify. */ +export function openBase(encapsulated: Uint8Array, recipientPrivateKey: Uint8Array, info: Uint8Array, aad: Uint8Array, ciphertext: Uint8Array): Uint8Array { + const pkR = x25519.getPublicKey(recipientPrivateKey) + const shared = extractAndExpand(dh(recipientPrivateKey, encapsulated), concatBytes(encapsulated, pkR)) + const { key, baseNonce } = keySchedule(shared, info) + try { + return chacha20poly1305(key, baseNonce, aad).decrypt(ciphertext) + } finally { + key.fill(0) + } +} diff --git a/forge-web/lib/vendor/platform-auth/passkey-vault/index.ts b/forge-web/lib/vendor/platform-auth/passkey-vault/index.ts new file mode 100644 index 000000000..8d154329f --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/passkey-vault/index.ts @@ -0,0 +1,68 @@ +// @pastapastapasta/platform-auth/passkey-vault: an on-chain passkey vault core (docs/passkey-vault.md). Not re-exported from the +// package root: names such as PasskeyError would collide with the root's. +export { bytesEqual, concatBytes, randomBytes, readU32be, u32be, wipe } from './bytes' +export { + isValidPrivateKey, + seedCodec, + SLOT_LENGTH, + slotKeysCodec, + votingKeysCodec, + type BundleCodec, + type SeedBundle, + type SlotBundle, + type SlotKey, + type SlotKeysCodecOptions, + type VotingKeysBundle, +} from './codecs' +export { + entryAad, + hpkeInfo, + MAX_CREDENTIAL_ID_LENGTH, + MIN_CREDENTIAL_ID_LENGTH, + openEntry, + prfInput, + recipientFromPrf, + sealEntry, + type EntryAadFields, + type OpenedBundle, + type OpenEntryInput, + type SealedVaultEntry, + type SealEntryInput, +} from './entry' +export { + PasskeyError, + VaultCryptoError, + VaultError, + type PasskeyErrorCode, + type VaultCryptoErrorCode, + type VaultErrorCode, +} from './errors' +export { deriveKeyPair, openBase, sealBase, type HpkeKeyPair } from './hpke' +export { KeyPurpose, KeyType, SecurityLevel, type ContractBounds, type OnChainKey, type VaultEntryRecord, type VaultPort } from './port' +export { defineProfile, sealedLengths, TAG_LENGTH, type VaultProfile } from './profile' +export { parseUserHandle, USER_HANDLE_LENGTH, userHandleFor } from './user-handle' +export { checkSlots, matchKey, type AcceptedSlot, type DropReason, type DroppedSlot, type SlotRules } from './verify' +export { + DEFAULT_MAX_PASSKEYS, + PasskeyVault, + type ConfirmedPasskey, + type ConfirmTarget, + type OpenedVault, + type PasskeyVaultOptions, + type PendingEnrolment, + type TrustedRecipient, + type VerifyContext, +} from './vault' +export { + browserPasskeyAdapter, + DEFAULT_PASSKEY_TIMEOUT_MS, + defaultPasskeyError, + prfSupport, + type BrowserPasskeyOptions, + type CeremonyKind, + type CreatedPasskey, + type CreatePasskeyOptions, + type GetPasskeyOptions, + type PasskeyAdapter, + type PasskeyAssertion, +} from './webauthn' diff --git a/forge-web/lib/vendor/platform-auth/passkey-vault/port.ts b/forge-web/lib/vendor/platform-auth/passkey-vault/port.ts new file mode 100644 index 000000000..6c4d6c343 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/passkey-vault/port.ts @@ -0,0 +1,57 @@ +// What the vault needs from Platform. The app builds the port: it binds the vault contract and the signer (the session key), reads +// with proofs, and serialises writes per identity. Ids are raw 32-byte identifiers here; the port converts to the SDK's forms. +import type { SealedVaultEntry } from './entry' + +/** rs-dpp `Purpose`. */ +export const KeyPurpose = { AUTHENTICATION: 0, ENCRYPTION: 1, DECRYPTION: 2, TRANSFER: 3, SYSTEM: 4, VOTING: 5, OWNER: 6 } as const +/** rs-dpp `SecurityLevel` (lower is stronger). */ +export const SecurityLevel = { MASTER: 0, CRITICAL: 1, HIGH: 2, MEDIUM: 3 } as const +/** rs-dpp `KeyType`. */ +export const KeyType = { ECDSA_SECP256K1: 0, BLS12_381: 1, ECDSA_HASH160: 2, BIP13_SCRIPT_HASH: 3, EDDSA_25519_HASH160: 4 } as const + +export type ContractBounds = + | { kind: 'singleContract'; contractId: Uint8Array } + | { kind: 'singleContractDocumentType'; contractId: Uint8Array; documentType: string } + | { kind: 'contractGroup'; groupId: Uint8Array } + +/** An identity public key as read from Platform with proofs, reduced to what the vault's checks need. */ +export interface OnChainKey { + id: number + purpose: number + securityLevel: number + type: number + /** 33-byte compressed point (ECDSA_SECP256K1) or 20-byte hash160 (ECDSA_HASH160). */ + data: Uint8Array + disabled: boolean + contractBounds?: ContractBounds + /** Expiry, ms since the epoch. */ + expiresAt?: number + /** The key's total budget in credits, when it has one. */ + totalBudget?: bigint + /** What is left of the budget in credits; undefined when unknown or the key has none. */ + remainingBudget?: bigint +} + +/** A vault entry as stored: the sealed fields plus the document's owner and bookkeeping. */ +export interface VaultEntryRecord extends SealedVaultEntry { + ownerId: Uint8Array + /** The document id (the port's own form). */ + documentId?: string + revision?: number + /** `$createdAt` / `$updatedAt`, ms since the epoch. */ + createdAt?: number + updatedAt?: number +} + +export interface VaultPort { + /** Every entry of `ownerId`, read with proofs. */ + list(ownerId: Uint8Array): Promise + /** The entry for one credential (`byCredential [$ownerId, credentialId]`), read with proofs; null when proved absent. */ + byCredential(ownerId: Uint8Array, credentialId: Uint8Array): Promise + /** The identity's public keys, read with proofs; null when the identity is proved absent. */ + identityKeys(ownerId: Uint8Array): Promise + /** Creates the entry, or replaces `existing` (same credential). Idempotent and serialised per identity. */ + put(o: { ownerId: Uint8Array; entry: SealedVaultEntry; existing: VaultEntryRecord | null }): Promise + /** Deletes the entry. Idempotent. */ + remove(o: { ownerId: Uint8Array; entry: VaultEntryRecord }): Promise +} diff --git a/forge-web/lib/vendor/platform-auth/passkey-vault/profile.ts b/forge-web/lib/vendor/platform-auth/passkey-vault/profile.ts new file mode 100644 index 000000000..ede448855 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/passkey-vault/profile.ts @@ -0,0 +1,41 @@ +// A vault profile: the labels and formats that make one app's entries its own. Changing any field orphans every stored entry, so an +// app defines its profile once, pins it with test vectors, and never edits it (a new layout is a new codec id or a new profile). +import type { BundleCodec } from './codecs' +import { need } from './errors' + +export interface VaultProfile { + /** PRF `first` input = UTF8(prfLabel) ‖ contractId. */ + readonly prfLabel: string + /** HPKE info = UTF8(infoLabel) ‖ 0x00 ‖ contractId ‖ ownerId. */ + readonly infoLabel: string + /** AAD = UTF8(aadDocType) ‖ 0x00 ‖ u8 version ‖ u8 len(credentialId) ‖ credentialId ‖ recipientKey ‖ u32be authKeyId. */ + readonly aadDocType: string + readonly entryVersion: 1 + /** The formats the vault seals and opens; ids must be unique. */ + readonly formats: readonly BundleCodec[] + /** + * Every format pads to one length, so every entry has the same sealed size whatever it holds, and opening refuses any other + * length before the passkey check (govhub, Forge). When false, formats may have different lengths (Yappr: 80 and 160); opening + * still refuses a length that is no format's before decrypting. + */ + readonly strictSealedLength: boolean +} + +/** AEAD tag length (ChaCha20-Poly1305). */ +export const TAG_LENGTH = 16 + +const printableAscii = (s: string) => s.length > 0 && s.length <= 128 && /^[\x21-\x7e]+$/.test(s) + +/** Checks a profile's invariants and freezes it. Throws on a profile that could never open its own entries. */ +export function defineProfile(p: VaultProfile): VaultProfile { + need(printableAscii(p.prfLabel) && printableAscii(p.infoLabel) && printableAscii(p.aadDocType), 'profile labels must be printable ASCII without spaces') + need(p.prfLabel !== p.infoLabel, 'the PRF and HPKE labels must differ') + need(p.entryVersion === 1, 'only entry version 1 exists') + need(p.formats.length >= 1, 'a profile needs at least one format') + need(new Set(p.formats.map((c) => c.id)).size === p.formats.length, 'format ids must be unique') + if (p.strictSealedLength) need(new Set(p.formats.map((c) => c.length)).size === 1, 'a strict profile pads every format to one length') + return Object.freeze({ ...p, formats: Object.freeze([...p.formats]) }) +} + +/** The sealed lengths a profile accepts. */ +export const sealedLengths = (p: VaultProfile): number[] => [...new Set(p.formats.map((c) => c.length + TAG_LENGTH))] diff --git a/forge-web/lib/vendor/platform-auth/passkey-vault/user-handle.ts b/forge-web/lib/vendor/platform-auth/passkey-vault/user-handle.ts new file mode 100644 index 000000000..4e4c1c71d --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/passkey-vault/user-handle.ts @@ -0,0 +1,27 @@ +// The WebAuthn user handle of a vault passkey: identityId ‖ vaultContractId, 64 bytes (WebAuthn's maximum), binary. +// A discoverable sign-in learns from it which identity's entry to read and that the passkey is this vault's. Two deployments of one +// relying party (testnet and mainnet contracts) never share a handle, so a provider never replaces one network's passkey with the +// other's (providers replace a passkey with the same relying party and user handle). +import { bytesEqual } from './bytes' +import { need, PasskeyError } from './errors' + +export const USER_HANDLE_LENGTH = 64 + +export function userHandleFor(identityId: Uint8Array, contractId: Uint8Array): Uint8Array { + need(identityId.length === 32 && contractId.length === 32, 'the identity and contract ids must be 32 bytes') + const handle = new Uint8Array(USER_HANDLE_LENGTH) + handle.set(identityId) + handle.set(contractId, 32) + return handle +} + +/** + * The identity a user handle names for this vault contract. Throws `PasskeyError` 'not-vault' when the handle is absent or not 64 + * bytes (an app's local-only passkey with a random 32-byte id, say), and 'other-vault' when it names another vault contract. + */ +export function parseUserHandle(handle: Uint8Array | null | undefined, contractId: Uint8Array): Uint8Array { + need(contractId.length === 32, 'the contract id must be 32 bytes') + if (!handle || handle.length !== USER_HANDLE_LENGTH) throw new PasskeyError("This passkey doesn't hold a key on Platform.", 'not-vault') + if (!bytesEqual(handle.subarray(32), contractId)) throw new PasskeyError("This passkey is set up for another network or app.", 'other-vault') + return handle.slice(0, 32) +} diff --git a/forge-web/lib/vendor/platform-auth/passkey-vault/vault.test.ts b/forge-web/lib/vendor/platform-auth/passkey-vault/vault.test.ts new file mode 100644 index 000000000..9e512a8ce --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/passkey-vault/vault.test.ts @@ -0,0 +1,458 @@ +import { describe, expect, it } from 'vitest' +import { secp256k1 } from '@noble/curves/secp256k1.js' +import { ripemd160 } from '@noble/hashes/legacy.js' +import { sha256 } from '@noble/hashes/sha2.js' +import { bytesToHex } from '@noble/hashes/utils.js' +import { bytesEqual } from './bytes' +import type { SlotBundle, SlotKey } from './codecs' +import { recipientFromPrf, sealEntry } from './entry' +import { PasskeyError, VaultError } from './errors' +import type { OnChainKey } from './port' +import { userHandleFor } from './user-handle' +import { checkSlots, matchKey, type DropReason } from './verify' +import { PasskeyVault, type ConfirmedPasskey } from './vault' +import { fakePasskeyAdapter, type FakePasskeyOptions } from './__fixtures__/fake-passkey' +import { MemoryVaultPort } from './__fixtures__/memory-port' +import { forgeProfile, forgeSlots } from './__fixtures__/profiles' + +const H = (label: string) => sha256(new TextEncoder().encode(label)) +const hex = bytesToHex +const NOW = 1_800_000_000_000 +const DAY = 86_400_000 +const contractId = H('forge-meta contract') +const ownerId = H('owner identity') +const group = H('dash-forge group') + +const MAIN: SlotKey = { purpose: 0, securityLevel: 2, keyType: 0, keyId: 3, privateKey: H('main key') } +const GRANT: SlotKey = { purpose: 0, securityLevel: 2, keyType: 2, keyId: 4, privateKey: H('grant key') } +const ENC: SlotKey = { purpose: 1, securityLevel: 3, keyType: 0, keyId: 5, privateKey: H('encryption key') } + +function onChain(k: SlotKey, over: Partial = {}): OnChainKey { + const point = secp256k1.getPublicKey(k.privateKey, true) + return { + id: k.keyId, + purpose: k.purpose, + securityLevel: k.securityLevel, + type: k.keyType, + data: k.keyType === 2 ? ripemd160(sha256(point)) : point, + disabled: false, + ...(k.purpose === 0 ? { contractBounds: { kind: 'contractGroup' as const, groupId: group }, expiresAt: NOW + 90 * DAY, totalBudget: 5_000_000_000n, remainingBudget: 4_000_000_000n } : {}), + ...over, + } +} + +interface Session { + ownerId: Uint8Array + keys: SlotKey[] +} +interface Verified { + keys: SlotKey[] + dropped: Array<[number, DropReason]> +} + +const copyKeys = (keys: readonly SlotKey[]) => keys.map((k) => ({ ...k, privateKey: k.privateKey.slice() })) + +function setup(o: { adapter?: FakePasskeyOptions; maxPasskeys?: number } = {}) { + const port = new MemoryVaultPort() + port.setKeys(ownerId, [onChain(MAIN), onChain(GRANT), onChain(ENC)]) + const adapter = fakePasskeyAdapter(o.adapter) + const seen: SlotBundle[] = [] + const vault = new PasskeyVault({ + profile: forgeProfile, + codec: forgeSlots, + port, + adapter, + rpId: 'forge.dashhq.org', + rpName: 'Dash Forge', + contractId, + maxPasskeys: o.maxPasskeys, + ownerOf: (s) => s.ownerId, + bundleFor: (s) => ({ format: 1, keys: copyKeys(s.keys) }), + now: () => NOW, + sleep: async () => {}, + verify(bundle, keys, ctx) { + seen.push(bundle) + const { accepted, dropped } = checkSlots(bundle.keys, keys, { + now: ctx.now, + expiryMarginMs: 60_000, + // slot 0 must be budgeted and bound to the app's group + accept: (_slot, key, index) => + index > 0 || (key.totalBudget !== undefined && key.contractBounds?.kind === 'contractGroup' && bytesEqual(key.contractBounds.groupId, group)), + }) + if (accepted[0]?.index !== 0) throw new VaultError("The key in this passkey isn't an active key of the identity.", 'refused') + return { keys: copyKeys(accepted.map((a) => a.slot)), dropped: dropped.map((d) => [d.index, d.reason]) } + }, + }) + const session: Session = { ownerId, keys: [MAIN, GRANT, ENC] } + return { port, adapter, vault, session, seen } +} + +async function addPasskey(t: ReturnType, session = t.session) { + const pending = await t.vault.enroll(session, { userName: 'alice' }) + const confirmed = await t.vault.confirm(pending) + const entry = await t.vault.store(session, confirmed) + return { pending, confirmed, entry } +} + +const errCode = async (p: Promise) => { + try { + await p + } catch (e) { + if (e instanceof VaultError || e instanceof PasskeyError) return e.code + throw e + } + return 'ok' +} + +describe('matchKey and checkSlots', () => { + it('matches a compressed point or its hash160, nothing else', () => { + expect(matchKey(MAIN.privateKey, onChain(MAIN))).toBe(true) + expect(matchKey(GRANT.privateKey, onChain(GRANT))).toBe(true) + expect(matchKey(MAIN.privateKey, onChain(GRANT))).toBe(false) + expect(matchKey(MAIN.privateKey, { ...onChain(MAIN), type: 1 })).toBe(false) + expect(matchKey(new Uint8Array(32), onChain(MAIN))).toBe(false) + }) + + it('drops each kind of unusable key with its reason, and keeps the rest in order', () => { + const slots = [MAIN, GRANT, ENC, { ...ENC, keyId: 9 }, { ...GRANT, keyId: 10 }, { ...GRANT, keyId: 11 }, { ...GRANT, keyId: 12 }, { ...GRANT, keyId: 13 }] + const chain = [ + onChain(MAIN), + onChain(GRANT, { disabled: true }), + onChain(ENC), + onChain({ ...GRANT, keyId: 10 }, { expiresAt: NOW + 30_000 }), + onChain({ ...GRANT, keyId: 11 }, { remainingBudget: 0n }), + onChain({ ...GRANT, keyId: 12, privateKey: H('other') }), + onChain({ ...GRANT, keyId: 13 }, { securityLevel: 1 }), + ] + const { accepted, dropped } = checkSlots(slots, chain, { now: NOW, expiryMarginMs: 60_000, accept: (_s, k) => k.id !== 5 }) + expect(accepted.map((a) => a.index)).toEqual([0]) + expect(dropped.map((d) => [d.index, d.reason])).toEqual([ + [1, 'disabled'], + [2, 'rule'], + [3, 'missing'], + [4, 'expired'], + [5, 'spent'], + [6, 'mismatch'], + [7, 'shape'], + ]) + // an unknown budget is not a spent one + expect(checkSlots([MAIN], [onChain(MAIN, { remainingBudget: undefined })], { now: NOW }).accepted).toHaveLength(1) + }) +}) + +describe('PasskeyVault: add a passkey and sign in with it', () => { + it('enrols, confirms, seals and writes one 256-byte entry, then opens it on another device', async () => { + const t = setup() + const { pending, confirmed, entry } = await addPasskey(t) + const create = t.adapter.calls.create[0]! + expect(hex(create.userHandle)).toBe(hex(userHandleFor(ownerId, contractId))) + expect(hex(create.prfInput)).toBe(hex(t.vault.prfInput)) + expect(create.exclude).toEqual([]) + expect(t.adapter.calls.get[0]!.allow.map(hex)).toEqual([hex(pending.credentialId)]) + expect(entry.sealed.length).toBe(256) + expect(entry.authKeyId).toBe(3) + expect(hex(confirmed.recipientKey)).toBe(hex(recipientFromPrf(t.adapter.prfOf(pending.credentialId, t.vault.prfInput)).publicKey)) + expect(t.port.entries).toHaveLength(1) + await t.vault.waitForEntry(ownerId, pending.credentialId, confirmed.recipientKey) + + const opened = await t.vault.open({ keepPrfOutput: true }) + expect(hex(opened.ownerId)).toBe(hex(ownerId)) + expect(opened.result.keys.map((k) => k.keyId)).toEqual([3, 4, 5]) + expect(hex(opened.result.keys[0]!.privateKey)).toBe(hex(MAIN.privateKey)) + expect(opened.result.dropped).toEqual([]) + // the PRF output is handed over for the local vault, and is the credential's output for the vault's PRF input + expect(hex(opened.prfOutput!)).toBe(hex(t.adapter.prfOf(pending.credentialId, t.vault.prfInput))) + expect(t.adapter.calls.get.at(-1)!.allow).toEqual([]) + // the bundle the check saw is wiped; what it returned survives + expect(t.seen[0]!.keys.every((k) => k.privateKey.every((b) => b === 0))).toBe(true) + // the session's own keys are untouched by sealing + expect(hex(MAIN.privateKey)).toBe(hex(H('main key'))) + }) + + it('wipes the PRF output unless asked to keep it', async () => { + const t = setup() + await addPasskey(t) + let prf: Uint8Array | undefined + const get = t.adapter.get.bind(t.adapter) + t.adapter.get = async (o) => { + const a = await get(o) + prf = a.prfOutput + return a + } + const opened = await t.vault.open() + expect(opened.prfOutput).toBeNull() + expect(prf!.every((b) => b === 0)).toBe(true) + }) + + it('checks the create-time PRF against the get-time one and wipes both', async () => { + const t = setup({ adapter: { prfAtCreate: true } }) + const pending = await t.vault.enroll(t.session, { userName: 'alice' }) + expect(pending.createPrf).not.toBeNull() + const createPrf = pending.createPrf! + await t.vault.confirm(pending) + expect(createPrf.every((b) => b === 0)).toBe(true) + + const other = await t.vault.enroll({ ownerId: H('another owner'), keys: [MAIN] }, { userName: 'bob' }) + other.createPrf![0]! ^= 1 + expect(await errCode(t.vault.confirm(other))).toBe('mismatch') + }) + + it('excludes the existing passkeys and stops at the cap', async () => { + const t = setup({ maxPasskeys: 2, adapter: { multiDevice: true } }) + const first = await addPasskey(t) + await addPasskey(t, { ownerId, keys: [MAIN] }) + expect(t.adapter.calls.create[1]!.exclude.map(hex)).toEqual([hex(first.pending.credentialId)]) + expect(await errCode(t.vault.enroll(t.session, { userName: 'alice' }))).toBe('too-many') + expect(t.adapter.calls.create).toHaveLength(2) + }) + + it('refuses a passkey with no PRF, and abandon tells the provider', async () => { + const t = setup({ adapter: { prf: false } }) + const pending = await t.vault.enroll(t.session, { userName: 'alice' }) + expect(pending.prfEnabled).toBe(false) + expect(await errCode(t.vault.confirm(pending))).toBe('no-prf') + await t.vault.abandon(pending) + expect(t.adapter.signalled.map(hex)).toEqual([hex(pending.credentialId)]) + expect(t.port.entries).toHaveLength(0) + }) + + it("refuses a credential id outside 16 to 255 bytes and drops it from the provider", async () => { + const t = setup({ adapter: { credentialIdLength: 15 } }) + expect(await errCode(t.vault.enroll(t.session, { userName: 'alice' }))).toBe('unsupported') + expect(t.adapter.signalled).toHaveLength(1) + }) + + it("confirm refuses a handle for another identity, another vault, or none", async () => { + const t = setup() + const pending = await t.vault.enroll(t.session, { userName: 'alice' }) + t.adapter.overrideNextHandle(userHandleFor(H('someone else'), contractId)) + expect(await errCode(t.vault.confirm(pending))).toBe('other-identity') + t.adapter.overrideNextHandle(userHandleFor(ownerId, H('testnet contract'))) + expect(await errCode(t.vault.confirm(pending))).toBe('other-vault') + t.adapter.overrideNextHandle(null) + expect(await errCode(t.vault.confirm(pending))).toBe('not-vault') + expect(t.port.entries).toHaveLength(0) + }) + + it('a cancelled confirm can be retried (the pending record is kept)', async () => { + const t = setup({ adapter: { prfAtCreate: true } }) + const pending = await t.vault.enroll(t.session, { userName: 'alice' }) + t.adapter.failNext(new PasskeyError('closed', 'cancelled')) + expect(await errCode(t.vault.confirm(pending))).toBe('cancelled') + expect(pending.createPrf!.some((b) => b !== 0)).toBe(true) + const confirmed = await t.vault.confirm(pending) + expect(pending.createPrf).toBeNull() + // after a failed store (say, the node refused the write) the same pending enrolment confirms again + await t.vault.confirm(pending) + await t.vault.store(t.session, confirmed) + expect(t.port.entries).toHaveLength(1) + }) + + it('waits for a lagging node, and says when the entry is not visible', async () => { + const t = setup() + t.port.lag = 3 + const { pending, confirmed } = await addPasskey(t) + await expect(t.vault.waitForEntry(ownerId, pending.credentialId, confirmed.recipientKey, { reads: 5 })).resolves.toBeTruthy() + expect(await errCode(t.vault.waitForEntry(ownerId, H('nothing').slice(0, 16), confirmed.recipientKey, { reads: 2 }))).toBe('not-visible') + // the last read's error propagates + t.port.byCredential = async () => { + throw new Error('node down') + } + await expect(t.vault.waitForEntry(ownerId, pending.credentialId, confirmed.recipientKey, { reads: 2 })).rejects.toThrow('node down') + }) +}) + +describe('PasskeyVault: never seal to an untrusted recipient', () => { + it('store refuses a ConfirmedPasskey it did not mint, and one for another identity', async () => { + const t = setup() + const forged: ConfirmedPasskey = { ownerId, credentialId: H('cred').slice(0, 16), recipientKey: recipientFromPrf(H('attacker prf')).publicKey, source: 'passkey' } + expect(await errCode(t.vault.store(t.session, forged))).toBe('untrusted-recipient') + // a local marker vouches for re-sealing only, never for a new entry + const marker = t.vault.trustMarker({ ownerId, credentialId: H('cred').slice(0, 16), recipientKey: forged.recipientKey }) + expect(await errCode(t.vault.store(t.session, marker as ConfirmedPasskey))).toBe('untrusted-recipient') + const { confirmed } = await addPasskey(t) + expect(await errCode(t.vault.store({ ownerId: H('another owner'), keys: [MAIN] }, confirmed))).toBe('other-identity') + // another vault instance's confirmation is not this one's + const t2 = setup() + expect(await errCode(t2.vault.store(t2.session, confirmed))).toBe('untrusted-recipient') + expect(t.port.writes.map((w) => w.op)).toEqual(['create']) + }) + + it('mutating a confirmation changes nothing: the private copy is sealed to', async () => { + const t = setup() + const pending = await t.vault.enroll(t.session, { userName: 'alice' }) + const confirmed = await t.vault.confirm(pending) + const real = hex(confirmed.recipientKey) + confirmed.recipientKey.set(recipientFromPrf(H('attacker prf')).publicKey) + const entry = await t.vault.store(t.session, confirmed) + expect(hex(entry.recipientKey)).toBe(real) + }) + + it('reseal: only to a trusted recipient key that the entry, re-read, still has', async () => { + const t = setup() + const { confirmed } = await addPasskey(t) + const [entry] = await t.vault.list(ownerId) + // a key change in this tab: the session now holds only the main key + const next: Session = { ownerId, keys: [MAIN] } + // the app's local marker for a passkey this device made + const marker = t.vault.trustMarker({ ownerId, credentialId: confirmed.credentialId, recipientKey: confirmed.recipientKey }) + await t.vault.reseal(entry!, next, { trustedRecipient: marker }) + expect(t.port.entries[0]!.revision).toBe(2) + expect((await t.vault.open()).result.keys.map((k) => k.keyId)).toEqual([3]) + + const [latest] = await t.vault.list(ownerId) + // raw bytes are not a TrustedRecipient: the types refuse them, and so does the vault at run time + const raw = { ownerId, credentialId: confirmed.credentialId, recipientKey: latest!.recipientKey, source: 'marker' as const } + expect(await errCode(t.vault.reseal(latest!, next, { trustedRecipient: raw }))).toBe('untrusted-recipient') + const wrongKey = t.vault.trustMarker({ ownerId, credentialId: confirmed.credentialId, recipientKey: recipientFromPrf(H('x')).publicKey }) + expect(await errCode(t.vault.reseal(latest!, next, { trustedRecipient: wrongKey }))).toBe('untrusted-recipient') + const otherCred = t.vault.trustMarker({ ownerId, credentialId: H('other cred').slice(0, 16), recipientKey: confirmed.recipientKey }) + expect(await errCode(t.vault.reseal(latest!, next, { trustedRecipient: otherCred }))).toBe('untrusted-recipient') + expect(await errCode(t.vault.reseal(latest!, { ownerId: H('another owner'), keys: [MAIN] }, { trustedRecipient: marker }))).toBe('other-identity') + // a marker whose key the chain no longer has is refused after the re-read + const stale = t.vault.trustMarker({ ownerId, credentialId: confirmed.credentialId, recipientKey: H('stale') }) + expect(await errCode(t.vault.reseal({ ...latest!, recipientKey: H('stale') }, next, { trustedRecipient: stale }))).toBe('untrusted-recipient') + expect(t.port.entries[0]!.revision).toBe(2) + }) + + it('a planted entry naming the user\'s credential but an attacker\'s recipient key is never re-sealed to', async () => { + const t = setup() + const { pending } = await addPasskey(t) + // an attacker who held a live key replaces the entry with one sealed to their own recipient key + t.port.entries = [] + const attackerRecipient = recipientFromPrf(H('attacker prf')).publicKey + t.port.plant(ownerId, sealEntry(forgeProfile, { contractId, ownerId, credentialId: pending.credentialId, recipientKey: attackerRecipient, bundle: { format: 1, keys: [MAIN] }, codec: forgeSlots })) + const [planted] = await t.vault.list(ownerId) + // "Needs update" re-seal asks the passkey: its PRF does not give the planted recipient key + expect(await errCode(t.vault.confirm({ ownerId, credentialId: planted!.credentialId, recipientKey: planted!.recipientKey }))).toBe('mismatch') + // nor can a confirmation for the real passkey be used to seal to the planted key + const real = await t.vault.confirm({ ownerId, credentialId: planted!.credentialId }) + expect(await errCode(t.vault.reseal(planted!, t.session, { trustedRecipient: real }))).toBe('untrusted-recipient') + // storing to the confirmed passkey replaces the unopenable entry (recipient keys are immutable: delete, then create) + await t.vault.store(t.session, real) + expect(t.port.writes.map((w) => w.op).slice(-2)).toEqual(['delete', 'create']) + expect(hex(t.port.entries[0]!.recipientKey)).toBe(hex(real.recipientKey)) + }) + + it('replacing an unopenable entry writes nothing when sealing fails', async () => { + const t = setup() + const { pending } = await addPasskey(t) + t.port.entries = [] + t.port.plant(ownerId, sealEntry(forgeProfile, { contractId, ownerId, credentialId: pending.credentialId, recipientKey: recipientFromPrf(H('attacker prf')).publicKey, bundle: { format: 1, keys: [MAIN] }, codec: forgeSlots })) + const real = await t.vault.confirm({ ownerId, credentialId: pending.credentialId }) + const writes = t.port.writes.length + // a session holding a key the codec refuses (CRITICAL) cannot be sealed + await expect(t.vault.store({ ownerId, keys: [{ ...MAIN, securityLevel: 1 }] }, real)).rejects.toThrow(/slot 0/) + expect(t.port.writes.length).toBe(writes) + expect(t.port.entries).toHaveLength(1) + }) + + it('reseal with a confirmation for that entry works; one for another entry does not', async () => { + const t = setup({ adapter: { multiDevice: true } }) + const a = await addPasskey(t) + const b = await addPasskey(t) + const entries = await t.vault.list(ownerId) + const entryA = entries.find((e) => bytesEqual(e.credentialId, a.pending.credentialId))! + const confirmA = await t.vault.confirm(entryA) + await t.vault.reseal(entryA, t.session, { trustedRecipient: confirmA }) + expect(await errCode(t.vault.reseal(entryA, t.session, { trustedRecipient: b.confirmed }))).toBe('untrusted-recipient') + }) +}) + +describe('PasskeyVault: the chain check on open', () => { + async function plantFor(t: ReturnType, keys: SlotKey[]) { + const { pending, confirmed } = await addPasskey(t) + t.port.entries = [] + t.port.plant(ownerId, sealEntry(forgeProfile, { contractId, ownerId, credentialId: pending.credentialId, recipientKey: confirmed.recipientKey, bundle: { format: 1, keys }, codec: forgeSlots })) + } + + it('refuses a planted bundle whose keys the identity does not have', async () => { + const t = setup() + await plantFor(t, [{ ...MAIN, privateKey: H('attacker key') }]) + expect(await errCode(t.vault.open())).toBe('refused') + expect(t.seen[0]!.keys[0]!.privateKey.every((b) => b === 0)).toBe(true) + }) + + it('refuses a disabled, expired, spent, unbounded or foreign-group main key', async () => { + for (const over of [ + { disabled: true }, + { expiresAt: NOW - 1 }, + { remainingBudget: 0n }, + { contractBounds: undefined, totalBudget: undefined }, + { contractBounds: { kind: 'contractGroup' as const, groupId: H('another group') } }, + ]) { + const t = setup() + await addPasskey(t) + t.port.setKeys(ownerId, [onChain(MAIN, over), onChain(GRANT), onChain(ENC)]) + expect(await errCode(t.vault.open())).toBe('refused') + } + }) + + it('drops failing extras and signs in with the rest', async () => { + const t = setup() + await addPasskey(t) + t.port.setKeys(ownerId, [onChain(MAIN), onChain(GRANT, { disabled: true }), onChain({ ...ENC, privateKey: H('rotated encryption key') })]) + const opened = await t.vault.open() + expect(opened.result.keys.map((k) => k.keyId)).toEqual([3]) + expect(opened.result.dropped).toEqual([ + [1, 'disabled'], + [2, 'mismatch'], + ]) + }) + + it('no entry, an unknown identity, a local-only passkey and another vault are each refused', async () => { + const t = setup() + const { pending } = await addPasskey(t) + t.port.entries = [] + expect(await errCode(t.vault.open())).toBe('no-entry') + await t.vault.store(t.session, await t.vault.confirm(pending)) + t.port.identities.clear() + expect(await errCode(t.vault.open())).toBe('unknown-identity') + t.adapter.overrideNextHandle(H('local-only random user.id')) + expect(await errCode(t.vault.open())).toBe('not-vault') + t.adapter.overrideNextHandle(userHandleFor(ownerId, H('testnet contract'))) + expect(await errCode(t.vault.open())).toBe('other-vault') + }) + + it('a failed key read propagates as itself', async () => { + const t = setup() + await addPasskey(t) + t.port.identityKeys = async () => { + throw new Error('node timeout') + } + await expect(t.vault.open()).rejects.toThrow('node timeout') + }) +}) + +describe('PasskeyVault: remove', () => { + it('signals the provider only for this device\'s passkeys', async () => { + const t = setup({ adapter: { multiDevice: true } }) + await addPasskey(t) + await addPasskey(t) + const [a, b] = await t.vault.list(ownerId) + await t.vault.remove(a!) + expect(t.adapter.signalled).toHaveLength(0) + await t.vault.remove(b!, { thisDevice: true }) + expect(t.adapter.signalled.map(hex)).toEqual([hex(b!.credentialId)]) + expect(await t.vault.list(ownerId)).toHaveLength(0) + }) + + it('refuses a codec that is not in the profile', () => { + const t = setup() + expect( + () => + new PasskeyVault({ + profile: forgeProfile, + codec: { ...forgeSlots }, + port: t.port, + adapter: t.adapter, + rpId: 'x', + rpName: 'x', + contractId, + ownerOf: (s) => s.ownerId, + bundleFor: () => ({ format: 1, keys: [] }), + verify: () => ({ keys: [], dropped: [] }), + }), + ).toThrow(/not one of the profile/) + }) +}) diff --git a/forge-web/lib/vendor/platform-auth/passkey-vault/vault.ts b/forge-web/lib/vendor/platform-auth/passkey-vault/vault.ts new file mode 100644 index 000000000..05282b136 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/passkey-vault/vault.ts @@ -0,0 +1,326 @@ +// The passkey vault service: enrol a passkey, seal a session's keys to it on Platform, open them on another device, list, remove and +// re-seal. Free of the SDK and of any UI: Platform is the app's VaultPort, WebAuthn its PasskeyAdapter, the chain check its `verify`. +// +// The rule that matters (govhub service.ts storeInVault; Yappr docs/PASSKEY_VAULT.md §6-7): the vault never seals to a recipient key +// it did not derive in this tab from a passkey's PRF output, or that the caller did not vouch for from its own local record. A +// recipient key read from the chain is public and anyone holding a live key of the owner can plant an entry; sealing the user's keys +// to it would hand them over. So `store` takes only a ConfirmedPasskey minted by `confirm` in this instance, and `reseal` only a +// TrustedRecipient minted by `confirm` or `trustMarker` for that entry's credential, which the entry, re-read, must still carry. +import { bytesEqual, wipe } from './bytes' +import type { BundleCodec } from './codecs' +import { isCredentialIdLength, openEntry, prfInput, recipientFromPrf, sealEntry, type SealedVaultEntry } from './entry' +import { need, PasskeyError, VaultError } from './errors' +import type { OnChainKey, VaultEntryRecord, VaultPort } from './port' +import type { VaultProfile } from './profile' +import { parseUserHandle, userHandleFor } from './user-handle' +import type { PasskeyAdapter } from './webauthn' + +export const DEFAULT_MAX_PASSKEYS = 10 + +export interface VerifyContext { + ownerId: Uint8Array + entry: VaultEntryRecord + codec: BundleCodec + now: number +} + +export interface PasskeyVaultOptions { + profile: VaultProfile + /** The format this vault seals with (one of the profile's). */ + codec: BundleCodec + /** Picks another of the profile's formats for a session (govhub: a seed or a single key). Default: `codec`. */ + codecFor?(session: S): BundleCodec + port: VaultPort + adapter: PasskeyAdapter + rpId: string + rpName: string + /** The vault contract id (32 bytes): in the PRF input, the HPKE info and the user handle. */ + contractId: Uint8Array + /** Passkeys per identity (the client's cap; the contract has none). Default 10. */ + maxPasskeys?: number + /** The identity a session signs for. */ + ownerOf(session: S): Uint8Array + /** A fresh bundle of what the session keeps (copies of its keys): the vault wipes it after sealing. */ + bundleFor(session: S): B + /** The entry key id, for a codec with no `authKeyIdOf` (a seed bundle). */ + authKeyIdOf?(session: S): number + /** + * The chain check: decides whether an opened bundle may be used, against the owner's keys read with proofs. Throw to refuse + * (`VaultError` 'refused' is the code meant for it; anything thrown propagates as itself, so a failed read stays a failed read). + * Return what the sign-in keeps, as copies: the vault wipes the bundle as soon as this returns. + */ + verify(bundle: B, keys: OnChainKey[], ctx: VerifyContext): R | Promise + /** Clock, ms since the epoch. */ + now?(): number + /** Waits between reads in waitForEntry (tests replace it). */ + sleep?(ms: number): Promise +} + +/** A passkey just made by `enroll`. Persist only `ownerId` and `credentialId` (public); `createPrf` is secret and stays in memory. */ +export interface PendingEnrolment { + ownerId: Uint8Array + credentialId: Uint8Array + /** The PRF output at creation, when the authenticator gave one; a successful `confirm` checks it, wipes it and sets it to null. */ + createPrf: Uint8Array | null + /** Whether the authenticator said it supports PRF. False usually means `confirm` will fail with 'no-prf'. */ + prfEnabled: boolean +} + +/** What `confirm` takes: a pending enrolment, or an existing entry (whose recipient key the passkey must then give). */ +export interface ConfirmTarget { + ownerId: Uint8Array + credentialId: Uint8Array + createPrf?: Uint8Array | null + recipientKey?: Uint8Array +} + +/** + * A recipient key this vault instance trusts for one credential of one identity. Only instances it minted are honoured, and their + * bytes are kept privately (mutating these fields changes nothing). + */ +export interface TrustedRecipient { + readonly ownerId: Uint8Array + readonly credentialId: Uint8Array + readonly recipientKey: Uint8Array + /** 'passkey': the passkey gave it in this tab (`confirm`); 'marker': the app's own local record vouches for it (`trustMarker`). */ + readonly source: 'passkey' | 'marker' +} + +/** A recipient key a passkey gave in this tab (`confirm`). The only kind `store` seals a new entry to. */ +export interface ConfirmedPasskey extends TrustedRecipient { + readonly source: 'passkey' +} + +export interface OpenedVault { + ownerId: Uint8Array + credentialId: Uint8Array + entry: VaultEntryRecord + /** What `verify` returned. */ + result: R + /** The assertion's PRF output, only with `keepPrfOutput` (the caller must wipe it); otherwise null and already wiped. */ + prfOutput: Uint8Array | null +} + +export class PasskeyVault { + readonly #o: PasskeyVaultOptions + readonly #prfInput: Uint8Array + readonly #max: number + /** Minted TrustedRecipients and private copies of their bytes. */ + readonly #trusted = new WeakMap() + + constructor(options: PasskeyVaultOptions) { + need(options.profile.formats.includes(options.codec), "the codec is not one of the profile's formats") + need(options.codec.authKeyIdOf !== undefined || options.authKeyIdOf !== undefined, 'a codec without authKeyIdOf needs the authKeyIdOf option') + this.#o = { ...options, contractId: options.contractId.slice() } + this.#prfInput = prfInput(options.profile, options.contractId) + this.#max = options.maxPasskeys ?? DEFAULT_MAX_PASSKEYS + } + + /** The PRF `first` input every passkey of this vault is evaluated with. */ + get prfInput(): Uint8Array { + return this.#prfInput.slice() + } + + #now(): number { + return this.#o.now?.() ?? Date.now() + } + + #assertRoom(passkeys: number): void { + if (passkeys >= this.#max) throw new VaultError(`An identity can have ${this.#max} passkeys. Remove one first.`, 'too-many') + } + + /** + * Step 1 of adding a passkey: the create ceremony, with the 64-byte user handle, the PRF evaluated, and the owner's existing + * passkeys excluded. Writes nothing. Follow with `confirm` (its own user gesture), then `store`; or `abandon`. + */ + async enroll(session: S, o: { userName: string; displayName?: string; signal?: AbortSignal }): Promise { + const ownerId = this.#o.ownerOf(session).slice() + const entries = await this.#o.port.list(ownerId) + this.#assertRoom(entries.length) + const created = await this.#o.adapter.create({ + rpId: this.#o.rpId, + rpName: this.#o.rpName, + userHandle: userHandleFor(ownerId, this.#o.contractId), + userName: o.userName, + displayName: o.displayName, + prfInput: this.prfInput, + exclude: entries.map((e) => e.credentialId), + signal: o.signal, + }) + const pending: PendingEnrolment = { ownerId, credentialId: created.credentialId, createPrf: created.prfOutput, prfEnabled: created.prfEnabled } + if (!isCredentialIdLength(created.credentialId.length)) { + await this.abandon(pending) + throw new PasskeyError('This passkey has an unusual credential id and cannot be used.', 'unsupported', created.credentialId) + } + return pending + } + + /** + * A get ceremony restricted to one credential, whose user handle must name `target.ownerId` and this vault, and whose PRF output + * must equal the create-time one (a pending enrolment) or give `target.recipientKey` (an existing entry). Returns the recipient key + * as a ConfirmedPasskey. The assertion's PRF output is wiped; on success so is `target.createPrf` (then set to null, so a pending + * enrolment can be confirmed again after a failed store). A cancelled or refused confirm leaves the target as it was. + */ + async confirm(target: ConfirmTarget, o: { signal?: AbortSignal } = {}): Promise { + const a = await this.#o.adapter.get({ rpId: this.#o.rpId, prfInput: this.prfInput, allow: [target.credentialId], signal: o.signal }) + try { + if (!bytesEqual(a.credentialId, target.credentialId)) throw new VaultError('The browser answered with another passkey.', 'mismatch') + const identity = parseUserHandle(a.userHandle, this.#o.contractId) + if (!bytesEqual(identity, target.ownerId)) throw new VaultError('This passkey belongs to another identity.', 'other-identity') + if (target.createPrf && !bytesEqual(target.createPrf, a.prfOutput)) { + throw new VaultError('The passkey gave a different key than when it was made. Try adding it again.', 'mismatch') + } + const recipient = recipientFromPrf(a.prfOutput) + wipe(recipient.privateKey) + if (target.recipientKey && !bytesEqual(target.recipientKey, recipient.publicKey)) { + throw new VaultError("This passkey doesn't open that entry.", 'mismatch') + } + if (target.createPrf) { + wipe(target.createPrf) + target.createPrf = null + } + return this.#mint({ ownerId: target.ownerId, credentialId: target.credentialId, recipientKey: recipient.publicKey }, 'passkey') as ConfirmedPasskey + } finally { + wipe(a.prfOutput) + } + } + + /** + * Vouches for a recipient key from the app's own local record of a passkey this device made (Forge's IndexedDB marker + * `{credentialId, recipientKey}`), for `reseal` only. Never pass a key read from the chain: that is what a planted entry carries. + */ + trustMarker(marker: { ownerId: Uint8Array; credentialId: Uint8Array; recipientKey: Uint8Array }): TrustedRecipient { + need(marker.ownerId.length === 32 && marker.recipientKey.length === 32, 'the owner id and recipient key must be 32 bytes') + return this.#mint(marker, 'marker') + } + + #mint(o: Omit, source: TrustedRecipient['source']): TrustedRecipient { + const copyOf = (): TrustedRecipient => ({ ownerId: o.ownerId.slice(), credentialId: o.credentialId.slice(), recipientKey: o.recipientKey.slice(), source }) + const token = Object.freeze(copyOf()) + this.#trusted.set(token, copyOf()) + return token + } + + #seal(session: S, ownerId: Uint8Array, credentialId: Uint8Array, recipientKey: Uint8Array): SealedVaultEntry { + const { profile, contractId } = this.#o + const codec = this.#o.codecFor?.(session) ?? this.#o.codec + const bundle = this.#o.bundleFor(session) + try { + const authKeyId = codec.authKeyIdOf ? undefined : this.#o.authKeyIdOf?.(session) + return sealEntry(profile, { contractId, ownerId, credentialId, recipientKey, bundle, codec, authKeyId }) + } finally { + codec.wipe(bundle) + } + } + + #assertOwner(session: S, ownerId: Uint8Array): void { + if (!bytesEqual(this.#o.ownerOf(session), ownerId)) throw new VaultError('This passkey belongs to another identity.', 'other-identity') + } + + /** + * Seals the session to a confirmed passkey and writes (or replaces) its entry. An entry for the same credential sealed to another + * recipient key can never be opened by this passkey (recipient keys are immutable on chain): once the new entry is sealed, it is + * removed and a new one created. Nothing is written when sealing or the cap refuses. + */ + async store(session: S, confirmed: ConfirmedPasskey): Promise { + const t = this.#trusted.get(confirmed) + if (!t || t.source !== 'passkey') throw new VaultError('Only a passkey confirmed in this tab can be sealed to.', 'untrusted-recipient') + this.#assertOwner(session, t.ownerId) + const { port } = this.#o + const existing = await port.byCredential(t.ownerId, t.credentialId) + if (existing && !bytesEqual(existing.ownerId, t.ownerId)) throw new VaultError('The entry belongs to another identity.', 'other-identity') + const stale = existing !== null && !bytesEqual(existing.recipientKey, t.recipientKey) + if (!existing || stale) { + const others = (await port.list(t.ownerId)).filter((e) => !bytesEqual(e.credentialId, t.credentialId)) + this.#assertRoom(others.length) + } + const entry = this.#seal(session, t.ownerId, t.credentialId, t.recipientKey) + if (existing && stale) await port.remove({ ownerId: t.ownerId, entry: existing }) + await port.put({ ownerId: t.ownerId, entry, existing: stale ? null : existing }) + return entry + } + + /** + * Re-seals an existing entry with the session's current keys, to a TrustedRecipient for that credential (from `confirm`, or + * `trustMarker` for this device's own passkeys). The entry, re-read with proofs, must still be sealed to it. + */ + async reseal(entry: VaultEntryRecord, session: S, o: { trustedRecipient: TrustedRecipient }): Promise { + const ownerId = entry.ownerId.slice() + this.#assertOwner(session, ownerId) + const t = this.#trusted.get(o.trustedRecipient) + if (!t) throw new VaultError('Only a recipient key this vault was given to trust can be sealed to.', 'untrusted-recipient') + if (!bytesEqual(t.ownerId, ownerId) || !bytesEqual(t.credentialId, entry.credentialId)) { + throw new VaultError('That trusted key is for another passkey.', 'untrusted-recipient') + } + const fresh = await this.#o.port.byCredential(ownerId, entry.credentialId) + if (!fresh) throw new VaultError('The entry is gone.', 'no-entry') + if (!bytesEqual(fresh.ownerId, ownerId) || !bytesEqual(fresh.recipientKey, t.recipientKey)) { + throw new VaultError('This entry is sealed to a key this device does not trust.', 'untrusted-recipient') + } + const sealed = this.#seal(session, ownerId, entry.credentialId, t.recipientKey) + await this.#o.port.put({ ownerId, entry: sealed, existing: fresh }) + return sealed + } + + /** + * Waits until a proved read shows the entry sealed to `recipientKey` (nodes can lag a block): at most `reads` reads (default 15), + * `intervalMs` apart. A read that fails is retried, except the last, whose error propagates. + */ + async waitForEntry(ownerId: Uint8Array, credentialId: Uint8Array, recipientKey: Uint8Array, o: { reads?: number; intervalMs?: number } = {}): Promise { + const reads = Math.max(1, o.reads ?? 15) + const sleep = this.#o.sleep ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))) + for (let i = 1; ; i += 1) { + const last = i >= reads + const read = this.#o.port.byCredential(ownerId, credentialId) + const e = last ? await read : await read.catch(() => null) + if (e && bytesEqual(e.recipientKey, recipientKey)) return e + if (last) throw new VaultError('The passkey entry is not visible on Platform yet. Check again in a minute.', 'not-visible') + await sleep(o.intervalMs ?? 2000) + } + } + + /** + * Sign-in: one get ceremony (discoverable unless `allow` is given), the entry its user handle and credential id name, opened with + * its PRF output, then the app's chain check against the owner's keys read with proofs. The bundle is wiped once `verify` returns. + */ + async open(o: { allow?: readonly Uint8Array[]; keepPrfOutput?: boolean; signal?: AbortSignal } = {}): Promise> { + const a = await this.#o.adapter.get({ rpId: this.#o.rpId, prfInput: this.prfInput, allow: o.allow ?? [], signal: o.signal }) + let keep = false + try { + const ownerId = parseUserHandle(a.userHandle, this.#o.contractId) + const entry = await this.#o.port.byCredential(ownerId, a.credentialId) + if (!entry) throw new VaultError('No entry for this passkey. It may have been removed; sign in another way and add it again.', 'no-entry') + if (!bytesEqual(entry.ownerId, ownerId)) throw new VaultError('The entry belongs to another identity.', 'other-identity') + if (!bytesEqual(entry.credentialId, a.credentialId)) throw new VaultError('The entry is for another passkey.', 'mismatch') + const { codec, bundle } = openEntry(this.#o.profile, { contractId: this.#o.contractId, ownerId, entry, prfOutput: a.prfOutput }) + let result: R + try { + const keys = await this.#o.port.identityKeys(ownerId) + if (!keys) throw new VaultError('The identity this passkey names was not found.', 'unknown-identity') + result = await this.#o.verify(bundle, keys, { ownerId, entry, codec, now: this.#now() }) + } finally { + codec.wipe(bundle) + } + keep = o.keepPrfOutput === true + return { ownerId, credentialId: a.credentialId, entry, result, prfOutput: keep ? a.prfOutput : null } + } finally { + if (!keep) wipe(a.prfOutput) + } + } + + list(ownerId: Uint8Array): Promise { + return this.#o.port.list(ownerId) + } + + /** Deletes an entry. Tell the provider only about this device's own passkeys (`thisDevice`): another may be anyone's credential id. */ + async remove(entry: VaultEntryRecord, o: { thisDevice?: boolean } = {}): Promise { + await this.#o.port.remove({ ownerId: entry.ownerId, entry }) + if (o.thisDevice) await this.#o.adapter.signalUnknown?.(this.#o.rpId, entry.credentialId) + } + + /** Drops a passkey made but never stored (no PRF, the dialog closed, the confirm failed): wipes its PRF output, tells the provider. */ + async abandon(pending: Pick): Promise { + wipe(pending.createPrf) + await this.#o.adapter.signalUnknown?.(this.#o.rpId, pending.credentialId) + } +} diff --git a/forge-web/lib/vendor/platform-auth/passkey-vault/verify.ts b/forge-web/lib/vendor/platform-auth/passkey-vault/verify.ts new file mode 100644 index 000000000..f5e1c78a8 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/passkey-vault/verify.ts @@ -0,0 +1,89 @@ +// The chain check's building blocks. HPKE authenticates nobody, so every key from an opened bundle must be checked against the +// owner's keys read fresh with proofs before anything uses it. These helpers do the checks every app shares; the app adds its own +// (contract bounds, group, budget policy) through `accept`, and decides what a dropped slot 0 means (it should refuse the sign-in). +import { secp256k1 } from '@noble/curves/secp256k1.js' +import { ripemd160 } from '@noble/hashes/legacy.js' +import { sha256 } from '@noble/hashes/sha2.js' +import { bytesEqual } from './bytes' +import type { SlotKey } from './codecs' +import { KeyType, type OnChainKey } from './port' + +/** Whether `privateKey` is the private half of `key`: its compressed point (ECDSA_SECP256K1) or that point's hash160 (ECDSA_HASH160). */ +export function matchKey(privateKey: Uint8Array, key: Pick): boolean { + let publicKey: Uint8Array + try { + publicKey = secp256k1.getPublicKey(privateKey, true) + } catch { + return false + } + if (key.type === KeyType.ECDSA_SECP256K1) return bytesEqual(publicKey, key.data) + if (key.type === KeyType.ECDSA_HASH160) return bytesEqual(ripemd160(sha256(publicKey)), key.data) + return false +} + +export type DropReason = + /** No key with this id on the identity (or a node behind: the app may prefer "try again" for slot 0). */ + | 'missing' + | 'disabled' + | 'expired' + /** The budget is known to be spent. An unknown budget is not a spent one. */ + | 'spent' + /** The slot's purpose, level or type is not the key's on chain. */ + | 'shape' + /** The private key does not match the key on chain. */ + | 'mismatch' + /** The app's `accept` refused it. */ + | 'rule' + +export interface SlotRules { + /** ms since the epoch. */ + now: number + /** A key expiring within this margin counts as expired (default 0). */ + expiryMarginMs?: number + /** The app's own rule for a key that passed the shared checks. */ + accept?(slot: Readonly, key: OnChainKey, index: number): boolean +} + +export interface AcceptedSlot { + index: number + /** The bundle's slot: its private key is the bundle's and is wiped with it. Copy what you keep. */ + slot: SlotKey + key: OnChainKey +} + +export interface DroppedSlot { + index: number + slot: SlotKey + reason: DropReason +} + +/** + * Checks each slot against the identity's keys: same id, purpose, level and type; enabled; not expiring within the margin; budget not + * known to be spent; the private key matches; then the app's rule. Returns the slots in bundle order, split. + */ +export function checkSlots(keys: readonly SlotKey[], onChain: readonly OnChainKey[], rules: SlotRules): { accepted: AcceptedSlot[]; dropped: DroppedSlot[] } { + const accepted: AcceptedSlot[] = [] + const dropped: DroppedSlot[] = [] + keys.forEach((slot, index) => { + const key = onChain.find((k) => k.id === slot.keyId) + if (!key) { + dropped.push({ index, slot, reason: 'missing' }) + return + } + const reason = dropReason(slot, key, index, rules) + if (reason) dropped.push({ index, slot, reason }) + else accepted.push({ index, slot, key }) + }) + return { accepted, dropped } +} + +/** Why `slot` may not use the on-chain `key` of its id, or null when it may. */ +function dropReason(slot: SlotKey, key: OnChainKey, index: number, rules: SlotRules): DropReason | null { + if (key.purpose !== slot.purpose || key.securityLevel !== slot.securityLevel || key.type !== slot.keyType) return 'shape' + if (key.disabled) return 'disabled' + if (key.expiresAt !== undefined && key.expiresAt - rules.now <= (rules.expiryMarginMs ?? 0)) return 'expired' + if (key.remainingBudget !== undefined && key.remainingBudget <= 0n) return 'spent' + if (!matchKey(slot.privateKey, key)) return 'mismatch' + if (rules.accept && !rules.accept(slot, key, index)) return 'rule' + return null +} diff --git a/forge-web/lib/vendor/platform-auth/passkey-vault/webauthn.test.ts b/forge-web/lib/vendor/platform-auth/passkey-vault/webauthn.test.ts new file mode 100644 index 000000000..afb123426 --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/passkey-vault/webauthn.test.ts @@ -0,0 +1,198 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { hmac } from '@noble/hashes/hmac.js' +import { sha256 } from '@noble/hashes/sha2.js' +import { bytesToHex } from '@noble/hashes/utils.js' +import { PasskeyError } from './errors' +import { parseUserHandle, userHandleFor } from './user-handle' +import { browserPasskeyAdapter, defaultPasskeyError, prfSupport } from './webauthn' +import { fakePasskeyAdapter } from './__fixtures__/fake-passkey' + +const H = (label: string) => sha256(new TextEncoder().encode(label)) +const identity = H('identity') +const contract = H('contract') +const ab = (b: Uint8Array) => b.slice().buffer as ArrayBuffer +const bytes = (b: BufferSource | undefined) => (b instanceof ArrayBuffer ? new Uint8Array(b) : b ? new Uint8Array(b.buffer, b.byteOffset, b.byteLength) : null) + +function credential(o: { rawId: Uint8Array; prf?: Uint8Array | null; enabled?: boolean; userHandle?: Uint8Array | null }) { + return { + rawId: ab(o.rawId), + response: { userHandle: o.userHandle ? ab(o.userHandle) : null }, + getClientExtensionResults: () => ({ prf: { enabled: o.enabled, results: o.prf ? { first: ab(o.prf) } : undefined } }), + } +} + +function stubCredentials(impl: { create?: (o: CredentialCreationOptions) => Promise; get?: (o: CredentialRequestOptions) => Promise }) { + const create = vi.fn(impl.create ?? (async () => null)) + const get = vi.fn(impl.get ?? (async () => null)) + vi.stubGlobal('navigator', { credentials: { create, get } }) + return { create, get } +} + +afterEach(() => { + vi.unstubAllGlobals() + vi.useRealTimers() +}) + +const createOptions = { rpId: 'forge.dashhq.org', rpName: 'Dash Forge', userHandle: userHandleFor(identity, contract), userName: 'alice', prfInput: H('prf input'), exclude: [H('old').slice(0, 16)] } + +describe('user handle', () => { + it('is identity ‖ contract, 64 bytes, and parses back to the identity', () => { + const handle = userHandleFor(identity, contract) + expect(handle.length).toBe(64) + expect(bytesToHex(handle)).toBe(bytesToHex(identity) + bytesToHex(contract)) + expect(bytesToHex(parseUserHandle(handle, contract))).toBe(bytesToHex(identity)) + }) + + it("refuses a missing or short handle as 'not-vault' and another contract's as 'other-vault'", () => { + const codeOf = (h: Uint8Array | null) => { + try { + parseUserHandle(h, contract) + } catch (e) { + return e instanceof PasskeyError ? e.code : 'other' + } + return 'ok' + } + expect(codeOf(null)).toBe('not-vault') + expect(codeOf(H('a local-only passkey: random 32-byte user.id'))).toBe('not-vault') + expect(codeOf(new Uint8Array(65))).toBe('not-vault') + expect(codeOf(userHandleFor(identity, H('testnet contract')))).toBe('other-vault') + expect(() => userHandleFor(identity.slice(0, 31), contract)).toThrow(/32 bytes/) + }) +}) + +describe('browserPasskeyAdapter', () => { + it('creates a discoverable, user-verified passkey with the PRF evaluated and the exclude list', async () => { + const rawId = H('cred').slice(0, 20) + const { create } = stubCredentials({ create: async () => credential({ rawId, enabled: true }) }) + const made = await browserPasskeyAdapter({ timeoutMs: 1000 }).create(createOptions) + expect(bytesToHex(made.credentialId)).toBe(bytesToHex(rawId)) + expect(made.prfOutput).toBeNull() + expect(made.prfEnabled).toBe(true) + const pk = create.mock.calls[0]![0].publicKey! + expect(pk.rp).toEqual({ id: 'forge.dashhq.org', name: 'Dash Forge' }) + expect(bytesToHex(bytes(pk.user.id)!)).toBe(bytesToHex(createOptions.userHandle)) + expect(pk.user.displayName).toBe('alice') + expect(pk.timeout).toBe(1000) + expect(pk.authenticatorSelection).toEqual({ residentKey: 'required', requireResidentKey: true, userVerification: 'required' }) + expect(pk.excludeCredentials!.map((c) => bytesToHex(bytes(c.id)!))).toEqual([bytesToHex(createOptions.exclude[0]!)]) + const ext = pk.extensions as { prf: { eval: { first: BufferSource } } } + expect(bytesToHex(bytes(ext.prf.eval.first)!)).toBe(bytesToHex(createOptions.prfInput)) + }) + + it('returns a create-time PRF output when the authenticator gives one', async () => { + const prf = H('prf at create') + stubCredentials({ create: async () => credential({ rawId: H('c').slice(0, 16), prf }) }) + const made = await browserPasskeyAdapter().create(createOptions) + expect(bytesToHex(made.prfOutput!)).toBe(bytesToHex(prf)) + expect(made.prfEnabled).toBe(true) + }) + + it('gets an assertion restricted to the allow list, with the user handle and PRF output', async () => { + const rawId = H('cred').slice(0, 20) + const prf = H('prf') + const handle = userHandleFor(identity, contract) + const { get } = stubCredentials({ get: async () => credential({ rawId, prf, userHandle: handle }) }) + const a = await browserPasskeyAdapter().get({ rpId: 'localhost', prfInput: H('in'), allow: [rawId] }) + expect(bytesToHex(a.credentialId)).toBe(bytesToHex(rawId)) + expect(bytesToHex(a.userHandle!)).toBe(bytesToHex(handle)) + expect(bytesToHex(a.prfOutput)).toBe(bytesToHex(prf)) + const pk = get.mock.calls[0]![0].publicKey! + expect(pk.rpId).toBe('localhost') + expect(pk.userVerification).toBe('required') + expect(pk.allowCredentials!.map((c) => bytesToHex(bytes(c.id)!))).toEqual([bytesToHex(rawId)]) + }) + + it("throws 'no-prf' with the credential id when the assertion has no PRF output", async () => { + const rawId = H('cred').slice(0, 20) + stubCredentials({ get: async () => credential({ rawId, prf: null, userHandle: null }) }) + const err = await browserPasskeyAdapter().get({ rpId: 'localhost', prfInput: H('in'), allow: [] }).catch((e: unknown) => e) + expect(err).toBeInstanceOf(PasskeyError) + expect((err as PasskeyError).code).toBe('no-prf') + expect(bytesToHex((err as PasskeyError).credentialId!)).toBe(bytesToHex(rawId)) + }) + + it('maps browser rejections, and lets the app map them itself', async () => { + const notAllowed = Object.assign(new Error('see https://www.w3.org/TR/webauthn-2/#sctn-privacy-considerations-client'), { name: 'NotAllowedError' }) + stubCredentials({ get: async () => Promise.reject(notAllowed) }) + await expect(browserPasskeyAdapter().get({ rpId: 'x', prfInput: H('i'), allow: [] })).rejects.toMatchObject({ code: 'cancelled' }) + const mapError = vi.fn((e: unknown, kind: string) => new Error(`${kind}: ${(e as Error).name}`)) + await expect(browserPasskeyAdapter({ mapError }).get({ rpId: 'x', prfInput: H('i'), allow: [] })).rejects.toThrow('get: NotAllowedError') + expect(defaultPasskeyError(Object.assign(new Error(), { name: 'SecurityError' })).code).toBe('unsupported') + expect(defaultPasskeyError(new Error('x')).code).toBe('failed') + expect(defaultPasskeyError(Object.assign(new Error(), { name: 'InvalidStateError' })).code).toBe('exists') + }) + + it("refuses with 'unsupported' where there is no WebAuthn", async () => { + vi.stubGlobal('navigator', {}) + await expect(browserPasskeyAdapter().create(createOptions)).rejects.toMatchObject({ code: 'unsupported' }) + }) + + it('aborts a ceremony that outlives its timeout (the backstop), so the prompt closes', async () => { + vi.useFakeTimers() + let signal: AbortSignal | undefined + stubCredentials({ + create: (o) => { + signal = o.signal ?? undefined + return new Promise(() => {}) + }, + }) + const pending = browserPasskeyAdapter({ timeoutMs: 1000 }).create(createOptions).catch((e: unknown) => e) + await vi.advanceTimersByTimeAsync(5999) + expect(signal?.aborted).toBe(false) + await vi.advanceTimersByTimeAsync(1) + const err = await pending + expect((err as PasskeyError).code).toBe('timeout') + expect(signal?.aborted).toBe(true) + }) + + it("aborts the ceremony when the caller's signal aborts", async () => { + let signal: AbortSignal | undefined + stubCredentials({ + get: (o) => { + signal = o.signal ?? undefined + return new Promise((_, reject) => signal?.addEventListener('abort', () => reject(Object.assign(new Error('aborted'), { name: 'AbortError' })))) + }, + }) + const outer = new AbortController() + const pending = browserPasskeyAdapter().get({ rpId: 'x', prfInput: H('i'), allow: [], signal: outer.signal }).catch((e: unknown) => e) + outer.abort() + expect(((await pending) as PasskeyError).code).toBe('cancelled') + expect(signal?.aborted).toBe(true) + }) + + it('signals an unknown credential as base64url, where supported', async () => { + const signalUnknownCredential = vi.fn(async () => {}) + vi.stubGlobal('PublicKeyCredential', { signalUnknownCredential }) + await browserPasskeyAdapter().signalUnknown!('localhost', Uint8Array.of(0xfb, 0xff, 0x01)) + expect(signalUnknownCredential).toHaveBeenCalledWith({ rpId: 'localhost', credentialId: '-_8B' }) + vi.stubGlobal('PublicKeyCredential', {}) + await expect(browserPasskeyAdapter().signalUnknown!('localhost', Uint8Array.of(1))).resolves.toBeUndefined() + }) +}) + +describe('prfSupport', () => { + it("reads the client capabilities, else says 'unknown'; 'no' without WebAuthn", async () => { + vi.stubGlobal('navigator', { credentials: {} }) + vi.stubGlobal('PublicKeyCredential', { getClientCapabilities: async () => ({ 'extension:prf': true }) }) + expect(await prfSupport()).toBe('yes') + vi.stubGlobal('PublicKeyCredential', { getClientCapabilities: async () => ({ 'extension:prf': false }) }) + expect(await prfSupport()).toBe('no') + vi.stubGlobal('PublicKeyCredential', {}) + expect(await prfSupport()).toBe('unknown') + vi.stubGlobal('PublicKeyCredential', undefined) + expect(await prfSupport()).toBe('no') + }) +}) + +describe('fakePasskeyAdapter', () => { + it('PRF = HMAC(secret, input); discoverable get picks the last passkey; exclude refuses a held one', async () => { + const fake = fakePasskeyAdapter({ prfAtCreate: true }) + const made = await fake.create(createOptions) + const c = fake.credentials[0]! + expect(bytesToHex(made.prfOutput!)).toBe(bytesToHex(hmac(sha256, c.secret, createOptions.prfInput))) + const a = await fake.get({ rpId: createOptions.rpId, prfInput: createOptions.prfInput, allow: [] }) + expect(bytesToHex(a.prfOutput)).toBe(bytesToHex(made.prfOutput!)) + await expect(fake.create({ ...createOptions, exclude: [made.credentialId] })).rejects.toThrow(/already holds/) + await expect(fake.get({ rpId: 'other.example', prfInput: createOptions.prfInput, allow: [] })).rejects.toMatchObject({ code: 'cancelled' }) + }) +}) diff --git a/forge-web/lib/vendor/platform-auth/passkey-vault/webauthn.ts b/forge-web/lib/vendor/platform-auth/passkey-vault/webauthn.ts new file mode 100644 index 000000000..88bd9baec --- /dev/null +++ b/forge-web/lib/vendor/platform-auth/passkey-vault/webauthn.ts @@ -0,0 +1,218 @@ +// WebAuthn with the PRF extension, behind a small adapter so the vault runs against a fake in tests. The passkey never signs anything +// for the vault: only its PRF output is used, to derive the HPKE recipient key. So challenges are random and nothing goes to a server. +// browserPasskeyAdapter is govhub vault/webauthn.ts plus Forge's backstop: a ceremony that outlives its timeout is aborted, so the +// prompt closes and the next attempt is not refused as "a request is already pending". +import { randomBytes } from './bytes' +import { PasskeyError } from './errors' + +export interface CreatedPasskey { + credentialId: Uint8Array + /** The PRF output at creation, when the authenticator gives one then (many give it only on get). */ + prfOutput: Uint8Array | null + /** Whether the authenticator said it supports PRF. */ + prfEnabled: boolean +} + +export interface PasskeyAssertion { + credentialId: Uint8Array + /** The user handle; null when the authenticator returned none. */ + userHandle: Uint8Array | null + /** 32 bytes. An assertion without PRF output throws PasskeyError 'no-prf' instead. */ + prfOutput: Uint8Array +} + +export interface CreatePasskeyOptions { + rpId: string + rpName: string + userHandle: Uint8Array + userName: string + /** Defaults to `userName`. */ + displayName?: string + prfInput: Uint8Array + /** Credentials the authenticator must not already hold (the owner's existing passkeys). */ + exclude: readonly Uint8Array[] + signal?: AbortSignal +} + +export interface GetPasskeyOptions { + rpId: string + prfInput: Uint8Array + /** Restricts the ceremony to these credentials; empty for a discoverable sign-in. */ + allow: readonly Uint8Array[] + signal?: AbortSignal +} + +export interface PasskeyAdapter { + create(o: CreatePasskeyOptions): Promise + get(o: GetPasskeyOptions): Promise + /** Tells the provider a credential is useless (never stored, or removed), where the browser supports it. Best effort. */ + signalUnknown?(rpId: string, credentialId: Uint8Array): Promise +} + +export type CeremonyKind = 'create' | 'get' + +export interface BrowserPasskeyOptions { + /** WebAuthn `timeout`; the backstop aborts 5 s after it. Default 120 s. */ + timeoutMs?: number + /** Maps a ceremony failure to what the app throws. Default: {@link defaultPasskeyError}. */ + mapError?: (error: unknown, kind: CeremonyKind) => unknown +} + +export const DEFAULT_PASSKEY_TIMEOUT_MS = 120_000 +const BACKSTOP_MS = 5_000 + +/** The default mapping from a WebAuthn rejection to a PasskeyError. A PasskeyError passes through. */ +export function defaultPasskeyError(error: unknown): PasskeyError { + if (error instanceof PasskeyError) return error + const name = (error as { name?: unknown } | null)?.name + if (name === 'NotAllowedError' || name === 'AbortError') return new PasskeyError('The passkey prompt was closed or timed out.', 'cancelled') + if (name === 'NotSupportedError' || name === 'SecurityError') return new PasskeyError('Passkeys are not available here.', 'unsupported') + if (name === 'InvalidStateError') return new PasskeyError('This device already holds a passkey for this account.', 'exists') + return new PasskeyError('The passkey request failed.', 'failed') +} + +/** What the browser says about PRF before trying. 'unknown' when it does not say (the actual output decides). */ +export async function prfSupport(): Promise<'yes' | 'no' | 'unknown'> { + const PKC = (globalThis as { PublicKeyCredential?: { getClientCapabilities?: () => Promise> } }).PublicKeyCredential + if (!PKC || !globalThis.navigator?.credentials) return 'no' + try { + const caps = await PKC.getClientCapabilities?.() + if (caps && 'extension:prf' in caps) return caps['extension:prf'] ? 'yes' : 'no' + } catch { + /* older browsers */ + } + return 'unknown' +} + +const buf = (b: Uint8Array): ArrayBuffer => b.slice().buffer as ArrayBuffer +function bytesOf(b: ArrayBuffer | ArrayBufferView | undefined | null): Uint8Array | null { + if (!b) return null + if (b instanceof ArrayBuffer) return new Uint8Array(b.slice(0)) + return new Uint8Array(b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength)) +} + +const prfExtension = (prfInput: Uint8Array): AuthenticationExtensionsClientInputs => + ({ prf: { eval: { first: buf(prfInput) } } }) as AuthenticationExtensionsClientInputs + +const base64url = (bytes: Uint8Array): string => { + let s = '' + for (const x of bytes) s += String.fromCharCode(x) + return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') +} + +type PrfResults = { prf?: { enabled?: boolean; results?: { first?: ArrayBuffer | ArrayBufferView } } } + +interface CredentialLike { + rawId: ArrayBuffer + response: { userHandle?: ArrayBuffer | null } + getClientExtensionResults(): PrfResults +} + +/** + * Runs one ceremony with an abort backstop: past `timeoutMs + 5 s`, or when the caller's signal aborts, the ceremony's own signal + * aborts so the browser closes the prompt. Every failure goes through `mapError`. + */ +async function ceremony( + start: (signal: AbortSignal) => Promise, + o: { timeoutMs: number; kind: CeremonyKind; signal: AbortSignal | undefined; mapError: (e: unknown, kind: CeremonyKind) => unknown }, +): Promise { + const controller = new AbortController() + const onAbort = () => controller.abort() + if (o.signal?.aborted) controller.abort() + o.signal?.addEventListener('abort', onAbort, { once: true }) + let timer: ReturnType | undefined + const backstop = new Promise((_, reject) => { + timer = setTimeout(() => reject(new PasskeyError('The passkey prompt timed out.', 'timeout')), o.timeoutMs + BACKSTOP_MS) + }) + try { + return await Promise.race([start(controller.signal), backstop]) + } catch (error) { + controller.abort() + throw o.mapError(error, o.kind) + } finally { + clearTimeout(timer) + o.signal?.removeEventListener('abort', onAbort) + } +} + +export function browserPasskeyAdapter(options: BrowserPasskeyOptions = {}): PasskeyAdapter { + const timeoutMs = options.timeoutMs ?? DEFAULT_PASSKEY_TIMEOUT_MS + const mapError = options.mapError ?? defaultPasskeyError + const credentials = (kind: CeremonyKind) => { + const c = globalThis.navigator?.credentials + if (!c) throw mapError(new PasskeyError('Passkeys are not available in this browser.', 'unsupported'), kind) + return c + } + + return { + async create(o) { + const c = credentials('create') + const cred = (await ceremony( + (signal) => + c.create({ + signal, + publicKey: { + timeout: timeoutMs, + challenge: buf(randomBytes(32)), + rp: { id: o.rpId, name: o.rpName }, + user: { id: buf(o.userHandle), name: o.userName, displayName: o.displayName ?? o.userName }, + pubKeyCredParams: [ + { type: 'public-key', alg: -7 }, + { type: 'public-key', alg: -257 }, + ], + authenticatorSelection: { residentKey: 'required', requireResidentKey: true, userVerification: 'required' }, + excludeCredentials: o.exclude.map((id) => ({ type: 'public-key' as const, id: buf(id) })), + extensions: prfExtension(o.prfInput), + }, + }), + { timeoutMs, kind: 'create', signal: o.signal, mapError }, + )) as CredentialLike | null + if (!cred) throw mapError(new PasskeyError('No passkey was created.', 'cancelled'), 'create') + const ext = cred.getClientExtensionResults() + const prfOutput = bytesOf(ext.prf?.results?.first) + return { + credentialId: new Uint8Array(cred.rawId.slice(0)), + prfOutput: prfOutput && prfOutput.length === 32 ? prfOutput : null, + prfEnabled: ext.prf?.enabled === true || prfOutput !== null, + } + }, + + async get(o) { + const c = credentials('get') + const cred = (await ceremony( + (signal) => + c.get({ + signal, + publicKey: { + timeout: timeoutMs, + challenge: buf(randomBytes(32)), + rpId: o.rpId, + userVerification: 'required', + allowCredentials: o.allow.map((id) => ({ type: 'public-key' as const, id: buf(id) })), + extensions: prfExtension(o.prfInput), + }, + }), + { timeoutMs, kind: 'get', signal: o.signal, mapError }, + )) as CredentialLike | null + if (!cred) throw mapError(new PasskeyError('No passkey was chosen.', 'cancelled'), 'get') + const credentialId = new Uint8Array(cred.rawId.slice(0)) + const prf = bytesOf(cred.getClientExtensionResults().prf?.results?.first) + if (!prf || prf.length !== 32) { + prf?.fill(0) + throw mapError(new PasskeyError("This passkey's provider doesn't support the PRF extension.", 'no-prf', credentialId), 'get') + } + return { credentialId, userHandle: bytesOf(cred.response.userHandle), prfOutput: prf } + }, + + async signalUnknown(rpId, credentialId) { + const PKC = (globalThis as { PublicKeyCredential?: { signalUnknownCredential?: (o: { rpId: string; credentialId: string }) => Promise } }) + .PublicKeyCredential + if (!PKC?.signalUnknownCredential) return + try { + await PKC.signalUnknownCredential({ rpId, credentialId: base64url(credentialId) }) + } catch { + /* best effort */ + } + }, + } +} diff --git a/forge-web/lib/view/funds.test.ts b/forge-web/lib/view/funds.test.ts index dc0ad9db5..1bdc196f7 100644 --- a/forge-web/lib/view/funds.test.ts +++ b/forge-web/lib/view/funds.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' -import { affordability, fundsNotice, fundsState, issueCoverage, LOW_BALANCE_CREDITS, nextFundsChange, renewFix } from './funds' +import { affordability, fundsNotice, fundsState, issueCoverage, LOW_BALANCE_CREDITS, nextFundsChange, renewableInWallet, renewFix } from './funds' import { previewCreate } from '../sdk/cost' import { balanceSettled, estimateMissed, reconcile, summarize, type SpendRow } from '../spend' @@ -74,6 +74,12 @@ describe('fundsNotice (the low-balance banner, ux-dx-spec §4)', () => { expect(fundsNotice(fundsState(10n ** 11n, key(4_000_000_000n, 3 * DAY), NOW), 'dg')).toMatchObject({ fix: 'renew-key' }) expect(renewFix('app-connect')).toBe('renew-in-wallet') expect(renewFix(null)).toBe('renew-key') + // A key a passkey restored: who made it is unknown, so both renewals are offered. + expect(renewFix('passkey')).toBe('renew-either') + expect(fundsNotice(fundsState(10n ** 11n, key(4_000_000_000n, 3 * DAY), NOW), 'passkey')).toMatchObject({ key: 'low:key-expiry', fix: 'renew-either' }) + expect(fundsNotice(fundsState(10n ** 11n, key(0n, 90 * DAY), NOW), 'passkey')).toMatchObject({ key: 'empty:key-budget', fix: 'renew-either' }) + expect(fundsNotice(fundsState(BigInt(LOW_BALANCE_CREDITS - 1), null, NOW), 'passkey')).toMatchObject({ fix: 'top-up' }) + expect(['app-connect', 'passkey', 'dg', null, undefined].map(renewableInWallet)).toEqual([true, true, false, false, false]) }) }) diff --git a/forge-web/lib/view/funds.ts b/forge-web/lib/view/funds.ts index d40be8ce9..8f14b33b0 100644 --- a/forge-web/lib/view/funds.ts +++ b/forge-web/lib/view/funds.ts @@ -93,13 +93,21 @@ export function issueCoverage(spendable: bigint | null, issueCredits: number, da * The one fix a low or empty state needs (`ux-dx-spec.md` §4: top up / renew key). * `renew-in-wallet`: the key came from a wallet's App Connect grant (session origin * `app-connect`), so it is renewed in that wallet (`AuthController.walletRenewalRequest`); the - * identity file or recovery phrase still works as the other way. + * identity file or recovery phrase still works as the other way. `renew-either`: the key was + * restored from a passkey (origin `passkey`), which does not say who made it, so both ways are + * offered side by side. */ -export type FundsFix = 'top-up' | 'renew-key' | 'renew-in-wallet' +export type FundsFix = 'top-up' | 'renew-key' | 'renew-in-wallet' | 'renew-either' -/** How "Renew" goes for a session: in the wallet for a key it granted through App Connect. */ -export function renewFix(origin: string | null | undefined): 'renew-key' | 'renew-in-wallet' { - return origin === 'app-connect' ? 'renew-in-wallet' : 'renew-key' +/** Whether a session's key can be renewed in a wallet: one it granted, or one a passkey restored. */ +export function renewableInWallet(origin: string | null | undefined): boolean { + return origin === 'app-connect' || origin === 'passkey' +} + +/** How "Renew" goes for a session: in the wallet for a key it granted, either way for a passkey's. */ +export function renewFix(origin: string | null | undefined): 'renew-key' | 'renew-in-wallet' | 'renew-either' { + if (!renewableInWallet(origin)) return 'renew-key' + return origin === 'passkey' ? 'renew-either' : 'renew-in-wallet' } /** diff --git a/forge-web/package.json b/forge-web/package.json index 502312bd0..c74316003 100644 --- a/forge-web/package.json +++ b/forge-web/package.json @@ -27,6 +27,7 @@ "dependencies": { "@dashevo/evo-sdk": "5.0.0-rc.8", "@dashevo/wasm-sdk": "5.0.0-rc.8", + "@noble/ciphers": "^2.4.0", "@noble/curves": "^2.4.0", "@noble/hashes": "^2.4.0", "@noble/secp256k1": "^3.2.0", diff --git a/forge-web/pnpm-lock.yaml b/forge-web/pnpm-lock.yaml index 31c51148a..13ede8dcb 100644 --- a/forge-web/pnpm-lock.yaml +++ b/forge-web/pnpm-lock.yaml @@ -14,6 +14,9 @@ importers: '@dashevo/wasm-sdk': specifier: 5.0.0-rc.8 version: 5.0.0-rc.8 + '@noble/ciphers': + specifier: ^2.4.0 + version: 2.4.0 '@noble/curves': specifier: ^2.4.0 version: 2.4.0 @@ -445,6 +448,10 @@ packages: cpu: [x64] os: [win32] + '@noble/ciphers@2.4.0': + resolution: {integrity: sha512-AnjFn0Jv92laAkvMrghlFZq4qQCIN/4DxFV/eooqtC2YTjB7kBeLMS2T9KJX4Dn+ZVXLOwK0lSgqDtx9gvxtiw==} + engines: {node: '>= 20.19.0'} + '@noble/curves@2.4.0': resolution: {integrity: sha512-P4/62zrgfH33CneE3Dn4WhJVA22YUU0eR51wKIan4NVRvwsA0YnPTwWGpNbpuacSujmSFLvyzpyuR30+fbq2Ew==} engines: {node: '>= 20.19.0'} @@ -2879,6 +2886,8 @@ snapshots: '@next/swc-win32-x64-msvc@14.2.33': optional: true + '@noble/ciphers@2.4.0': {} + '@noble/curves@2.4.0': dependencies: '@noble/hashes': 2.4.0 diff --git a/tools/audit/no-devnet-copy.sh b/tools/audit/no-devnet-copy.sh index 52ec613cc..9caf81190 100755 --- a/tools/audit/no-devnet-copy.sh +++ b/tools/audit/no-devnet-copy.sh @@ -41,6 +41,7 @@ ALLOW=( '^docs/dev/' '^docs/research/' '^docs/security/private-repos\.md$' # the normative design, which names each contract set + '^docs/security/passkey-vault\.md$' # its deployment status names each network's pending forge-meta update '^docs/testing/' '^docs/upstream/' # tests and their data