diff --git a/.gitleaks.toml b/.gitleaks.toml index f550653b5..66cf5fbf1 100644 --- a/.gitleaks.toml +++ b/.gitleaks.toml @@ -30,6 +30,9 @@ paths = [ '''forge-contracts/vectors/.*\.json''', # The generator for those vectors. '''forge-contracts/schema/vectors\.py''', + # Interop vectors vendored from platform-auth (App Connect, passkey vault): keys derived from + # fixed seeds and published upstream so every app reproduces the same bytes. + '''forge-web/lib/vendor/platform-auth/[^/]+/(vectors\.json|__vectors__/[^/]+\.json)''', # Fixtures for the secret scanner's own tests: fake tokens and the public Dash Core WIF # vectors, which must look real for the scanner to be tested. '''tools/secret-scan-vectors/.*''', diff --git a/CHANGELOG.md b/CHANGELOG.md index 51decde3a..a449f2351 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,7 @@ Members-only content in public repositories, Environments and the secret scan. P - **Environments** (`dg env`): configuration and secrets kept outside git, encrypted for a repository's **Maintainers** (the default for `production`, `prod*`, `staging` and `release*`) or its **Members**, changed by maintainers only, injected with `dg env run` or written to a git-ignored file with `dg env export -o .env`. Two changes at once fail closed (E608) until a maintainer keeps one. `dg collab remove` lists the values the removed member could read. See [Environments](docs/guides/environments.md). - **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. ### Changed diff --git a/docs/design/ux-dx-spec.md b/docs/design/ux-dx-spec.md index b50ff2af3..b4e388fe1 100644 --- a/docs/design/ux-dx-spec.md +++ b/docs/design/ux-dx-spec.md @@ -73,7 +73,7 @@ With no storage profile the command stops before creating anything: *"No storage ### 2.2 Browser: getting an identity Sign-in sheet (replaces `login-modal.tsx`): three tiles plus an "Advanced" disclosure. -1. **Use my Dash wallet** (app-connect, PV14; first when the contract exists on the active network). App creates an ephemeral keypair → QR / deep link with the request (group `dash-forge`; one AUTHENTICATION HIGH key, budget 0.05 DASH, expiry 90 days; ENCRYPTION optional for private repos) → polls `loginKeyResponse` by `appEphemeralPubKeyHash` → decrypts the grant → **verifies on-chain** that the key is live on the responder with the requested bounds, budget and expiry → vault. Waiting copy: *"Approve in your wallet. Forge gets a key that can spend at most 0.05 DASH, only here, until ."* After 3 min: *"No response yet. Keep this tab open, or choose another method."* If no wallet supports it yet the tile says so — *"needs a wallet with Platform login (list)"*. +1. **Use my Dash wallet** (App Connect v2 where the chain runs PV14 and Forge is deployed; first where a wallet can answer, else last with the reason). App creates an ephemeral keypair → QR (and, on a phone, a deep link that also carries a return address `/connect/`) with the request (group `dash-forge`; one AUTHENTICATION HIGH key, budget 0.05 DASH, expiry 90 days; no encryption key, since no Forge contract allows a wallet-issued one) → polls `loginKeyResponse` by `appEphemeralPubKeyHash`, at once when the tab regains focus or the wallet returns → decrypts the grant → **verifies on-chain** that the key is live on the responder with the requested bounds, budget and expiry (the budget may be higher: wallets offer presets from 0.1 DASH) → confirm step ("A wallet answered for this identity": compare the username and id with the wallet) → vault. One approval covers all four Forge contracts, so no guided grants follow. Waiting copy: *"Approve in your wallet. One approval covers all of Forge, spending up to 0.05 DASH until . Your wallet may offer other limits."* A link under the code, *"Using a Dash Wallet build without App Connect v2? Show the older code"*, switches to the older exchange (one approval per contract, guided) and back. If no wallet supports either yet the tile says so. Details: [wallet-login.md](wallet-login.md#app-connect-v2-one-approval-for-all-of-forge). 2. **Create a new identity** (funds from any Dash wallet). (i) 12-word mnemonic generated in-browser; the user confirms three words before continuing; (ii) deposit QR with amount (default 0.05 DASH, min 0.02; *"This becomes your Platform credits. ~0.0005 DASH per issue or push."*); (iii) watch the address, build and broadcast the asset lock, wait for InstantSend, register the identity **with the limited key inside the IdentityCreate** so no second signature is needed; (iv) the master key exists only in memory during this step. Note under the QR: *"This page watches for your deposit through the Dash network's own nodes, and asks a block explorer (`insight.dash.org`, changeable in Settings) only if they cannot answer. Neither can take funds or keys."* 3. **Import an identity file** (bridge JSON, `dg auth export`, or mnemonic): the master key signs one `IdentityUpdate` registering a limited key and is discarded. *"Your master key is used once, right now, to create a limited key for this browser. It is not stored."* @@ -83,7 +83,7 @@ Sign-in sheet (replaces `login-modal.tsx`): three tiles plus an "Advanced" discl - Holds limited key(s), storage credentials (§3), the local spend ledger. Never the master key. - AES-256-GCM under **passkey PRF** when available, else **Argon2id(passphrase)** (m=64 MiB, t=3); both can be enrolled. Auto-lock after 12 h or sign-out. - Header pill: DPNS name (or 8-char id), balance, and a thin **key budget bar**. Tooltip: *"This browser's key: 0.031 of 0.05 DASH left · expires 24 Dec."* -- Budget < 20 % or expiry < 7 days: amber pill + banner *"This browser's key is nearly used up. Renew (uses your master key once)."* Renewal = a new limited key via any of the three routes; `IdentityKeyLimitsUpdate` top-up when a master key was imported anyway. +- Budget < 20 % or expiry < 7 days: amber pill + banner *"This browser's key is nearly used up. Renew (uses your master key once)."* Renewal = a new limited key via any of the three routes; `IdentityKeyLimitsUpdate` top-up when a master key was imported anyway. A key a wallet granted through App Connect is renewed in that wallet (**Renew in your wallet**: choose the vault protection first, then approve the new code; the wallet disables the old key in the same update), with the identity file or phrase as the other way. ### 2.4 CLI auth ``` diff --git a/docs/design/wallet-login.md b/docs/design/wallet-login.md index 64b2b51f8..9e23980a0 100644 --- a/docs/design/wallet-login.md +++ b/docs/design/wallet-login.md @@ -1,6 +1,6 @@ # Sign in with a mobile Dash wallet (D-L) -Status: shipped in forge-web (`lib/auth/wallet-protocol.ts`, `app-connect.ts`, `key-registration.ts`, `components/auth/wallet-connect-flow.tsx`). Verified 2026-09-26 against the wallets' sources: Dash Wallet Android `master` fedb593e4 and Dash Wallet iOS `develop` a345cc852. +Status: shipped in forge-web (`lib/auth/wallet-protocol.ts`, `app-connect.ts`, `key-registration.ts`, `components/auth/wallet-connect-flow.tsx`). Verified 2026-09-26 against the wallets' sources: Dash Wallet Android `master` fedb593e4 and Dash Wallet iOS `develop` a345cc852. Those sections describe the **older exchange (v1, DashConnect)**. App Connect v2, which asks for one key for all of Forge, is described in [its own section](#app-connect-v2-one-approval-for-all-of-forge) below; we know of no released wallet that speaks it yet. ## What the wallets do @@ -35,8 +35,8 @@ Forge's previous request also had an extra `keyIndex(u32)` between the contract 2. **Then one approval per further contract, asked in one sequence.** A session holds up to one key per Forge contract (forge-core, forge-collab, forge-community, and forge-meta on a four-contract set): the vault's main key, plus extra wallet grants sealed beside it (`vault-extra:` blob under the vault's derived storage key). `getSigningKeyWif(contractId)` picks the key whose on-chain bounds cover the write's contract. With none, it throws `MissingGrantError` *before signing* (nothing is broadcast or charged), and the write's guard opens the sheet on the grant for **that** contract: **Approve issues and pull requests** (forge-collab) or **Approve stars, watches and follows** (forge-community). Each is one more `dash-key:` for that contract, read only from the signed-in identity. The first sign-in does not leave that to a refused write: when it finishes, the sheet asks for every contract the wallet has not covered, in order (forge-collab, forge-community, then forge-meta), as "Step 2 of 3: approve Forge collaboration" (`lib/auth/guided-grants.ts`). The user can skip a step or the rest, and a skipped grant keeps the on-demand behaviour above. Settings shows the button for the next missing grant until all exist. A wallet whose key is unbounded (Android) covers every contract at once and the sequence does not start. So the honest statement is **one approval per Forge contract until wallets grant group-bound keys**, not one QR code. 3. **Read both response contracts**, behind one interface (`responseSources`): the legacy key-exchange contract recorded in `deployments/.json` `keyExchange` (testnet: yappr's; a devnet: Forge's copy from `deploy-key-exchange.mjs`, on bonsia `4avwgxyfhPjtiTTNwkz9ei7bYTHG5NUUtwNx9mA8Uzwh`) and the App Connect system contract, wherever each exists on chain. Both go through the same checks. 4. **First login registers the key (`dash-st:`)**: an unsigned, tagless IdentityUpdate adding the auth key bound to the requested contract, plus the encryption key with its proof of possession. The wallet rebuilds and signs it. Forge then waits for the auth key (whatever key id it landed under) and verifies it. -5. **Upgrade path.** When a wallet grants a key bound to the dash-forge group (with limits, through App Connect), it covers every Forge contract and is not flagged, so no further approval is asked and the guided sequence does not start. Nothing else changes. -6. **Say which wallets work, per network** (`walletSignInSupported`, the request screen's footer). On testnet the tile comes first and names DashPay (Dash Wallet), where to find the feature (More → Tools → Connections), and that it is not in a released version yet. Elsewhere the tile comes last, and the request screen says Dash Wallet support arrives with testnet, that on this devnet only an internal iOS build with the contract entered by hand can answer, and to use an identity file or create an identity instead. +5. **Upgrade path.** When a wallet grants a key bound to the dash-forge group (with limits, through App Connect), it covers every Forge contract and is not flagged, so no further approval is asked and the guided sequence does not start. That is the v2 flow below, which is now offered first where it is available; this section's v1 flow stays behind "Show the older code". +6. **Say which wallets work, per network** (`walletSignInSupported`, the request screen's footer). Where App Connect v2 is on offer the tile comes first on any network (see below). On testnet the tile comes first and names DashPay (Dash Wallet), where to find the feature (More → Tools → Connections), and that it is not in a released version yet. Elsewhere the tile comes last, and the request screen says Dash Wallet support arrives with testnet, that on this devnet only an internal iOS build with the contract entered by hand can answer, and to use an identity file or create an identity instead. 7. **Tell the user where to scan (SECU-08).** The request binds nothing about who shows it (no origin or domain, here or in App Connect), so a lookalike page can show a code with Forge's contract id and the label "Dash Forge", and the wallet's approval screen cannot tell it from this one. The request step therefore opens with "Scan only a code shown on forge.dashhq.org" (the build's own address, `lib/site.ts`), that Forge never asks for a code it didn't show, what an approval grants (a key that signs as the identity with no budget or expiry unless the wallet sets one, which today's wallets don't, and the encryption key that opens private and members-only content), and what to do after scanning an untrusted code (Settings → Devices & keys → Disable all other keys, then replace the encryption key; docs/guides/revoke-keys.md). This is copy only: how the login derives and delivers the encryption key is unchanged (D27). Origin binding in the request needs the upstream wallet work in `docs/upstream/`. ### Verification (same rules for both sources) @@ -70,6 +70,54 @@ The real fix is upstream (e): the wallet signs the request context (`hash160(app **Deep-link hijack.** On a phone the request is an `Open in DashPay (Dash Wallet)` link (`dash-key:` URI; both wallets register the scheme, see the table above). A desktop browser shows only the QR, since the wallets are phone apps. Any installed app can register the scheme, and iOS's own notes say a custom scheme carries no authenticated caller (`DashConnectDeepLink.swift`). A hijacking app learns only the ephemeral public key and the contract id. It cannot decrypt a response meant for Forge, and anything it answers is caught by the checks above: a different identity, or keys Forge would not accept. What it *can* do is answer with its own identity, which the identity confirmation is there to catch. The link carries no secret. +## App Connect v2: one approval for all of Forge + +Status: implemented in forge-web, on protocol code vendored from platform-auth (`lib/vendor/platform-auth/app-connect/`, recorded in `VENDORED.json`; the profile is platform-auth's `docs/APP_CONNECT_PROFILE.md`). **We know of no released wallet that speaks it yet** (not checked against any wallet's source in this change). It is covered by the profile's test vectors and unit tests. A scripted wallet (`e2e/wallet-responder-v2.ts`), a live test and a Playwright spec are written for sakura (see Tests) but **have not been run against a live chain yet**: no devnet node was reachable when they were written. v1 above is unchanged and stays for wallets that only speak it: a wallet that does not know `v=2` refuses the request, so the two never share a QR code. + +### The request + +`lib/auth/app-connect-v2.ts` builds one request per attempt: +- **One binding**: `contractGroup(dash-forge group)`, AUTHENTICATION / **HIGH**, with Forge's default limits (`defaultLimits`: 0.05 DASH, 90 days) as a proposal. HIGH, not CRITICAL: Forge has no tokens and refuses anything but HIGH. The wallet clamps the proposal to its presets (0.1 DASH and up) and the chain records what was granted; the confirm step and Settings show the granted figures. +- **`appId` is forge-core** (the group's owner owns it, which is what the profile's owner rule needs), label "Dash Forge". +- **No encryption binding.** No Forge contract allows wallet-issued encryption keys, so a wallet would refuse one as invalid. A v2 sign-in therefore does not deliver the encryption key that a v1 sign-in registers (D27): members-only and private content are set up in Settings afterwards. +- **`CONNECTION_ID`**: 16 random bytes per network in localStorage, kept across sign-out and forget (`lib/auth/connection-id.ts`). A wallet that approves disables the key of its previous grant for the same (identity, app, connection id) in the same update, so signing in again or renewing never leaves this browser's old key live. +- **Clocks**: `CREATED_AT` is this device's clock (the wallet compares it with its own); the proposed expiry and the verifier's "now" are chain time (`readChainClock`), falling back to the device clock. +- **Only the phone's deep link carries `cb`** (`https:///connect/?r=`). The QR leaves it out (a smaller code, and a phone scanning it has no Forge tab to return to). It is left out too on an IPFS build and when the page is not on the canonical site's origin: the return page can only reach tabs of its own origin. + +### Availability and trust + +The v2 request is offered when Forge is deployed on the network, the chain reports protocol 14 or later, and the group check passes. `AuthController.checkGroup` (`assertGroupHolds`) runs before a code is shown: it pins the group owner, requires no admins, and accepts and names members this build does not know (shown on the confirm step). The vendored `group.ts` (an exact member list) is not used; it would break whenever Forge adds a contract. Otherwise only v1 is offered, as before. + +A locked vault holding a wallet-granted key blocks a v2 sign-in (`walletSignInBlocker`): any approval disables the key of the wallet's previous grant before Forge sees the answer, and nobody knows which identity will answer, so such a vault is unlocked first while its key still opens. + +### Verification + +The poll pages through the `loginKeyResponse` rows of the request (`listAppConnectCandidates`), opens each with the request's ephemeral key and checks it with the vendored verifier (the key is live on the answering identity, has exactly the bounds, level and limits asked for, and is not about to expire or spent), then once more with Forge's own rules (`findWalletKey`: AUTHENTICATION / HIGH, group-bound, with a budget and an expiry), which yields the key the vault stores. The key is stored like any wallet key, with origin `app-connect`. + +Who answered is still not proven (anyone who saw the QR can answer from their own identity), but on App Connect Forge can see it: every answer that opens with this request's key counts as a responder, accepted or not, for a 3 second settle window, and **two identities are refused**. Without an identity hint the confirm step stays ("A wallet answered for this identity": compare the username and id with the wallet). A request lives 10 minutes and is polled every 2 s for a minute, then every 4 s; the poll also runs at once when the tab regains focus or becomes visible, and when the `/connect/` page reports the wallet came back. The return page tells that tab a failure the wallet reports (`ac` = declined, stale, unsupported, invalid, failed), and the tab shows it; it is only a nudge, and nothing is trusted from it. With no tab waiting (a code shown in another browser), the page says what the wallet reported and sends the user back to the Forge tab where they started: the request's key lives in that tab's memory only, so nothing continues on the return page. + +### The session + +- One key covers every contract, so `grants` are complete, the key is not flagged `unlimited`, and no guided grants follow. +- `AuthSession.origin = 'app-connect'` survives a reload (stored with the vault). A write is not started in the last 5 minutes before the key expires (`APP_CONNECT_SIGNING_EXPIRY_MARGIN_MS`): it would fail as expired, so the session offers renewal first. +- **Write errors** read as App Connect does (`classifyAppConnectError`, in `lib/view/write-errors.ts`): + +| Action | Codes | What Forge does | +|---|---|---| +| `renew` | 20015, 20016, 40218 | The key sheet opens (budget or expiry), with **Renew in your wallet** first and the identity file second | +| `logout` | 20003, 20006, 40208 | "Your wallet revoked this browser's access": the key sheet opens and the session locks as for any disabled key. Forge keeps the vault (lock-only; it may hold storage settings and an encryption key) | +| `handoff` | 20013, 20004, 20007 | Cannot happen: Forge's identity updates are signed with the master key. Shown as any refusal | +| `invalidate` | 20014 | The session's keys are checked on chain again (`recheckSession`), and the usual sentence is shown | + +- **Renewing** (`walletRenewalRequest`, "Renew in your wallet"): the same request with `IDENTITY_HINT` and the same connection id, and no `MODE` (no wallet supports `MODE` = renew yet, and its type is even, so a wallet that does not know it refuses the whole request; `RENEW_MODE` is off). The vault protection is chosen **before** the code shows. The wallet disables the old key in the same update that adds the new one, so a marker for the renewal in flight keeps other tabs from locking the vault in that window; it is cleared when the new key is stored, and on cancel, expiry or refusal (`endWalletRenewal`). The banner, the top-up sheet and Settings → This browser's key route a wallet-granted key here (`fundsNotice(state, origin)` → `renew-in-wallet`); the thresholds are Forge's (under 20 % of the budget, under 7 days). +- Master-key top-up, renewal and revocation work on a v2 key as on any Forge browser key (`isForgeBrowserKey`). + +### Not done + +- A wallet's list of known apps: wallets open `cb` and show branding only for hosts they associate with the `appId`, so forge-core and forge.dashhq.org have to be added to it, or a wallet may warn about an unknown app. Not pursued upstream yet. +- Wiping the vault when the wallet revokes access (the profile suggests it); Forge only locks. +- `MODE` = renew, and an encryption binding (it would need a contract that allows wallet-issued encryption keys). + ## Compatibility matrix Every Dash Wallet row needs a build from the development branch: no released version has DashConnect yet (see "Release status" above). @@ -82,7 +130,9 @@ Every Dash Wallet row needs a build from the development branch: no released ver | Dash Wallet iOS | testnet | **Once forge-v2 is on testnet** | key lands bound to forge-core (or forge-collab), unlimited | | Dash Wallet iOS, internal build (`DASH_DEVNET`) | sakura (devnet) | **Only with a manual override**: Settings → Devnet Settings → DashConnect Contract ID = the `keyExchange.contractId` of `deployments/devnet-sakura.json` (deployed with the RC2 registration), and a DashPay identity on sakura | shipping builds have no devnet; not run on a device in this change (see Manual test) | | Dash Wallet iOS | mainnet | No | Connections is off on mainnet (`!WalletEnvironment.isTestNetwork`) | -| Any wallet publishing to App Connect `H8F9…` with group-bound, limited keys | sakura now, all networks at PV14 | **Yes** (unit-tested) | one approval, no warning | +| Any wallet that answers an App Connect **v2** request (`dash-key:…&v=2`) per the profile | sakura now, any network where Forge is deployed at PV14 | **Yes** (unit-tested; no released wallet known to do it yet) | one approval for all of Forge, a budget and an expiry, no warning; no encryption key; renewed in the wallet; the wallet may warn about an app it does not know | +| Any wallet publishing to App Connect `H8F9…` a v1-style response with group-bound, limited keys | sakura now, all networks at PV14 | **Yes** (unit-tested) | one approval, no warning (shown under "Show the older code") | +| Scripted v2 responder (`e2e/wallet-responder-v2.ts`, the profile's wallet rules) | sakura (needs a test identity of your own) | **Written, not yet run live** (its request checks are unit-tested) | login, a forge-community write with no grant, renewal and the old key disabled; vitest live test and Playwright e2e below | | Scripted responder (`e2e/wallet-responder.mjs`, the Android/iOS logic) | sakura (run on bonsia) | **Yes**, live | vitest live test and Playwright e2e below | ## Tests @@ -91,7 +141,13 @@ Every Dash Wallet row needs a build from the development branch: no released ver - `lib/auth/wallet-session.test.ts`: per-contract key choice by scope, `MissingGrantError`, non-Forge contracts refused, a grant kept across lock/unlock and across a returning login, a group-key grant for forge-collab, a grant that does not cover the request refused, a failed grant check keeps the session, disabled grants dropped, renewal disabling every held key in the same update, locked renew/revoke refused, revoke of a wallet session. - `lib/auth/responder-profile.test.ts`: the confirmation warnings (another stored identity, no name, a new name). - `lib/auth/wallet-login.live.test.ts` (`FORGE_LIVE=1`, sakura; run on bonsia): (iOS path) first login with QR #2, a forge-core repo created with the wallet's key, a star refused locally, the one-tap forge-collab grant, the star lands, a returning login without QR #2, cleanup; (Android path) the key lands unbounded and covers both contracts, and after it is disabled the next login is refused (`RevokedWalletKey`). -- `e2e/wallet-login.spec.ts` (`E2E_DEVNET=sakura E2E_WRITE=1`): the real browser from the QR text on the page (QR #2, confirmation warnings, passkey preference), Settings' grant prompt, **Star opening the grant sheet by itself**, the wallet's approval, the star landing, and the phone viewport's deep link. +- `e2e/wallet-login.spec.ts` (`E2E_DEVNET=sakura E2E_WRITE=1`): the real browser from the QR text on the page (QR #2, confirmation warnings, passkey preference), Settings' grant prompt, **Star opening the grant sheet by itself**, the wallet's approval, the star landing, and the phone viewport's deep link. Where App Connect v2 is on offer (sakura) it takes "Show the older code" first. +- `lib/auth/app-connect-v2.test.ts`, `app-connect-port.test.ts`, `app-connect-session.test.ts`, `connection-id.test.ts`: the request's bytes and `cb` (QR without, link with), the verifier's accept and reject cases, the ambiguity rule, retries, the port's key mapping, the vault origin, the expiry margin and the renewal marker. The vendored module's own tests (profile vectors, verifier, poller, errors) run in `pnpm test`. +- `lib/auth/connect-callback.test.ts`, `components/auth/connect-return.test.tsx`: the `cb` rules (omitted on IPFS builds, other origins and http), the `r` / `ac` parsing, the channel messages, and the return page (declined and failed statuses, the ack from the waiting tab, the "go back to the Forge tab" case). +- `components/auth/wallet-connect-flow.test.tsx`, `login-modal.test.tsx`, `top-up-sheet.test.tsx`, `low-funds-banner.test.tsx`, `hooks/use-write-guard.test.tsx`: v2 shown first (after the group and locked-key checks), the older code and back, the confirm step, poll on focus and on the return page's message, the renewal (protection first, the marker ended on every way out but a stored key), the tile order, and renewal routed to the wallet. +- `lib/auth/wallet-responder-v2.test.ts`: the scripted wallet's request checks accept exactly what Forge asks for and refuse what the profile's wallet rules refuse. +- `lib/auth/app-connect-v2.live.test.ts` (`FORGE_LIVE=1`, sakura; real spend; not yet run): login with the scripted v2 wallet, a repo and a star signed by the one key, renewal in the wallet and the old key disabled, cleanup. +- `e2e/wallet-login-v2.spec.ts` (the live part not yet run; the read-only part skips itself when no devnet node is reachable): read-only (the wallet tile first, the v2 request and its terms, the older code and back, the phone link without `cb` on a local http build, the `/connect/` page) and, with `E2E_WRITE=1`, the full login, a star with no grant sheet, and renewal. ## Manual test on a device diff --git a/forge-web/.eslintrc.json b/forge-web/.eslintrc.json index 1aae13a48..77f04664b 100644 --- a/forge-web/.eslintrc.json +++ b/forge-web/.eslintrc.json @@ -63,6 +63,20 @@ ] }] } + }, + { + "files": ["**/*.ts", "**/*.tsx"], + "excludedFiles": ["**/*.test.ts", "**/*.test.tsx", "lib/auth/wallet-sim.ts"], + "rules": { + "@typescript-eslint/no-restricted-imports": ["error", { + "patterns": [ + { + "group": ["**/vendor/platform-auth/app-connect/test-helpers", "**/vendor/platform-auth/app-connect/test-helpers.*", "./test-helpers", "./test-helpers.*"], + "message": "The vendored App Connect test-helpers build vector requests from fixed seeds: tests and lib/auth/wallet-sim.ts only." + } + ] + }] + } } ], "ignorePatterns": [ diff --git a/forge-web/app/connect/page.tsx b/forge-web/app/connect/page.tsx new file mode 100644 index 000000000..07a7f1973 --- /dev/null +++ b/forge-web/app/connect/page.tsx @@ -0,0 +1,18 @@ +'use client' + +/** + * `/connect` — where a wallet returns after an App Connect v2 approval (`cb` in the request). + * Static: it only passes the wallet's nudge to the tab that showed the code + * (`components/auth/connect-return.tsx`, `lib/auth/connect-callback.ts`). + */ + +import { AppShell } from '@/components/app-shell' +import { ConnectReturn } from '@/components/auth/connect-return' + +export default function ConnectPage(): JSX.Element { + return ( + + + + ) +} diff --git a/forge-web/components/auth/connect-return.test.tsx b/forge-web/components/auth/connect-return.test.tsx new file mode 100644 index 000000000..da8db2e8f --- /dev/null +++ b/forge-web/components/auth/connect-return.test.tsx @@ -0,0 +1,95 @@ +// @vitest-environment jsdom +/** + * The page a wallet returns to after an App Connect v2 approval: it nudges the tab that showed the + * code, and when none answers says what the wallet reported and points back to that tab. It never + * continues a sign-in itself. + */ + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { CALLBACK_CHANNEL, ACK_WAIT_MS } from '@/lib/auth/connect-callback' + +const replace = vi.hoisted(() => vi.fn()) +// The router object is stable across renders, as Next's is (the page's effect depends on it). +const router = vi.hoisted(() => ({ replace })) +vi.mock('next/navigation', () => ({ useRouter: () => router })) + +const { ConnectReturn } = await import('./connect-return') + +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +const HASH = 'ab'.repeat(20) +let host: HTMLDivElement +let root: Root + +function visit(search: string): void { + window.history.replaceState(null, '', `/connect/${search}`) + act(() => root.render()) +} +const text = (): string => host.textContent ?? '' + +beforeEach(() => { + replace.mockClear() + host = document.createElement('div') + document.body.appendChild(host) + root = createRoot(host) +}) +afterEach(() => { + act(() => root.unmount()) + host.remove() + vi.useRealTimers() + window.history.replaceState(null, '', '/') +}) + +describe('the wallet return page', () => { + it('goes home when the link is not a well-formed callback', () => { + visit('?r=nope&ac=ok') + expect(replace).toHaveBeenCalledWith('/') + }) + + it('says what a declined or failed approval was, without waiting for a tab', () => { + visit(`?r=${HASH}&ac=declined`) + expect(text()).toContain('Sign-in declined') + // A fresh page load for the next one. + act(() => root.unmount()) + root = createRoot(host) + visit(`?r=${HASH}&ac=failed`) + expect(text()).toContain("Your wallet couldn't finish") + }) + + it('tells the tab with the code about a decline too, so it can stop waiting', async () => { + const waiting = new BroadcastChannel(CALLBACK_CHANNEL) + const seen: unknown[] = [] + waiting.onmessage = (e: MessageEvent) => seen.push(e.data) + visit(`?r=${HASH}&ac=declined`) + await act(async () => new Promise((r) => setTimeout(r, 60))) + expect(seen).toEqual([{ type: 'forge-app-connect-callback', requestHash: HASH, status: 'declined' }]) + expect(text()).toContain('Sign-in declined') + waiting.close() + }) + + it('tells the tab with the code, and steps aside when it answers', async () => { + const waiting = new BroadcastChannel(CALLBACK_CHANNEL) + const seen: unknown[] = [] + waiting.onmessage = (e: MessageEvent) => { + seen.push(e.data) + waiting.postMessage({ type: 'forge-app-connect-ack', requestHash: HASH }) + } + visit(`?r=${HASH}&ac=ok`) + await act(async () => new Promise((r) => setTimeout(r, 60))) + expect(seen).toEqual([{ type: 'forge-app-connect-callback', requestHash: HASH, status: 'ok' }]) + expect(text()).toContain("You're signing in on your other Forge tab") + waiting.close() + }) + + it('points back to the Forge tab where the user started when none answers', () => { + vi.useFakeTimers() + visit(`?r=${HASH}&ac=ok`) + expect(text()).toContain('Finishing sign-in') + act(() => void vi.advanceTimersByTime(ACK_WAIT_MS + 10)) + expect(text()).toContain('Go back to Forge') + expect(text()).toContain('Forge tab where you started') + expect(host.querySelector('a')!.getAttribute('href')).toBe('/') + }) +}) diff --git a/forge-web/components/auth/connect-return.tsx b/forge-web/components/auth/connect-return.tsx new file mode 100644 index 000000000..1136cb2e2 --- /dev/null +++ b/forge-web/components/auth/connect-return.tsx @@ -0,0 +1,100 @@ +'use client' + +/** + * Where a wallet returns after an App Connect v2 approval (`cb` in the request; `/connect/`). + * + * It is a nudge and nothing more: it tells the tab that showed the code to check now, and if that + * tab answers, this one can be closed. If no tab answers (the code was shown in another browser + * or a tab that was closed), it says what the wallet reported and points back to where the user + * started. It stores nothing and signs nothing: the request's key exists in the first tab's + * memory only, so a sign-in cannot continue here. + */ + +import { useEffect, useState } from 'react' +import Link from 'next/link' +import { useRouter } from 'next/navigation' +import { Button } from '@/components/ui/button' +import { Spinner } from '@/components/ui/states' +import { + ACK_WAIT_MS, + CALLBACK_CHANNEL, + callbackStatusCopy, + isConnectCallbackAck, + parseConnectCallback, + type ConnectCallbackMessage, +} from '@/lib/auth/connect-callback' + +type View = + | { readonly kind: 'waiting' } + | { readonly kind: 'other-tab' } + | { readonly kind: 'status'; readonly title: string; readonly body: string } + +export function ConnectReturn(): JSX.Element { + const router = useRouter() + const [view, setView] = useState({ kind: 'waiting' }) + + useEffect(() => { + const callback = parseConnectCallback(window.location.search) + // Not one of ours: nothing to do here. + if (callback === null) { + router.replace('/') + return + } + // The wallet reported a failure: said at once. The tab that showed the code is told too, so it + // can stop waiting for an answer that will not come. + const failure = callbackStatusCopy(callback.status) + const fallback: View = { + kind: 'status', + title: 'Go back to Forge', + body: 'Return to the Forge tab where you started. It checks your wallet on its own, and signs you in when the approval is there.', + } + if (failure) setView({ kind: 'status', ...failure }) + let channel: BroadcastChannel | null = null + try { + channel = typeof BroadcastChannel === 'undefined' ? null : new BroadcastChannel(CALLBACK_CHANNEL) + } catch { + channel = null + } + if (channel === null) { + if (!failure) setView(fallback) + return + } + const open = channel + let answered = false + open.onmessage = (event: MessageEvent) => { + if (!isConnectCallbackAck(event.data, callback.requestHash)) return + answered = true + if (!failure) setView({ kind: 'other-tab' }) + } + const message: ConnectCallbackMessage = { type: 'forge-app-connect-callback', requestHash: callback.requestHash, status: callback.status } + open.postMessage(message) + const timer = setTimeout(() => { + if (!answered && !failure) setView(fallback) + }, ACK_WAIT_MS) + return () => { + clearTimeout(timer) + open.close() + } + }, [router]) + + return ( +
+ {view.kind === 'waiting' ? : null} + {view.kind === 'other-tab' ? ( + <> +

You're signing in on your other Forge tab

+

You can close this one.

+ + ) : null} + {view.kind === 'status' ? ( + <> +

{view.title}

+

{view.body}

+ + + + + ) : null} +
+ ) +} diff --git a/forge-web/components/auth/wallet-connect-flow.test.tsx b/forge-web/components/auth/wallet-connect-flow.test.tsx index 12d3b216d..66c369c0c 100644 --- a/forge-web/components/auth/wallet-connect-flow.test.tsx +++ b/forge-web/components/auth/wallet-connect-flow.test.tsx @@ -3,6 +3,11 @@ * Wallet sign-in over an unfinished renewal whose key is locked: the renewal's passphrase input is * uncontrolled, so the typed passphrase never lands in the DOM's `value` attribute. The wallet's * encryption key goes to the sign-in with every attempt, and is wiped once it is done (D27). + * + * App Connect v2: shown first where the chain supports it (with the group check and the locked-key + * check before the code), a link to the older code and back, the poll cut short on focus and on the + * return page's message, the confirm step, and a renewal in the wallet that granted the key + * (protection first, the old key's renewal mark ended on every way out but a stored key). */ import { act } from 'react' @@ -10,11 +15,32 @@ import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { PendingRenewalChoiceError, PendingRenewalLockedError } from '@/lib/auth/controller' -const { ID, FORGE, answered } = vi.hoisted(() => ({ +const { ID, FORGE, answered, v2, auth } = vi.hoisted(() => ({ ID: '9r27eDsuXEqoMNymW1A2MKFrpBhzSkepVKwXrGzq9dUD', FORGE: { core: 'CoreContract111', collab: 'CollabContract111', community: 'CommunityContract111', group: 'Group111' }, /** The encryption keys of the last answer the fake wallet gave. */ answered: { keys: [] as Uint8Array[] }, + /** The App Connect v2 side of the fake chain and wallet. */ + v2: { + available: false, + /** What the fake wallet answers: resolve it from a test, or reject it. */ + pending: null as { resolve: (g: unknown) => void; reject: (e: Error) => void } | null, + trigger: null as { fire: () => void } | null, + awaited: 0, + calls: [] as string[], + /** The older (v1) request stays unanswered, so its request step stays on screen. */ + holdV1: false, + /** The older flow's response-source lookup never returns (it is still being built). */ + holdSources: false, + /** The renewal request's private key, to see it spent. */ + renewalPriv: null as Uint8Array | null, + }, + /** The signed-in session and controller the flow reads. */ + auth: { + identity: null as string | null, + unlockScope: null as 'full' | 'signing' | null, + controller: {} as Record, + }, })) const FAKE_VAULT_PASSPHRASE = 'fake-vault-passphrase-000' const FAKE_RENEWAL_PASSPHRASE = 'fake-renewal-passphrase-789' @@ -31,13 +57,35 @@ vi.mock('@/lib/auth/connect', async (importOriginal) => ({ })) vi.mock('@/lib/auth/app-connect', async (importOriginal) => ({ ...(await importOriginal()), - responseSources: async () => [{}], - newLoginRequest: () => ({ uri: 'dash-key:fake', expiresAt: Date.now() + 60_000 }), + responseSources: async () => (v2.holdSources ? new Promise(() => undefined) : [{}]), + newLoginRequest: () => { + v2.calls.push('v1-request') + return { uri: 'dash-key:fake', expiresAt: Date.now() + 60_000 } + }, awaitWalletAnswer: async () => { + if (v2.holdV1) return new Promise(() => undefined) answered.keys = [new Uint8Array(32).fill(0x42)] return { kind: 'keys', identityId: ID, keys: [{ scope: {}, limits: {} }], encryptionKeys: answered.keys } }, })) +vi.mock('@/lib/auth/app-connect-v2', async (importOriginal) => ({ + ...(await importOriginal()), + appConnectV2Available: async () => v2.available, + readChainClock: async () => ({ timeMs: 1_800_000_000_000, protocolVersion: 14 }), + newV2LoginRequest: () => { + v2.calls.push('request') + return fakeV2Request(null) + }, + awaitV2Grant: (_sdk: unknown, _req: unknown, p: { trigger: { fire: () => void }; signal: AbortSignal }) => { + v2.awaited++ + v2.trigger = p.trigger + return new Promise((resolve, reject) => { + v2.pending = { resolve, reject } + // The real poll ends with an AbortError when the sheet closes or restarts. + p.signal.addEventListener('abort', () => reject(new DOMException('cancelled', 'AbortError')), { once: true }) + }) + }, +})) vi.mock('@/lib/auth/key-registration', async (importOriginal) => ({ ...(await importOriginal()), isUnlimited: () => false, @@ -45,11 +93,34 @@ vi.mock('@/lib/auth/key-registration', async (importOriginal) => ({ vi.mock('@/lib/auth/responder-profile', () => ({ responderProfile: async () => ({ identityId: ID, name: null, namedAt: null, warnings: [] }), })) -vi.mock('@/components/ui/qr', () => ({ Qr: () => null })) +vi.mock('@/components/ui/qr', () => ({ Qr: ({ value }: { value: string }) =>
{value}
})) vi.mock('@/contexts/auth-context', () => ({ - useAuth: () => ({ adoptWalletKeys, addWalletGrant: vi.fn(), identity: null, isLoading: false, vaults: [], unlockScope: null }), + useAuth: () => ({ + adoptWalletKeys, + addWalletGrant: vi.fn(), + identity: auth.identity, + isLoading: false, + vaults: [], + unlockScope: auth.unlockScope, + controller: auth.controller, + }), })) +/** A v2 request as the (mocked) builder returns it; `hint`: the identity a renewal names. */ +function fakeV2Request(hint: string | null): { appEphemeralPriv: Uint8Array } & Record { + return { + request: { authBindings: [{ totalBudget: 5_000_000_000n, expiresAt: 1_807_776_000_000 }] }, + qrUri: 'dash-key:v2qr?v=2', + linkUri: 'dash-key:v2link?v=2&cb=x', + requestHash: new Uint8Array(20).fill(0xab), + createdAt: Date.now(), + expiresAt: Date.now() + 600_000, + chainTimeAtCreation: 1_800_000_000_000, + identityHint: hint, + appEphemeralPriv: new Uint8Array(32).fill(7), + } +} + const { WalletConnectFlow } = await import('./wallet-connect-flow') ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true @@ -68,8 +139,39 @@ async function flush(): Promise { for (let i = 0; i < 5; i++) await act(async () => Promise.resolve()) } +const checkGroup = vi.fn() +const walletSignInBlocker = vi.fn() +const walletRenewalRequest = vi.fn() +const endWalletRenewal = vi.fn() + beforeEach(() => { adoptWalletKeys.mockReset() + v2.available = false + v2.pending = null + v2.trigger = null + v2.awaited = 0 + v2.calls = [] + v2.holdV1 = false + v2.holdSources = false + v2.renewalPriv = null + auth.identity = null + auth.unlockScope = null + checkGroup.mockReset().mockImplementation(async () => { + v2.calls.push('group') + return { unknown: [], unchecked: [], notice: null } + }) + walletSignInBlocker.mockReset().mockImplementation(async () => { + v2.calls.push('blocker') + return null + }) + walletRenewalRequest.mockReset().mockImplementation(async () => { + v2.calls.push('renewal-request') + const req = { ...fakeV2Request(ID), replacesKeyId: 7 } + v2.renewalPriv = req.appEphemeralPriv + return req + }) + endWalletRenewal.mockReset() + auth.controller = { checkGroup, walletSignInBlocker, walletRenewalRequest, endWalletRenewal } host = document.createElement('div') document.body.appendChild(host) root = createRoot(host) @@ -123,3 +225,399 @@ describe('WalletConnectFlow: a locked unfinished renewal', () => { expect(answered.keys[0]!.every((b) => b === 0)).toBe(true) }) }) + +/** What the verified v2 grant is: the identity and its group-bound key (budget 0.05 DASH). */ +const V2_GRANT = { + identityId: ID, + key: { keyId: 9, wif: 'wif', scope: { unbounded: false }, limits: { remaining: 5_000_000_000n, total: 5_000_000_000n, expiresAt: 1_807_776_000_000 } }, +} +const q = (testId: string): HTMLElement | null => host.querySelector(`[data-testid="${testId}"]`) + +describe('WalletConnectFlow: App Connect v2 sign-in', () => { + it('shows the v2 request first, after the group and locked-key checks, with one-approval terms', async () => { + v2.available = true + act(() => root.render()) + await flush() + expect(v2.calls).toEqual(['group', 'blocker', 'request']) + expect(q('qr-value')!.textContent).toBe('dash-key:v2qr?v=2') + expect(q('approval-terms')!.textContent).toMatch(/One approval covers all of Forge, spending up to 0\.05\d* DASH/) + expect(q('approval-terms')!.textContent).toMatch(/until /) + expect(q('wallet-support')!.textContent).toMatch(/App Connect v2/) + expect(q('older-code')!.textContent).toBe('Using a Dash Wallet build without App Connect v2? Show the older code') + expect(v2.awaited).toBe(1) + }) + + it('goes straight to the older code where v2 is not available', async () => { + v2.holdV1 = true + act(() => root.render()) + await flush() + expect(q('qr-value')!.textContent).toBe('dash-key:fake') + expect(q('older-code')).toBeNull() + expect(q('newer-code')).toBeNull() + expect(v2.calls).toEqual(['v1-request']) + }) + + it('falls back to the older code when the group check refuses', async () => { + v2.available = true + v2.holdV1 = true + checkGroup.mockRejectedValueOnce(new Error('refusing to bind a key to this group')) + act(() => root.render()) + await flush() + expect(q('qr-value')!.textContent).toBe('dash-key:fake') + expect(v2.awaited).toBe(0) + }) + + it('switches to the older code and back', async () => { + v2.available = true + v2.holdV1 = true + act(() => root.render()) + await flush() + await act(async () => q('older-code')!.click()) + await flush() + expect(q('qr-value')!.textContent).toBe('dash-key:fake') + expect(q('wallet-support')!.textContent).not.toMatch(/App Connect v2/) + expect(q('older-code')).toBeNull() + await act(async () => q('newer-code')!.click()) + await flush() + expect(q('qr-value')!.textContent).toBe('dash-key:v2qr?v=2') + }) + + it('asks to unlock first when a locked vault holds a wallet key', async () => { + v2.available = true + walletSignInBlocker.mockResolvedValueOnce('Unlock the key stored for 9r27eD…9dUD first.') + const onUnlock = vi.fn() + act(() => root.render()) + await flush() + expect(q('wallet-blocked')!.textContent).toContain('Unlock the key stored') + expect(q('qr-value')).toBeNull() + expect(v2.calls).not.toContain('request') + await act(async () => byText('Unlock').click()) + expect(onUnlock).toHaveBeenCalled() + }) + + it('confirms who answered, shows the granted limits and the group notice, then stores it as App Connect\'s', async () => { + v2.available = true + checkGroup.mockResolvedValueOnce({ unknown: ['x'], unchecked: [], notice: 'The group also holds 1 contract this build does not know.' }) + const onDone = vi.fn() + adoptWalletKeys.mockResolvedValue(undefined) + act(() => root.render()) + await flush() + await act(async () => v2.pending!.resolve(V2_GRANT)) + await flush() + expect(q('wallet-confirm')).not.toBeNull() + expect(q('granted-identity')!.textContent).toBe(ID) + expect(q('unlimited-key-warning')).toBeNull() + expect(q('approval-terms')!.textContent).toMatch(/spending capped at 0\.05\d* DASH/) + expect(q('group-notice')!.textContent).toContain('does not know') + act(() => host.querySelector('input[type="checkbox"]')!.click()) + act(() => type(host.querySelector('#vault-passphrase')!, FAKE_VAULT_PASSPHRASE)) + act(() => type(host.querySelector('#vault-passphrase-2')!, FAKE_VAULT_PASSPHRASE)) + await act(async () => byText('Finish signing in').click()) + expect(adoptWalletKeys).toHaveBeenCalledWith(ID, [V2_GRANT.key], expect.objectContaining({ passphrase: FAKE_VAULT_PASSPHRASE }), { + discardPendingRenewal: false, + origin: 'app-connect', + }) + expect(onDone).toHaveBeenCalled() + }) + + it('polls at once when the tab regains focus or becomes visible', async () => { + v2.available = true + act(() => root.render()) + await flush() + const fire = vi.spyOn(v2.trigger!, 'fire') + act(() => void window.dispatchEvent(new Event('focus'))) + expect(fire).toHaveBeenCalledTimes(1) + act(() => void document.dispatchEvent(new Event('visibilitychange'))) + expect(fire).toHaveBeenCalledTimes(2) + }) + + it("polls at once when the return page reports this request, and ignores another's", async () => { + v2.available = true + act(() => root.render()) + await flush() + const fire = vi.spyOn(v2.trigger!, 'fire') + const page = new BroadcastChannel('forge-app-connect') + const acks: unknown[] = [] + page.onmessage = (e: MessageEvent) => acks.push(e.data) + page.postMessage({ type: 'forge-app-connect-callback', requestHash: 'cd'.repeat(20), status: 'ok' }) + page.postMessage({ type: 'forge-app-connect-callback', requestHash: 'ab'.repeat(20), status: 'ok' }) + await new Promise((r) => setTimeout(r, 40)) + expect(fire).toHaveBeenCalledTimes(1) + expect(acks).toEqual([{ type: 'forge-app-connect-ack', requestHash: 'ab'.repeat(20) }]) + page.close() + }) + + it('names a refusal and offers another try', async () => { + v2.available = true + act(() => root.render()) + await flush() + await act(async () => v2.pending!.reject(new Error('Two identities answered.'))) + await flush() + expect(host.querySelector('[role="alert"]')!.textContent).toContain('Two identities answered.') + expect(byText('Try again')).toBeDefined() + }) +}) + +describe('WalletConnectFlow: App Connect v2, the edges', () => { + it('takes the old request off screen at once when the code is switched', async () => { + v2.available = true + act(() => root.render()) + await flush() + expect(q('qr-value')!.textContent).toBe('dash-key:v2qr?v=2') + // The older flow is still being built (its sources are not back): the spent v2 code must not stay up. + v2.holdSources = true + await act(async () => q('older-code')!.click()) + await flush() + expect(q('qr-value')).toBeNull() + expect(q('older-code')).toBeNull() + expect(host.textContent).toContain('Finding the wallet login contract') + }) + + it('shows a failed group read with Try again, not a silent switch to the older code', async () => { + v2.available = true + checkGroup.mockRejectedValueOnce(new Error('Reading the contract group timed out')) + act(() => root.render()) + await flush() + expect(host.querySelector('[role="alert"]')!.textContent).toContain('timed out') + expect(byText('Try again')).toBeDefined() + expect(v2.calls).not.toContain('v1-request') + expect(v2.awaited).toBe(0) + }) + + it('takes a failed v2 request off screen and keeps the older code reachable', async () => { + v2.available = true + v2.holdV1 = true + act(() => root.render()) + await flush() + expect(q('qr-value')).not.toBeNull() + await act(async () => v2.pending!.reject(new Error('The key your wallet sent has no spending limit or no expiry.'))) + await flush() + // The spent code is gone; the error stands with Try again and a way to the older code. + expect(q('qr-value')).toBeNull() + expect(host.querySelector('[role="alert"]')!.textContent).toContain('no spending limit') + await act(async () => q('older-code-error')!.click()) + await flush() + expect(v2.calls).toContain('v1-request') + }) + + it('offers the older code when the group read keeps failing, and does not read the group again for it', async () => { + v2.available = true + v2.holdV1 = true + checkGroup.mockRejectedValue(new Error('Reading the contract group timed out')) + act(() => root.render()) + await flush() + expect(host.querySelector('[role="alert"]')!.textContent).toContain('timed out') + checkGroup.mockClear() + await act(async () => q('older-code-error')!.click()) + await flush() + expect(v2.calls).toContain('v1-request') + expect(checkGroup).not.toHaveBeenCalled() + expect(host.querySelector('[role="alert"]')).toBeNull() + }) + + it('says what the wallet reported when it returns with a decline', async () => { + v2.available = true + act(() => root.render()) + await flush() + const page = new BroadcastChannel('forge-app-connect') + page.postMessage({ type: 'forge-app-connect-callback', requestHash: 'ab'.repeat(20), status: 'declined' }) + await act(async () => new Promise((r) => setTimeout(r, 40))) + expect(q('wallet-reported')!.textContent).toContain('Sign-in declined') + page.close() + }) +}) + +describe('WalletConnectFlow: renew in the wallet that granted the key', () => { + const fillProtection = (): void => { + act(() => type(host.querySelector('#vault-passphrase')!, FAKE_VAULT_PASSPHRASE)) + act(() => type(host.querySelector('#vault-passphrase-2')!, FAKE_VAULT_PASSPHRASE)) + } + + it('chooses the protection before any request exists', async () => { + auth.identity = ID + act(() => root.render()) + await flush() + expect(q('wallet-renew-prepare')).not.toBeNull() + expect(q('qr-value')).toBeNull() + expect(walletRenewalRequest).not.toHaveBeenCalled() + expect(byText('Continue to your wallet').disabled).toBe(true) + fillProtection() + expect(byText('Continue to your wallet').disabled).toBe(false) + expect(walletRenewalRequest).not.toHaveBeenCalled() + }) + + it('shows the code, stores the new key as App Connect\'s and keeps the renewal mark until then', async () => { + auth.identity = ID + adoptWalletKeys.mockResolvedValue(undefined) + const onDone = vi.fn() + act(() => root.render()) + await flush() + fillProtection() + await act(async () => byText('Continue to your wallet').click()) + await flush() + expect(walletRenewalRequest).toHaveBeenCalledTimes(1) + expect(q('qr-value')!.textContent).toBe('dash-key:v2qr?v=2') + expect(q('approval-terms')!.textContent).toMatch(/Approve the renewal in the wallet/) + expect(q('older-code')).toBeNull() + expect(endWalletRenewal).not.toHaveBeenCalled() + await act(async () => v2.pending!.resolve(V2_GRANT)) + await flush() + expect(adoptWalletKeys).toHaveBeenCalledWith(ID, [V2_GRANT.key], expect.objectContaining({ passphrase: FAKE_VAULT_PASSPHRASE }), { + discardPendingRenewal: false, + origin: 'app-connect', + }) + expect(onDone).toHaveBeenCalled() + // Stored: the controller already cleared the mark. + expect(endWalletRenewal).not.toHaveBeenCalled() + }) + + it('ends the renewal when the sheet closes before the wallet answers', async () => { + auth.identity = ID + act(() => root.render()) + await flush() + fillProtection() + await act(async () => byText('Continue to your wallet').click()) + await flush() + await act(async () => { + root.render(<>) + }) + // The poll ends with an abort; the renewal's mark goes with it. + await act(async () => v2.pending!.reject(new DOMException('cancelled', 'AbortError'))) + await flush() + expect(endWalletRenewal).toHaveBeenCalledWith(expect.objectContaining({ identityHint: ID, replacesKeyId: 7 })) + expect(adoptWalletKeys).not.toHaveBeenCalled() + }) + + it('ends the renewal when the wallet refuses, and names why', async () => { + auth.identity = ID + act(() => root.render()) + await flush() + fillProtection() + await act(async () => byText('Continue to your wallet').click()) + await flush() + await act(async () => v2.pending!.reject(new Error("The key your wallet sent has no spending limit or no expiry. Forge didn't use it."))) + await flush() + expect(endWalletRenewal).toHaveBeenCalledTimes(1) + expect(host.querySelector('[role="alert"]')!.textContent).toContain('no spending limit') + }) + + it('keeps a granted key that failed to store on screen, with the reason', async () => { + auth.identity = ID + adoptWalletKeys.mockRejectedValue(new Error('Another tab changed the key stored meanwhile.')) + act(() => root.render()) + await flush() + fillProtection() + await act(async () => byText('Continue to your wallet').click()) + await flush() + await act(async () => v2.pending!.resolve(V2_GRANT)) + await flush() + expect(q('wallet-renew-store')).not.toBeNull() + expect(host.querySelector('[role="alert"]')!.textContent).toContain('Another tab changed') + expect(byText('Store the new key')).toBeDefined() + // Not given up until the sheet closes. + expect(endWalletRenewal).not.toHaveBeenCalled() + }) + + it('closing the sheet before the wallet request exists spends it and ends the renewal', async () => { + auth.identity = ID + let release: () => void = () => undefined + const gate = new Promise((resolve) => { + release = resolve + }) + walletRenewalRequest.mockImplementation(async () => { + await gate + const req = { ...fakeV2Request(ID), replacesKeyId: 7 } + v2.renewalPriv = req.appEphemeralPriv + return req + }) + act(() => root.render()) + await flush() + fillProtection() + await act(async () => byText('Continue to your wallet').click()) + await flush() + await act(async () => { + root.render(<>) + }) + await act(async () => release()) + await flush() + expect(v2.awaited).toBe(0) + expect(endWalletRenewal).toHaveBeenCalledWith(expect.objectContaining({ identityHint: ID, replacesKeyId: 7 })) + expect(v2.renewalPriv!.every((b) => b === 0)).toBe(true) + }) + + it('a granted key that cannot be stored yet is held for a decision, then stored', async () => { + auth.identity = ID + adoptWalletKeys.mockRejectedValueOnce(new PendingRenewalChoiceError(7)).mockResolvedValueOnce(undefined) + const onDone = vi.fn() + act(() => root.render()) + await flush() + fillProtection() + await act(async () => byText('Continue to your wallet').click()) + await flush() + await act(async () => v2.pending!.resolve(V2_GRANT)) + await flush() + // The wallet has disabled the old key: the new one is kept on screen, not dropped. + expect(q('wallet-renew-store')).not.toBeNull() + expect(q('pending-renewal-choice')).not.toBeNull() + expect(onDone).not.toHaveBeenCalled() + expect(endWalletRenewal).not.toHaveBeenCalled() + await act(async () => byText('Continue with the wallet').click()) + await flush() + expect(adoptWalletKeys).toHaveBeenLastCalledWith(ID, [V2_GRANT.key], expect.anything(), { discardPendingRenewal: true, origin: 'app-connect' }) + expect(onDone).toHaveBeenCalled() + expect(endWalletRenewal).not.toHaveBeenCalled() + }) + + it('closing the sheet with the new key unstored ends the renewal', async () => { + auth.identity = ID + adoptWalletKeys.mockRejectedValue(new Error('The vault is locked.')) + act(() => root.render()) + await flush() + fillProtection() + await act(async () => byText('Continue to your wallet').click()) + await flush() + await act(async () => v2.pending!.resolve(V2_GRANT)) + await flush() + expect(q('wallet-renew-store')).not.toBeNull() + expect(host.querySelector('[role="alert"]')!.textContent).toContain('vault is locked') + // Not a way out that unmounts the flow (it would drop the key): only a retry. + expect(byText('Unlock')).toBeUndefined() + expect(endWalletRenewal).not.toHaveBeenCalled() + act(() => root.unmount()) + expect(endWalletRenewal).toHaveBeenCalledTimes(1) + root = createRoot(host) + }) + + it('closing the sheet while the new key is being stored leaves the mark to that attempt', async () => { + auth.identity = ID + let fail: (e: Error) => void = () => undefined + adoptWalletKeys.mockImplementation( + () => + new Promise((_resolve, reject) => { + fail = reject + }), + ) + act(() => root.render()) + await flush() + fillProtection() + await act(async () => byText('Continue to your wallet').click()) + await flush() + await act(async () => v2.pending!.resolve(V2_GRANT)) + await flush() + act(() => root.unmount()) + // Mid-store: another tab must keep treating the old key as replaced. + expect(endWalletRenewal).not.toHaveBeenCalled() + await act(async () => fail(new Error('Another tab changed the key stored meanwhile.'))) + expect(endWalletRenewal).toHaveBeenCalledTimes(1) + root = createRoot(host) + }) + + it('asks a signing-only tab to unlock first', async () => { + auth.identity = ID + auth.unlockScope = 'signing' + act(() => root.render()) + await flush() + expect(q('renew-unlock')).not.toBeNull() + expect(walletRenewalRequest).not.toHaveBeenCalled() + }) +}) diff --git a/forge-web/components/auth/wallet-connect-flow.tsx b/forge-web/components/auth/wallet-connect-flow.tsx index b5d4e75ea..e0d7a949c 100644 --- a/forge-web/components/auth/wallet-connect-flow.tsx +++ b/forge-web/components/auth/wallet-connect-flow.tsx @@ -19,6 +19,19 @@ * * Dash Wallet answers on testnet only (`walletSignInSupported`); elsewhere the sheet says so. * + * App Connect v2 (`lib/auth/app-connect-v2.ts`) comes first where the network and the chain allow + * it: ONE request, one approval, one key bound to the whole Forge contract group with a budget + * and an expiry, so no guided grants follow. A link switches to the v1 flow above for wallets + * that do not speak v2 (the two never share a QR: a v1-only wallet refuses `v=2`). The phone's + * deep link carries a callback to `/connect/`; the poll also runs when the tab regains focus and + * when that page reports the wallet came back (`lib/auth/connect-callback.ts`). Without an + * identity hint the confirm step stays ("A wallet answered for this identity"). + * + * `mode="renew"` renews the signed-in session's key in the wallet that granted it (origin + * `app-connect`): the protection for the new key is chosen BEFORE the code shows (the wallet + * disables the old key when it approves), the request names the identity, and the new key is + * stored without a confirm step. + * * `mode="grant"` asks the signed-in identity's wallet for a key on another contract (a shipped * wallet grants one contract per approval) and adds it to the session: no confirmation step, * since only answers from the signed-in identity are read. @@ -31,9 +44,10 @@ import { useCallback, useEffect, useRef, useState } from 'react' import { AlertTriangle, RefreshCw, Smartphone } from 'lucide-react' +import { FiatNote } from '@/components/ui/fiat-note' import { useAuth } from '@/contexts/auth-context' import { useUiStore } from '@/hooks/use-ui-store' -import { PendingRenewalChoiceError, PendingRenewalLockedError, UnlockNeededError } from '@/lib/auth/controller' +import { PendingRenewalChoiceError, PendingRenewalLockedError, UnlockNeededError, type WalletRenewalRequest } from '@/lib/auth/controller' import { Button } from '@/components/ui/button' import { UnlockMore } from '@/components/auth/unlock-more' import { Field, Input } from '@/components/ui/input' @@ -42,6 +56,7 @@ import { ErrorBox, useProtection } from '@/components/auth/protection-fields' import { Waiting } from '@/components/auth/step-status' import { ScanOnlyHere } from '@/components/auth/scan-warning' import { ACTIVE_NETWORK } from '@/lib/constants' +import { creditsToDash } from '@/lib/sdk/cost' import { REQUEST_TTL_MS, RequestExpired, @@ -54,12 +69,26 @@ import { type PollStatus, type WalletAnswer, } from '@/lib/auth/app-connect' +import { + PollTrigger, + appConnectV2Available, + awaitV2Grant, + disposeV2Request, + newV2LoginRequest, + readChainClock, + type V2Grant, + type V2LoginRequest, +} from '@/lib/auth/app-connect-v2' +import { connectionId } from '@/lib/auth/connection-id' +import { callbackStatusCopy, connectCallbackUrl, listenForCallback } from '@/lib/auth/connect-callback' +import { defaultLimits } from '@/lib/auth/limited-key' import { GRANT_COPY, isUnlimited, keyRegistrationUri, scopeCovers, type WalletKey } from '@/lib/auth/key-registration' -import { contractKind } from '@/lib/deployments' +import { contractKind, type ForgeIds } from '@/lib/deployments' import { responderProfile, type ResponderProfile } from '@/lib/auth/responder-profile' import { isAbort } from '@/lib/sdk/facade' import { PHASE_TEXT, connectPlatform, withPlatformRead } from '@/lib/auth/connect' -import { formatDate } from '@/lib/view/format' +import { creditsAsDash, formatDate } from '@/lib/view/format' +import type { KeyLimits } from '@/lib/view/funds' import { cn, errorMessage } from '@/lib/utils' /** The wallet link where a wallet can answer (the main action), and where none can (secondary). */ @@ -67,12 +96,82 @@ const DEEP_LINK_PRIMARY = 'bg-forge-700 text-white hover:bg-forge-800' const DEEP_LINK_SECONDARY = 'border border-anvil-300 text-anvil-800 hover:bg-anvil-100 dark:border-anvil-700 dark:text-anvil-100 dark:hover:bg-anvil-800' +/** A small underlined text button under the code (the older/newer code links). */ +const TEXT_BUTTON = 'hit-area block text-[12px] text-anvil-500 underline hover:text-anvil-800 dark:text-anvil-400 dark:hover:text-anvil-100' + +type Sdk = Awaited> + +/** What a v2 request asks the wallet for: the budget (credits) and the proposed expiry (ms). */ +interface V2Terms { + readonly budget: bigint | null + readonly expiresAt: number | null +} + type Step = - | { readonly kind: 'request'; readonly uri: string; readonly expiresAt: number } + /** `linkUri`: the phone's deep link (v2: it carries the callback); `v2`: the App Connect v2 request. */ + | { readonly kind: 'request'; readonly uri: string; readonly linkUri?: string; readonly expiresAt: number; readonly v2?: V2Terms } | { readonly kind: 'register'; readonly uri: string; readonly expiresAt: number } - | { readonly kind: 'confirm'; readonly profile: ResponderProfile; readonly unlimited: boolean; readonly unbounded: boolean } + | { + readonly kind: 'confirm' + readonly profile: ResponderProfile + readonly unlimited: boolean + readonly unbounded: boolean + /** A v2 grant's limits (as the chain records them), and the group check's notice. */ + readonly v2?: { readonly limits: KeyLimits | null; readonly notice: string | null } + } + /** A locked vault holds a wallet key that a new approval would disable: unlock it first. */ + | { readonly kind: 'blocked'; readonly message: string } + /** + * A renewal's new key is granted (the wallet has already disabled the old one) and is being + * stored. When storing needs a decision or an unlock (an unfinished renewal on this device, a + * locked vault), the grant is held here to try again; closing the sheet drops it. + */ + | { readonly kind: 'renew-store' } | { readonly kind: 'expired' } +/** The request's primary binding as {@link V2Terms}. */ +function termsOf(req: V2LoginRequest): V2Terms { + const binding = req.request.authBindings[0] + return { budget: binding?.totalBudget ?? null, expiresAt: binding?.expiresAt ?? null } +} + +/** + * Poll for the wallet's v2 answer, and poll at once when the tab regains focus or becomes visible + * (the user comes back from the wallet) or the `/connect/` page reports the wallet returned + * (`onReturn` gets the status it carries). The request is spent however this ends. + */ +export function awaitGrantWithWake( + sdk: Parameters[0], + req: V2LoginRequest, + p: Omit[2], 'trigger'> & { readonly onReturn?: (status: string | null) => void }, +): Promise { + const { onReturn, ...rest } = p + const trigger = new PollTrigger() + const wake = (): void => trigger.fire() + const onVisible = (): void => { + if (document.visibilityState === 'visible') trigger.fire() + } + let stopCallback = (): void => undefined + const stop = (): void => { + window.removeEventListener('focus', wake) + document.removeEventListener('visibilitychange', onVisible) + stopCallback() + } + try { + window.addEventListener('focus', wake) + document.addEventListener('visibilitychange', onVisible) + stopCallback = listenForCallback(req.requestHash, (status) => { + onReturn?.(status) + wake() + }) + } catch (e) { + stop() + disposeV2Request(req) + return Promise.reject(e) + } + return awaitV2Grant(sdk, req, { ...rest, trigger }).finally(stop) +} + /** * A phone or tablet browser: the wallet is on this device, so a link beats a QR. Dash Wallet * exists for Android and iOS only, so a desktop browser gets the QR alone. @@ -83,8 +182,19 @@ function onMobile(): boolean { return uaData?.mobile ?? /Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent) } -export function WalletConnectFlow({ onDone, mode = 'login', contractId }: { onDone: () => void; mode?: 'login' | 'grant'; contractId?: string }): JSX.Element { - const { adoptWalletKeys, addWalletGrant, identity, isLoading, vaults, unlockScope } = useAuth() +export function WalletConnectFlow({ + onDone, + mode = 'login', + contractId, + onUnlock, +}: { + onDone: () => void + mode?: 'login' | 'grant' | 'renew' + contractId?: string + /** 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() // Read when the request starts (a scope change must not restart a running request). const scopeRef = useRef(unlockScope) scopeRef.current = unlockScope @@ -117,45 +227,85 @@ export function WalletConnectFlow({ onDone, mode = 'login', contractId }: { onDo const [preparing, setPreparing] = useState(PHASE_TEXT.connecting) const [attempt, setAttempt] = useState(0) const [confirmed, setConfirmed] = useState(false) - const grant = useRef<{ identityId: string; keys: readonly WalletKey[]; answer: WalletAnswer } | null>(null) + /** The answer held for the confirm step: a v1 answer (its key bytes are wiped) or a v2 grant (`answer: null`). */ + const grant = useRef<{ identityId: string; keys: readonly WalletKey[]; answer: WalletAnswer | null } | null>(null) /** Wipe the held answer's private key bytes and drop the grant. */ const dropGrant = useCallback(() => { - if (grant.current) wipeAnswer(grant.current.answer) + if (grant.current?.answer) wipeAnswer(grant.current.answer) grant.current = null }, []) const mobile = onMobile() const unlimited = step?.kind === 'confirm' && step.unlimited const { fields, protection, problem } = useProtection({ preferPasskey: unlimited }) + /** + * The wallet-login version the user asked for with "Show the older code" (v1), and whether a v2 + * request was on offer here at all (then the v1 code links back to it). + */ + const [olderCode, setOlderCode] = useState(false) + const [v2Offered, setV2Offered] = useState(false) + /** + * Renewal: the protection for the new key is chosen first (the wallet disables the old key when + * it approves), then the code shows. `renewGo` flips on that choice; the protection is kept for + * a retry. The renewal is of the signed-in session; its tab must be fully unlocked. + */ + const [renewGo, setRenewGo] = useState(false) + const renewProtection = useRef | null>(null) + const needsUnlock = mode === 'renew' && unlockScope === 'signing' + /** A wallet renewal whose new key is not stored yet: its mark ends if the sheet closes first. */ + const renewalReq = useRef(null) + /** What the wallet's return page reported (`ac`), when it was a failure. */ + const [reported, setReported] = useState(null) // Read at request time, not effect deps: a change must not restart a request mid-flow (the // identity changes from null to the new one inside the login itself). - const latest = useRef({ addWalletGrant, onDone, stored: vaults.map((v) => v.identityId) }) - latest.current = { addWalletGrant, onDone, stored: vaults.map((v) => v.identityId) } + const latest = useRef({ addWalletGrant, adoptWalletKeys, onDone, controller, stored: vaults.map((v) => v.identityId) }) + latest.current = { addWalletGrant, adoptWalletKeys, onDone, controller, stored: vaults.map((v) => v.identityId) } // A grant is for the signed-in identity: a different one (or signing out) starts over. const grantFor = mode === 'grant' ? identity : null // The sign-in sheet: unlocking there finishes an unfinished renewal with its passphrase. const openLogin = useUiStore((s) => s.openLogin) + // The sheet closes with a renewal's new key unstored (the old one is already disabled): no key + // is being replaced after all, so other tabs stop expecting one. + const mounted = useRef(true) + /** A renewal's new key is being stored now: the mark ends with that attempt, not with the sheet. */ + const storing = useRef(false) + useEffect(() => { + mounted.current = true + return () => { + mounted.current = false + if (renewalReq.current && !storing.current) latest.current.controller.endWalletRenewal(renewalReq.current) + } + }, []) + // A reloaded tab holds the signing key only: storing the wallet's keys over the stored key + // (carrying its grants and settings across) needs the vault open. Unlock, then carry on. + const [unlockFirst, setUnlockFirst] = useState<(() => void) | null>(null) /** * Store the wallet's keys. `discard`: give up an unfinished renewal on this device first, * keeping its key (opened with `renewalUnlock` when given) for the next revoke to disable; * `drop`: give it up without its key. */ - // A reloaded tab holds the signing key only: storing the wallet's keys over the stored key - // (carrying its grants and settings across) needs the vault open. Unlock, then carry on. - const [unlockFirst, setUnlockFirst] = useState<(() => void) | null>(null) const finish = async (discard: boolean, renewalUnlock?: { passphrase: string } | 'passkey', drop = false): Promise => { const g = grant.current - if (!protection || !g) return + // A renewal stores with the protection chosen before its code showed (its fields are gone). + const chosen = (mode === 'renew' ? renewProtection.current : null) ?? protection + if (!g) return + if (!chosen) { + setError('Choose how to protect the new key first.') + return + } setError(null) + storing.current = renewalReq.current !== null try { - await adoptWalletKeys(g.identityId, g.keys, protection, { + await adoptWalletKeys(g.identityId, g.keys, chosen, { discardPendingRenewal: discard, ...(renewalUnlock ? { renewalUnlock } : {}), ...(drop ? { dropUnopened: true } : {}), - encryptionKeys: g.answer.encryptionKeys, - justRegistered: g.answer.kind === 'register', + // A v1 answer brings the wallet's encryption key; a v2 grant has none and is stored as App Connect's. + ...(g.answer ? { encryptionKeys: g.answer.encryptionKeys, justRegistered: g.answer.kind === 'register' } : { origin: 'app-connect' as const }), }) dropGrant() + // Stored: the controller already ended a wallet renewal's mark. + renewalReq.current = null setPendingRenewal(null) setRenewalLocked(null) if (renewalPassphraseRef.current) renewalPassphraseRef.current.value = '' @@ -169,23 +319,52 @@ export function WalletConnectFlow({ onDone, mode = 'login', contractId }: { onDo void finish(discard, renewalUnlock, drop) }) else setError(errorMessage(e)) + // The sheet closed while this was storing, so nothing will retry: the old key is not being replaced. + if (!mounted.current && renewalReq.current) { + latest.current.controller.endWalletRenewal(renewalReq.current) + renewalReq.current = null + } + } finally { + storing.current = false } } + // The effect below stores a renewal's grant through the latest render's `finish`. + const finishRef = useRef(finish) + finishRef.current = finish + useEffect(() => { - const controller = new AbortController() - const signal = controller.signal + const abort = new AbortController() + const signal = abort.signal setError(null) setConfirmed(false) setStatus('waiting') + setReported(null) void (async () => { try { if (!forge) throw new Error('Dash Forge is not deployed here') if (mode === 'grant' && !grantFor) throw new Error('Sign in (or unlock) first: the approval is added to the signed-in identity.') // A grant is sealed with the vault: a reloaded (signing-only) tab unlocks first (below). if (mode === 'grant' && scopeRef.current === 'signing') return + // A renewal waits for its protection (chosen before the code shows) and for a full unlock. + if (mode === 'renew' && (!renewGo || scopeRef.current === 'signing')) return const sdk = await connectPlatform(ACTIVE_NETWORK.network, (p) => !signal.aborted && setPreparing(PHASE_TEXT[p])) if (signal.aborted) return + if (mode === 'renew') { + await runRenewal(sdk, forge, signal) + return + } + // App Connect v2 first where the network and the chain allow it, unless the user asked + // for the older code (a wallet without v2 refuses a v2 request). + if (mode === 'login' && !olderCode) { + setPreparing('Checking what your wallet can answer') + const v2 = await v2Offer(sdk) + if (signal.aborted) return + if (v2.available) { + await runV2Login(sdk, forge, signal, v2.notice) + return + } + } setPreparing('Finding the wallet login contract') const sources = await withPlatformRead(responseSources(sdk, ACTIVE_NETWORK.key), 'Finding the wallet login contract') if (signal.aborted) return @@ -236,22 +415,222 @@ export function WalletConnectFlow({ onDone, mode = 'login', contractId }: { onDo } catch (e) { if (signal.aborted || isAbort(e)) return if (e instanceof RequestExpired) setStep({ kind: 'expired' }) - else setError(errorMessage(e)) + else { + // A v2 request that failed is spent (its key is gone): it must not stay up to be scanned. + setStep((cur) => (cur?.kind === 'request' && cur.v2 ? null : cur)) + setError(errorMessage(e)) + } } })() + + /** Whether a v2 request can be offered here, and the group check's notice for the confirm step. */ + async function v2Offer(sdk: Sdk): Promise<{ available: boolean; notice: string | null }> { + if (!(await appConnectV2Available(sdk, ACTIVE_NETWORK.network))) return { available: false, notice: null } + // On offer here from now on: if what follows fails, the older code is still one click away. + if (!signal.aborted) setV2Offered(true) + try { + // Forge's own group check, before any code shows. + const check = await latest.current.controller.checkGroup() + return { available: true, notice: check.notice } + } catch (e) { + // Only Forge's refusal of the group means "no v2 here"; a failed read is shown, with Try again. + if (errorMessage(e).startsWith('refusing to bind')) { + if (!signal.aborted) setV2Offered(false) + return { available: false, notice: null } + } + throw e + } + } + + /** What both v2 paths pass the poll: status updates only while this request is current. */ + const pollOptions = (forge: ForgeIds): Parameters[2] => ({ + network: ACTIVE_NETWORK.network, + forge, + signal, + onStatus: (s) => { + if (!signal.aborted) setStatus(s) + }, + onReturn: (status) => { + if (!signal.aborted) setReported(status) + }, + }) + + /** v2 sign-in: one request, then the confirm step (nobody is named, so anyone could answer). */ + async function runV2Login(sdk: Sdk, forge: ForgeIds, aborted: AbortSignal, notice: string | null): Promise { + // Any approval disables the key of this browser's previous grant: a locked vault that holds + // one is opened first, while it still can be. + const blocker = await latest.current.controller.walletSignInBlocker() + if (aborted.aborted) return + if (blocker !== null) { + setStep({ kind: 'blocked', message: blocker }) + return + } + const { timeMs } = await readChainClock(sdk) + if (aborted.aborted) return + const req = newV2LoginRequest(ACTIVE_NETWORK.network, forge, { + connectionId: connectionId(ACTIVE_NETWORK.key), + chainNow: timeMs, + callbackUrl: connectCallbackUrl, + }) + setStep({ kind: 'request', uri: req.qrUri, linkUri: req.linkUri, expiresAt: req.expiresAt, v2: termsOf(req) }) + const granted = await awaitGrantWithWake(sdk, req, pollOptions(forge)) + if (aborted.aborted) return + grant.current = { identityId: granted.identityId, keys: [granted.key], answer: null } + const profile = await responderProfile(sdk, granted.identityId, ACTIVE_NETWORK.network, latest.current.stored) + if (aborted.aborted) return + setStep({ kind: 'confirm', profile, unlimited: false, unbounded: false, v2: { limits: granted.key.limits, notice } }) + } + + /** Renewal: the wallet that granted this browser's key grants a new one (no confirm: the identity is known). */ + async function runRenewal(sdk: Sdk, forge: ForgeIds, aborted: AbortSignal): Promise { + if (!renewProtection.current) throw new Error('Choose how to protect the new key first.') + const auth = latest.current.controller + const req = await auth.walletRenewalRequest({ callbackUrl: connectCallbackUrl }) + let granted: V2Grant + try { + if (aborted.aborted) { + disposeV2Request(req) + auth.endWalletRenewal(req) + return + } + setStep({ kind: 'request', uri: req.qrUri, linkUri: req.linkUri, expiresAt: req.expiresAt, v2: termsOf(req) }) + granted = await awaitGrantWithWake(sdk, req, pollOptions(forge)) + } catch (e) { + // Cancelled, expired or refused: the old key is not being replaced after all. + auth.endWalletRenewal(req) + throw e + } + // The wallet has answered, so it has disabled the old key: store the new one now, even if + // the sheet is closing. When that needs a decision or an unlock, the grant is held for it. + renewalReq.current = req + grant.current = { identityId: granted.identityId, keys: [granted.key], answer: null } + setStep({ kind: 'renew-store' }) + await finishRef.current(false) + } return () => { - controller.abort() + abort.abort() dropGrant() } // `attempt` restarts the whole request (a new ephemeral key and QR). - }, [attempt, forge, target, mode, grantFor, dropGrant, grantWhat]) + }, [attempt, forge, target, mode, grantFor, dropGrant, grantWhat, olderCode, renewGo, needsUnlock]) - const restart = useCallback(() => setAttempt((a) => a + 1), []) + const restart = useCallback(() => { + // The spent request goes off screen; the next one replaces it. + setStep(null) + setAttempt((a) => a + 1) + }, []) + /** Switch between the v2 and the older code: the old request goes off screen at once (its key is spent). */ + const switchCode = (older: boolean): void => { + setStep(null) + setOlderCode(older) + } // A reloaded tab holds the signing key only; an approval is stored with the rest of the vault. if (mode === 'grant' && unlockScope === 'signing') { return } + if (needsUnlock) return + // A renewal asks how to protect the new key before its code shows: the wallet disables the old + // key as it approves, so the new one must be storable the moment the answer arrives. + if (mode === 'renew' && !renewGo) { + const defaults = defaultLimits() + 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. +

+

+ +

+ {fields} + + {problem ?

{problem}

: null} +
+ ) + } + if (step?.kind === 'blocked') { + return ( +
+

{step.message}

+
+ {onUnlock ? ( + + ) : null} + +
+
+ ) + } + /** An unfinished renewal on this device that storing the wallet's keys ran into: the choice, and its unlock. */ + const pendingRenewalUi = + pendingRenewal !== null ? ( +
+

{pendingRenewal}

+
+ + +
+ {renewalLocked !== null ? ( +
+

{renewalLocked.message}

+ {renewalLocked.methods.includes('passphrase') ? ( + + setHasRenewalPassphrase(e.target.value !== '')} /> + + ) : null} +
+ {renewalLocked.methods.includes('passphrase') ? ( + + ) : null} + {renewalLocked.methods.includes('passkey') ? ( + + ) : null} + +
+
+ ) : null} +
+ ) : null + 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.

+ {pendingRenewalUi} + {unlockFirst ? : null} + +
+ +
+
+ ) + } if (step?.kind === 'confirm') { const { profile } = step return ( @@ -280,6 +659,20 @@ export function WalletConnectFlow({ onDone, mode = 'login', contractId }: { onDo ))} {step.unlimited ? : null} + {step.v2 ? ( + <> + {step.v2.limits?.total != null ? ( +

+ +

+ ) : null} + {step.v2.notice ? ( +

+ {step.v2.notice} +

+ ) : null} + + ) : null}

Anyone who saw your QR code could have answered first with their own identity; this wallet protocol cannot tell. Only you can, by comparing the username and id above with what your wallet showed. @@ -298,44 +691,7 @@ export function WalletConnectFlow({ onDone, mode = 'login', contractId }: { onDo > Finish signing in - {pendingRenewal !== null ? ( -

-

{pendingRenewal}

-
- - -
- {renewalLocked !== null ? ( -
-

{renewalLocked.message}

- {renewalLocked.methods.includes('passphrase') ? ( - - setHasRenewalPassphrase(e.target.value !== '')} /> - - ) : null} -
- {renewalLocked.methods.includes('passphrase') ? ( - - ) : null} - {renewalLocked.methods.includes('passkey') ? ( - - ) : null} - -
-
- ) : null} -
- ) : null} + {pendingRenewalUi} {problem ?

{problem}

: null} {unlockFirst ? : null} @@ -359,8 +715,14 @@ export function WalletConnectFlow({ onDone, mode = 'login', contractId }: { onDo const qrLabel = isRegister ? 'Wallet key registration request' : 'Wallet login request' // Where no released wallet can answer (a devnet, mainnet), that comes first and the wallet // link is secondary: a big primary button that cannot work is a dead end (QW2-029). - const supported = walletSignInSupported(ACTIVE_NETWORK.network) - const supportNote = mode === 'login' && step?.kind === 'request' ? : null + const v2 = step?.kind === 'request' ? step.v2 : undefined + const reportedCopy = step?.kind === 'request' ? callbackStatusCopy(reported) : undefined + // The phone's deep link may carry the callback the QR leaves out. + const linkUri = step?.kind === 'request' && step.linkUri ? step.linkUri : uri + // A v2 request is the one on offer where it shows, so its link leads even where no released + // wallet answers yet; a v1 request keeps the dead-end rule above. + const supported = walletSignInSupported(ACTIVE_NETWORK.network) || v2 !== undefined + const supportNote = mode === 'login' && step?.kind === 'request' ? : null // Said where the QR is on screen: a phone's QR sits in a collapsed disclosure. const qrPrivate = step?.kind === 'request' ?

Keep this QR code private: anyone who scans it can answer it.

: null return ( @@ -369,6 +731,12 @@ export function WalletConnectFlow({ onDone, mode = 'login', contractId }: { onDo {mode === 'grant' && !isRegister ? (

Approve {grantWhat.toLowerCase()} for this identity in your wallet.

) : null} + {v2 ? ( +

+ {mode === 'renew' ? 'Approve the renewal in the wallet that gave this browser its key. ' : 'Approve in your wallet. '} + +

+ ) : null} {isRegister ? (

One more step, first time only. Your wallet approved, and now it has to add Forge's key to your identity.{' '} @@ -380,7 +748,7 @@ export function WalletConnectFlow({ onDone, mode = 'login', contractId }: { onDo mobile ? ( <> : null} {supported ? supportNote : null} + {reportedCopy ? ( +

+ {reportedCopy.title}. {reportedCopy.body} +

+ ) : null} + {mode === 'login' && v2 ? ( + + ) : null} + {mode === 'login' && step?.kind === 'request' && !v2 && v2Offered ? ( + + ) : null} {error ? ( ) : null} + {mode === 'login' && error && v2Offered && !olderCode ? ( + + ) : null} ) } @@ -432,8 +820,15 @@ export function WalletConnectFlow({ onDone, mode = 'login', contractId }: { onDo * development build still pins testnet to protocol 13 while testnet runs 14, so Platform rejects * its answer until that is fixed (issue #591). */ -export function WalletSupportNote(): JSX.Element { +export function WalletSupportNote({ protocol = 'v1' }: { protocol?: 'v1' | 'v2' } = {}): JSX.Element { const { network, key } = ACTIVE_NETWORK + if (protocol === 'v2') { + return ( +

+ Needs a Dash Wallet build that supports App Connect v2, which may be a development build. Wallets without it can answer the older code. +

+ ) + } if (!walletSignInSupported(network)) { return (

@@ -452,6 +847,27 @@ export function WalletSupportNote(): JSX.Element { ) } +/** + * What one v2 approval covers: all of Forge, up to a budget (credits) until a date. `granted`: + * the limits the chain records after the wallet's approval; else the ones Forge proposes, which + * the wallet may change. + */ +function ApprovalTerms({ budget, expiresAt, granted = false }: { budget: bigint | null; expiresAt: number | null; granted?: boolean }): JSX.Element { + const dash = budget === null ? null : creditsToDash(Number(budget)) + return ( + <> + One approval covers all of Forge + {dash !== null ? ( + <> + , {granted ? 'with spending capped at' : 'spending up to'} {creditsAsDash(Number(budget))} DASH + + + ) : null} + {expiresAt !== null ? <> until {formatDate(expiresAt)} : null}.{granted ? '' : ' Your wallet may offer other limits.'} + + ) +} + /** "This key has no spending limit" (a shipped wallet's key): what it means, what to do. */ export function UnlimitedKeyWarning({ unbounded }: { unbounded: boolean }): JSX.Element { return ( diff --git a/forge-web/components/keys-panel.tsx b/forge-web/components/keys-panel.tsx index 649c8377d..320e5b9a9 100644 --- a/forge-web/components/keys-panel.tsx +++ b/forge-web/components/keys-panel.tsx @@ -43,7 +43,7 @@ export async function forgetConfirm(identityId: string): Promise @@ -128,7 +130,11 @@ export function KeysPanel(): JSX.Element { ) : null} {low ? ( -

This browser's key is nearly used up. Top it up or renew it (uses your master key once).

+

+ {inWallet + ? "This browser's key is nearly used up. Renew it in your wallet, or top it up with your identity file or recovery phrase." + : "This browser's key is nearly used up. Top it up or renew it (uses your master key once)."} +

) : null}
{canTopUp ? ( @@ -137,8 +143,14 @@ export function KeysPanel(): JSX.Element { ) : null} {/* A pasted key is not Forge's to renew: that is a first import. */} - + ) : null} + {pasted ? ( +
+ + ) : null} {view === 'grant' ? ( <> {/* Keyed by contract: the next step starts a new request, never the last one's QR. */} @@ -231,6 +232,27 @@ export function LoginModal(): JSX.Element { ) } +/** + * The sheet's title. A write asked for the sheet: say which (L-62). Creating an identity is + * sign-up, and says so on every step (QW4-022), as GitHub's "Create your account" does. + */ +function titleFor(view: View | null, grantTitle: string, action: string | undefined): string { + switch (view) { + case 'grant': + return grantTitle + case 'renew': + return "Renew this browser's key" + case 'wallet-renew': + return "Renew this browser's key in your wallet" + case 'create': + return 'Create your identity' + case 'dg': + return 'Sign in with dg' + default: + return action ? `Sign in to ${action}` : 'Sign in to Dash Forge' + } +} + /** Skip this approval, or the rest: a skipped one is asked for when a write first needs it. */ function GuidedSkip({ step, onSkip, onSkipAll }: { step: { readonly step: number; readonly of: number }; onSkip: () => void; onSkipAll: () => void }): JSX.Element { return ( @@ -255,7 +277,8 @@ function GuidedSkip({ step, onSkip, onSkipAll }: { step: { readonly step: number /** The sheet's description line for a view. */ function describeView(view: View, limitedKeys: boolean): 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 sends this browser a key it derives for Dash Forge. Your recovery phrase and master key stay on the phone.' + 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 (!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. @@ -323,7 +346,7 @@ function Tile({ function ChooseView({ onPick }: { onPick: (v: View) => void }): JSX.Element { const { limitedKeys } = useAuth() const closeLogin = useUiStore((s) => s.closeLogin) - const walletAvailable = useWalletAvailability(limitedKeys) + const { available: walletAvailable, v2: walletV2 } = useWalletAvailability(limitedKeys) const [advanced, setAdvanced] = useState(false) const creating = useCreationInProgress() // While writes are paused (a devnet move, or the operator's PAGES_NOTICE=paused), no identity is @@ -331,15 +354,18 @@ function ChooseView({ onPick }: { onPick: (v: View) => void }): JSX.Element { const pausedReason = writesPausedReason() // No forge-v2 here means no contract group to bind a key to: nothing to sign in to. if (!limitedKeys) return - // First only where Dash Wallet can answer (testnet); elsewhere last, saying why. - const walletFirst = walletSignInSupported(ACTIVE_NETWORK.network) + // First where a wallet can answer: App Connect v2 is on offer here, or Dash Wallet answers the + // older exchange (testnet). Elsewhere last, saying why. + const walletFirst = walletV2 || walletSignInSupported(ACTIVE_NETWORK.network) const walletTile = walletAvailable ? ( { if (!limitedKeys) return let cancelled = false connectPlatform(ACTIVE_NETWORK.network) - .then((sdk) => withTimeout(walletLoginAvailable(sdk, ACTIVE_NETWORK.key), PLATFORM_READ_MS, 'Finding the wallet login contract')) + .then(async (sdk) => { + // v2 needs no response contract of its own; a failed check only means "not v2". + const v2 = await withTimeout(appConnectV2Available(sdk, ACTIVE_NETWORK.network), PLATFORM_READ_MS, 'Checking what your wallet can answer').catch(() => false) + // When Platform cannot be asked, the tile shows anyway (see above). + const v1 = await withTimeout(walletLoginAvailable(sdk, ACTIVE_NETWORK.key), PLATFORM_READ_MS, 'Finding the wallet login contract').catch(() => true) + return { available: v1 || v2, v2 } + }) .then( - (ok) => !cancelled && setAvailable(ok), - () => !cancelled && setAvailable(true), + (next) => !cancelled && setState(next), + () => !cancelled && setState({ available: true, v2: false }), ) return () => { cancelled = true } }, [limitedKeys]) - return available + return state } /** A dashed "choose a file" button over a hidden file input. */ diff --git a/forge-web/components/low-funds-banner.test.tsx b/forge-web/components/low-funds-banner.test.tsx new file mode 100644 index 000000000..1b3784f5f --- /dev/null +++ b/forge-web/components/low-funds-banner.test.tsx @@ -0,0 +1,82 @@ +// @vitest-environment jsdom +/** + * The low-funds banner sends a key a wallet granted (App Connect) to be renewed in that wallet; + * every other key keeps "Renew key" (the identity file). + */ + +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 ID = '9r27eDsuXEqoMNymW1A2MKFrpBhzSkepVKwXrGzq9dUD' +const session = vi.hoisted(() => ({ origin: null as 'app-connect' | null, reason: 'key-expiry' as 'key-expiry' | 'key-budget' | 'balance', level: 'low' as 'low' | 'empty' })) + +vi.mock('@/contexts/auth-context', () => ({ + useAuth: () => ({ + identity: ID, + origin: session.origin, + funds: { level: session.level, reason: session.reason, spendable: 1_000_000_000n }, + }), +})) + +const { LowFundsBanner } = await import('./low-funds-banner') + +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +let host: HTMLDivElement +let root: Root +const main = (): HTMLButtonElement => host.querySelector('[data-testid="low-funds-banner"] button')! + +async function show(): Promise { + act(() => root.render()) + await act(async () => Promise.resolve()) +} + +beforeEach(() => { + session.origin = null + session.reason = 'key-expiry' + session.level = 'low' + sessionStorage.clear() + host = document.createElement('div') + document.body.appendChild(host) + root = createRoot(host) +}) +afterEach(() => { + act(() => useUiStore.getState().closeLogin()) + act(() => root.unmount()) + host.remove() +}) + +describe('the low-funds banner', () => { + it("renews a wallet-granted key in the wallet", async () => { + session.origin = 'app-connect' + await show() + expect(main().textContent).toBe('Renew in your wallet') + act(() => main().click()) + expect(useUiStore.getState().loginView).toBe('wallet-renew') + }) + + it('also for an empty budget', async () => { + session.origin = 'app-connect' + session.reason = 'key-budget' + session.level = 'empty' + await show() + expect(main().textContent).toBe('Renew in your wallet') + }) + + it('keeps "Renew key" and the identity file for a key this browser registered', async () => { + await show() + expect(main().textContent).toBe('Renew key') + act(() => main().click()) + expect(useUiStore.getState().loginView).toBe('import') + }) + + it('a low balance is still a top-up, whatever the key came from', async () => { + session.origin = 'app-connect' + session.reason = 'balance' + await show() + expect(main().textContent).toBe('Top up') + }) +}) diff --git a/forge-web/components/low-funds-banner.tsx b/forge-web/components/low-funds-banner.tsx index 7c9bc0b51..63206bdb1 100644 --- a/forge-web/components/low-funds-banner.tsx +++ b/forge-web/components/low-funds-banner.tsx @@ -3,9 +3,9 @@ /** * The low-balance banner (`ux-dx-spec.md` §4, low-balance states): when funds are low or empty, * one banner under the header with the specific fix — top up the identity, or renew this - * browser's key — dismissible once per state per session (sessionStorage). It shows at every - * width, so a phone, whose header only has room for the icon-sized funds cue, still says what is - * wrong and how to fix it. + * browser's key (in the wallet that granted it, when it came from one) — dismissible once per + * state per session (sessionStorage). It shows at every width, so a phone, whose header only has + * room for the icon-sized funds cue, still says what is wrong and how to fix it. */ import { useEffect, useState } from 'react' @@ -32,10 +32,10 @@ function readDismissed(identity: string): readonly string[] { } export function LowFundsBanner(): JSX.Element | null { - const { identity, funds } = useAuth() + const { identity, funds, origin } = useAuth() const openTopUp = useUiStore((s) => s.openTopUp) const openLogin = useUiStore((s) => s.openLogin) - const notice = funds ? fundsNotice(funds) : null + const notice = funds ? fundsNotice(funds, origin) : null // Read after mount (sessionStorage is browser-only), per identity; until then nothing shows, // so neither a flash nor another identity's dismissals. const [dismissed, setDismissed] = useState<{ identity: string; keys: readonly string[] } | null>(null) @@ -46,6 +46,8 @@ 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' const dismiss = (): void => { const keys = [...dismissed.keys, notice.key] try { @@ -72,9 +74,9 @@ export function LowFundsBanner(): JSX.Element | null { + ) : null} {canTopUpKey ? ( ) : null} - diff --git a/forge-web/contexts/auth-context.tsx b/forge-web/contexts/auth-context.tsx index eed3bd566..76a9d388d 100644 --- a/forge-web/contexts/auth-context.tsx +++ b/forge-web/contexts/auth-context.tsx @@ -68,6 +68,13 @@ interface AuthContextValue { readonly signer: WriteAuth | null /** How this session's key is held: a vault-stored limited key, or a tab-only raw key. */ readonly storage: AuthSession['storage'] | null + /** + * Where the stored key came from when this browser did not register it (`app-connect`: a + * wallet's grant, renewed in that wallet), else null. + */ + readonly origin: NonNullable | null + /** Check the session's keys on chain again (a write was refused as outside the key's bounds). */ + recheckSession: () => Promise /** Whether this network supports limited keys (forge-v2, protocol 14). */ readonly limitedKeys: boolean /** Keys stored (encrypted) on this device for this network. */ @@ -237,6 +244,9 @@ export function AuthProvider({ unlock: withReload(controller.unlock.bind(controller)), loginWithRawKey: withReload(controller.loginWithRawKey.bind(controller)), refreshBalance: () => controller.refreshBalance(), + recheckSession: async () => { + await controller.recheckSession() + }, logout: () => controller.logout(), forget: withReload(controller.forget.bind(controller)), revokeStored: withReload(controller.revokeStored.bind(controller)), @@ -324,6 +334,7 @@ export function AuthProvider({ error: state.error, signer, storage: session?.storage ?? null, + origin: session?.origin ?? null, grants: session?.grants ?? null, unlimitedKey: session?.unlimited === true, unboundedKey: session?.unbounded === true, @@ -369,6 +380,7 @@ export function SignedOutView({ children }: { children: React.ReactNode }): JSX. error: null, signer: null, storage: null, + origin: null, grants: null, unlimitedKey: false, unboundedKey: false, diff --git a/forge-web/e2e/wallet-login-v2.spec.ts b/forge-web/e2e/wallet-login-v2.spec.ts new file mode 100644 index 000000000..e9229d27c --- /dev/null +++ b/forge-web/e2e/wallet-login-v2.spec.ts @@ -0,0 +1,252 @@ +import { test, expect, devices, type Page } from '@playwright/test' +import { existsSync, readFileSync } from 'node:fs' +import { connect } from 'node:net' +import { resolve } from 'node:path' +import { deploymentFilePath } from './network' +import { E2E_DEVNET, E2E_NETWORK, PASSPHRASE, idFile, repoUrl, shot, unlock } from './helpers' +import { approveV2, disableGrants, newV2Wallet } from './wallet-responder-v2' + +/** + * Sign in with a mobile wallet that speaks App Connect v2, with a scripted wallet + * (e2e/wallet-responder-v2.ts) that does what such a wallet does with the code the page shows. + * + * Read-only (no secrets, no spend; needs the devnet's nodes to answer reads, and skips itself when + * none of them accepts a connection from this machine): + * + * E2E_DEVNET=sakura pnpm exec playwright test wallet-login-v2.spec.ts + * + * r1. Desktop: the wallet tile comes first; the request is v2 (`v=2`, one approval for all of + * Forge, with the budget and the date), the support note names App Connect v2, and "Show the + * older code" switches to the v1 request (`v=1`) and "Show the newer code" back. + * r2. Phone: "Open in DashPay (Dash Wallet)" is the v2 link (no callback on a local http build: + * `cb` needs the canonical https site), and the older code is one tap away. + * r3. `/connect/`, where a wallet returns: a malformed link goes home, a declined approval says + * so, a tab that shows a code answers the page (which then steps aside), and with no such + * tab the page sends the user back to the Forge tab where they started. + * + * Live (real spend on a devnet with the RELAY test identity; testnet has no forge-v2): + * + * E2E_DEVNET=sakura E2E_WRITE=1 pnpm exec playwright test wallet-login-v2.spec.ts + * + * w1. Scan → the wallet adds ONE group-bound key and publishes the response → the page shows the + * identity and the granted limits (no "no spending limit" warning) → passphrase → signed in. + * Settings shows no further approval to ask for. A star (a forge-community write) opens no + * grant sheet and lands. Renew in your wallet: protection first, then a new code; the wallet + * adds a new key and disables the old one in the same update; the page stores it and shows its + * id. + * + * Every key the scripted wallet adds is disabled at the end. + */ + +test.skip(E2E_NETWORK === 'testnet', 'testnet has no forge-v2 deployment, so no App Connect v2 request') + +/** A v2 request's URI: `n=d` on a devnet, `v=2`. */ +const V2_URI = /^dash-key:[1-9A-HJ-NP-Za-km-z]+\?n=d&v=2$/ +const V1_URI = /^dash-key:[1-9A-HJ-NP-Za-km-z]+\?n=d&v=1$/ +const REQUEST_HASH = 'ab'.repeat(20) + +/** Whether the first DAPI node of the devnet under test accepts a TCP connection (5 s). */ +async function devnetReachable(): Promise { + 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 + } +} + +/** The URI a QR on the page encodes (the Qr component prints it as its caption). */ +async function shownUri(page: Page, scheme = 'dash-key'): Promise { + const caption = page.locator('figcaption', { hasText: `${scheme}:` }).first() + await expect(caption).toBeVisible({ timeout: 60_000 }) + return (await caption.textContent())!.trim() +} + +async function openWalletRequest(page: Page): Promise { + await page.goto('/', { waitUntil: 'domcontentloaded' }) + await page.getByRole('banner').getByRole('button', { name: /^sign in$/i }).first().click() + const wallet = page.getByTestId('tile-wallet') + await expect(wallet).toBeVisible({ timeout: 60_000 }) + await wallet.click() +} + +test.describe('v2 request (read-only)', () => { + test.beforeAll(async () => { + test.skip(!(await devnetReachable()), 'the devnet nodes are not reachable from this machine (the request needs Platform reads)') + }) + + test('r1. desktop: the wallet tile is first, the request is v2, and the older code is one click away', async ({ browser }) => { + const page = await (await browser.newContext()).newPage() + await page.goto('/', { waitUntil: 'domcontentloaded' }) + 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'))) + 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) + + await page.getByTestId('tile-wallet').click() + await expect(page.getByTestId('request-countdown')).toContainText('Expires in') + expect(await shownUri(page)).toMatch(V2_URI) + await expect(page.getByTestId('approval-terms')).toContainText(/one approval covers all of forge, spending up to 0\.05 dash/i) + await expect(page.getByTestId('approval-terms')).toContainText(/until /) + await expect(page.getByTestId('wallet-support')).toContainText(/app connect v2/i) + await expect(page.getByTestId('wallet-deep-link')).toHaveCount(0) + await shot(page, 'wallet-login-v2-01-request') + + // The older code: today's v1 request, and a way back. + await page.getByTestId('older-code').click() + await expect(page.getByTestId('newer-code')).toBeVisible({ timeout: 60_000 }) + expect(await shownUri(page)).toMatch(V1_URI) + await expect(page.getByTestId('approval-terms')).toHaveCount(0) + await shot(page, 'wallet-login-v2-02-older-code') + await page.getByTestId('newer-code').click() + await expect(page.getByTestId('older-code')).toBeVisible({ timeout: 60_000 }) + expect(await shownUri(page)).toMatch(V2_URI) + }) + + test('r2. phone: "Open in DashPay (Dash Wallet)" is the v2 link, with the QR behind a disclosure', async ({ browser }) => { + const page = await (await browser.newContext({ ...devices['Pixel 7'] })).newPage() + await openWalletRequest(page) + const link = page.getByTestId('wallet-deep-link') + await expect(link).toBeVisible({ timeout: 60_000 }) + const href = (await link.getAttribute('href'))! + expect(href).toMatch(/^dash-key:[1-9A-HJ-NP-Za-km-z]+\?n=d&v=2/) + // `cb` needs the canonical https site: this local http build leaves it out (BroadcastChannel + // would not reach the tab either). + expect(href).not.toContain('cb=') + await expect(link).toHaveText(/open in dashpay \(dash wallet\)/i) + await expect(page.getByTestId('older-code')).toBeVisible() + await page.getByTestId('older-code').click() + await expect(page.getByTestId('newer-code')).toBeVisible({ timeout: 60_000 }) + expect(await link.getAttribute('href')).toMatch(V1_URI) + await shot(page, 'wallet-login-v2-03-phone') + }) +}) + +test.describe('/connect/ (the wallet returns here)', () => { + test('a malformed link goes home', async ({ page }) => { + await page.goto('/connect/?r=not-a-hash') + await expect(page).not.toHaveURL(/\/connect\//, { timeout: 30_000 }) + }) + + test('a declined approval says so', async ({ page }) => { + await page.goto(`/connect/?r=${REQUEST_HASH}&ac=declined`) + await expect(page.getByRole('heading', { name: 'Sign-in declined' })).toBeVisible({ timeout: 30_000 }) + await expect(page.getByRole('link', { name: 'Open Forge' })).toBeVisible() + }) + + test('the tab that shows the code answers, and this page steps aside', async ({ page, context }) => { + // Stand in for the waiting tab: ack the page's message the way the wallet flow does. + const waiting = await context.newPage() + await waiting.goto('/networks/', { waitUntil: 'domcontentloaded' }) + await waiting.evaluate((hash) => { + const channel = new BroadcastChannel('forge-app-connect') + // Kept reachable so the channel is not collected before the message arrives. + Object.assign(window, { forgeTestChannel: channel }) + channel.onmessage = (event: MessageEvent) => { + if ((event.data as { type?: string; requestHash?: string })?.type === 'forge-app-connect-callback' && (event.data as { requestHash?: string }).requestHash === hash) { + channel.postMessage({ type: 'forge-app-connect-ack', requestHash: hash }) + } + } + }, REQUEST_HASH) + await page.goto(`/connect/?r=${REQUEST_HASH}&ac=ok`) + await expect(page.getByRole('heading', { name: /you.re signing in on your other forge tab/i })).toBeVisible({ timeout: 30_000 }) + }) + + test('with no tab waiting, it sends the user back to the Forge tab where they started', async ({ page }) => { + await page.goto(`/connect/?r=${REQUEST_HASH}&ac=ok`) + await expect(page.getByRole('heading', { name: 'Go back to Forge' })).toBeVisible({ timeout: 30_000 }) + await expect(page.getByText(/forge tab where you started/i)).toBeVisible() + }) +}) + +test.describe('v2 sign-in and renewal (live, real spend)', () => { + test.skip(process.env['E2E_WRITE'] !== '1', 'live writes: set E2E_DEVNET=sakura E2E_WRITE=1') + test.skip(!existsSync(idFile('RELAY')), 'devnet test identities not found (RELAY)') + test.describe.configure({ mode: 'serial', timeout: 15 * 60_000 }) + + test('w1. scan, confirm, one key for all of Forge, a star with no grant sheet; renew in the wallet', async ({ browser }) => { + const relay = (JSON.parse(readFileSync(idFile('RELAY'), 'utf8')) as { identityId: string }).identityId + const wallet = newV2Wallet() + const page = await (await browser.newContext()).newPage() + let renewedKeyId: number | null = null + try { + await openWalletRequest(page) + const uri = await shownUri(page) + expect(uri).toMatch(V2_URI) + const first = await approveV2({ wallet, uri, identityFile: idFile('RELAY'), devnet: E2E_DEVNET }) + expect(first.label).toBe('Dash Forge') + expect(first.replacedKeyId).toBeNull() + + // Confirm: the identity and the limits the chain records; not the shipped wallets' warning. + await expect(page.getByTestId('granted-identity')).toHaveText(relay, { timeout: 120_000 }) + await expect(page.getByTestId('unlimited-key-warning')).toHaveCount(0) + await expect(page.getByTestId('approval-terms')).toContainText(/spending capped at 0\.05 dash/i) + await shot(page, 'wallet-login-v2-04-confirm') + await page.getByLabel(/this is my identity/i).check() + await page.getByLabel('Passphrase', { exact: true }).fill(PASSPHRASE) + await page.getByLabel('Repeat passphrase').fill(PASSPHRASE) + await page.getByRole('button', { name: /finish signing in/i }).click() + await expect(page.getByTestId('funds-pill')).toBeVisible({ timeout: 60_000 }) + + // One key covers every contract: nothing more to approve, and the key shows its limits. + await page.goto('/settings/', { waitUntil: 'domcontentloaded' }) + await unlock(page) + await expect(page.getByTestId('keys-panel')).toBeVisible({ timeout: 30_000 }) + await expect(page.getByTestId('grant-collab')).toHaveCount(0) + await expect(page.getByTestId('keys-panel').getByTestId('unlimited-key-warning')).toHaveCount(0) + await expect(page.getByTestId('key-id')).toHaveAttribute('data-key-id', String(first.keyId)) + await expect(page.getByTestId('key-budget')).toContainText('0.05') + await expect(page.getByTestId('key-renew-in-wallet')).toBeVisible() + await shot(page, 'wallet-login-v2-05-settings') + + // A star is a forge-community write: no grant sheet, and it lands. + await page.goto(repoUrl(), { waitUntil: 'domcontentloaded' }) + await unlock(page) + const star = page.getByRole('button', { name: /^star/i }) + await expect(star).toBeEnabled({ timeout: 60_000 }) + await star.click() + await expect(page.getByRole('dialog', { name: /approve stars, watches and follows/i })).toHaveCount(0) + await expect(page.getByRole('button', { name: /starred/i })).toBeVisible({ timeout: 90_000 }) + await page.getByRole('button', { name: /starred/i }).click() + await expect(page.getByRole('button', { name: /^star/i })).toBeVisible({ timeout: 90_000 }) + + // Renew in the wallet: the protection first, then the code; the wallet disables the old key. + await page.goto('/settings/', { waitUntil: 'domcontentloaded' }) + await unlock(page) + await page.getByTestId('key-renew-in-wallet').click() + await expect(page.getByTestId('wallet-renew-prepare')).toBeVisible({ timeout: 30_000 }) + await expect(page.locator('figcaption', { hasText: 'dash-key:' })).toHaveCount(0) + await page.getByLabel('Passphrase', { exact: true }).fill(PASSPHRASE) + await page.getByLabel('Repeat passphrase').fill(PASSPHRASE) + await page.getByRole('button', { name: /continue to your wallet/i }).click() + const renewUri = await shownUri(page) + expect(renewUri).toMatch(V2_URI) + expect(renewUri).not.toBe(uri) + await shot(page, 'wallet-login-v2-06-renew') + const second = await approveV2({ wallet, uri: renewUri, identityFile: idFile('RELAY'), devnet: E2E_DEVNET }) + expect(second.replacedKeyId).toBe(first.keyId) + renewedKeyId = second.keyId + await expect(page.getByRole('dialog')).toBeHidden({ timeout: 120_000 }) + await expect(page.getByTestId('key-id')).toHaveAttribute('data-key-id', String(second.keyId), { timeout: 60_000 }) + await shot(page, 'wallet-login-v2-07-renewed') + } finally { + // The first key is already disabled by the renewal: only the live one remains to disable. + const left = await disableGrants({ wallet, identityFile: idFile('RELAY'), devnet: E2E_DEVNET }) + if (renewedKeyId !== null) expect(left).toEqual([renewedKeyId]) + } + }) +}) diff --git a/forge-web/e2e/wallet-login.spec.ts b/forge-web/e2e/wallet-login.spec.ts index 20843b9eb..4b39c2b64 100644 --- a/forge-web/e2e/wallet-login.spec.ts +++ b/forge-web/e2e/wallet-login.spec.ts @@ -12,8 +12,14 @@ import { deploymentFilePath } from './network' * * E2E_DEVNET=sakura E2E_WRITE=1 pnpm exec playwright test wallet-login.spec.ts * - * m1. Desktop: on a devnet the wallet tile comes after Create, Import and dg, and the request says - * plainly that Dash Wallet answers on testnet only. The sheet shows a dash-key QR (its text is + * This is the OLDER wallet protocol (v1, the legacy key exchange). Where App Connect v2 is on offer + * (a devnet with protocol 14, as here) the sheet shows the v2 request first and the wallet tile + * comes first: this spec takes "Show the older code" to reach v1 (wallet-login-v2.spec.ts + * covers v2). + * + * m1. Desktop: the wallet tile is first where v2 is on offer (testnet: it is first too, as Dash + * Wallet answers there; no v2 yet). After "Show the older code" the request says plainly that + * Dash Wallet answers on testnet only. The sheet shows a dash-key QR (its text is * in the caption) and a countdown, and no deep link. The wallet approves (legacy key-exchange contract); the page shows QR #2 * (dash-st); the wallet registers the key; the page shows the identity, the "no spending * limit" warning and asks for a passkey; the user confirms and signs in with a passphrase; @@ -34,10 +40,10 @@ const ROOT = resolve(__dirname, '../..') /** The wallet-login QR's URI: `n=t` on testnet, `n=d` on a devnet. */ const KEY_URI = new RegExp(`^dash-key:[1-9A-HJ-NP-Za-km-z]+\\?n=${E2E_NETWORK === 'testnet' ? 't' : 'd'}&v=1$`) /** - * The sign-in tiles in order. Dash Wallet answers on testnet only, so there its tile comes first; - * on a devnet it comes last, after the dg tile. + * The sign-in tiles in order: the wallet tile comes first where a wallet can answer: on testnet + * (Dash Wallet answers the older code there) and on a devnet with App Connect v2 on offer. */ -const TILE_ORDER = E2E_NETWORK === 'testnet' ? ['tile-wallet', 'tile-create', 'tile-import', 'tile-dg'] : ['tile-create', 'tile-import', 'tile-dg', 'tile-wallet'] +const TILE_ORDER = ['tile-wallet', 'tile-create', 'tile-import', 'tile-dg'] const CHAIN_KEY = randomBytes(32).toString('hex') type Responder = typeof import('./wallet-responder.mjs') const responder = (): Promise => import(pathToFileURL(join(__dirname, 'wallet-responder.mjs')).href) @@ -74,11 +80,16 @@ test('m1. desktop: scan, register, confirm, sign in; then the one-tap grant for await page.getByRole('button', { name: /^sign in$/i }).first().click() const wallet = page.getByTestId('tile-wallet') await expect(wallet).toBeVisible({ timeout: 60_000 }) - // Not the first option on a devnet: no released wallet answers here (the dg tile sits before it). - const order = await page.locator('[data-testid^="tile-"]').evaluateAll((els) => els.map((e) => e.getAttribute('data-testid'))) + // The buttons only: a cost line between the tiles shares the testid prefix. + const order = await page.locator('button[data-testid^="tile-"]').evaluateAll((els) => els.map((e) => e.getAttribute('data-testid'))) expect(order.slice(0, TILE_ORDER.length)).toEqual(TILE_ORDER) - if (E2E_NETWORK !== 'testnet') await expect(wallet).toContainText(/testnet/i) await wallet.click() + // On a devnet the v2 request shows first: take the older code (v1), the subject of this spec. + if (E2E_NETWORK !== 'testnet') { + await page.getByTestId('older-code').click({ timeout: 60_000 }) + // The v1 request is built after a few reads: wait for its link back to the newer code. + await expect(page.getByTestId('newer-code')).toBeVisible({ timeout: 60_000 }) + } await expect(page.getByTestId('request-countdown')).toContainText('Expires in') await expect(page.getByTestId('wallet-support')).toContainText(E2E_NETWORK === 'testnet' ? /testnet development build/i : /works on testnet only/i) await expect(page.getByTestId('wallet-deep-link')).toHaveCount(0) @@ -131,6 +142,11 @@ test('m2. phone: "Open in DashPay (Dash Wallet)" instead of a QR', async ({ brow await page.goto('/', { waitUntil: 'domcontentloaded' }) await page.getByRole('button', { name: /^sign in$/i }).first().click() await page.getByTestId('tile-wallet').click({ timeout: 60_000 }) + if (E2E_NETWORK !== 'testnet') { + await page.getByTestId('older-code').click({ timeout: 60_000 }) + // The v1 request is built after a few reads: until then the v2 link would still be on screen. + await expect(page.getByTestId('newer-code')).toBeVisible({ timeout: 60_000 }) + } const link = page.getByTestId('wallet-deep-link') await expect(link).toBeVisible({ timeout: 60_000 }) expect(await link.getAttribute('href')).toMatch(KEY_URI) diff --git a/forge-web/e2e/wallet-responder-v2.ts b/forge-web/e2e/wallet-responder-v2.ts new file mode 100644 index 000000000..9a4ca0d31 --- /dev/null +++ b/forge-web/e2e/wallet-responder-v2.ts @@ -0,0 +1,212 @@ +// copy-lint-ignore-file: a test helper no user reads +/** + * A scripted App Connect v2 wallet for the wallet-login e2e and the live test: what a wallet that + * speaks `APP_CONNECT_PROFILE.md` does with the `dash-key:...&v=2` request Forge shows, done with a + * devnet test identity's own keys in Node. Like a real wallet it never signs the app's transitions: + * it parses the request, checks it, and rebuilds the identity update from its own state. + * + * approveV2({ wallet, uri, identityFile, devnet }) + * 1. parse and check the request (the wallet rules: freshness, one contractGroup binding of + * the Forge group at HIGH with a budget, no encryption binding); + * 2. in ONE identity update signed by the master key: add a fresh key bound to the group with + * the requested budget and expiry (or the `limits` given), and disable the key of this + * wallet's previous grant for the same (identity, connection id); + * 3. publish the `loginKeyResponse` in the App Connect contract under the identity, sealed to + * the request's ephemeral key (`answerV2`, the vendored module's own sealing). + * disableGrants({ wallet, identityFile, devnet }) + * cleanup: disable every key this wallet added that is still live. + * + * The wallet's memory of its grants is the `wallet` object (an identity-and-connection map to key + * ids): the chain does not record connection ids. It reuses `connect()` of wallet-responder.mjs. + * It broadcasts: run only against a devnet with a test identity of your own. + */ + +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import * as secp from '@noble/secp256k1' +import { bytesToHex } from '@noble/hashes/utils.js' + +import { APP_CONNECT_CONTRACT_ID } from '../lib/auth/app-connect' +import { base58Encode } from '../lib/auth/base58' +import { answerV2 } from '../lib/auth/wallet-sim' +import { + KeySecurityLevel, + checkAppConnectRequestAge, + parseAppConnectUri, + type AppConnectRequest, +} from '../lib/vendor/platform-auth/app-connect' + +type Responder = typeof import('./wallet-responder.mjs') +const responder = (): Promise => import(pathToFileURL(join(__dirname, 'wallet-responder.mjs')).href) + +/** The grants one scripted wallet has made, so a renewal can disable the key it replaces. */ +export interface V2Wallet { + /** `:` → the live key id of that grant. */ + readonly grants: Map + /** Every key id this wallet added, per identity (for cleanup). */ + readonly added: Map +} + +export function newV2Wallet(): V2Wallet { + return { grants: new Map(), added: new Map() } +} + +/** Why this wallet would refuse a request (the profile's `ac` statuses), or null when it accepts. */ +export function v2RequestRefusal( + req: AppConnectRequest, + p: { readonly now: number; readonly groupId: string; readonly expectLabel?: string }, +): { readonly status: 'stale' | 'unsupported' | 'invalid'; readonly why: string } | null { + const age = checkAppConnectRequestAge(req.createdAt, p.now) + if (age !== null) return { status: 'stale', why: `request is ${age}` } + if (req.mode !== undefined) return { status: 'unsupported', why: `unknown mode ${req.mode}` } + if (req.authBindings.length !== 1) return { status: 'invalid', why: `${req.authBindings.length} auth bindings, Forge asks for one` } + if (req.encBindings.length !== 0) return { status: 'invalid', why: 'an encryption binding: no Forge contract allows wallet-issued encryption keys' } + const [binding] = req.authBindings + if (binding === undefined) return { status: 'invalid', why: 'no auth binding' } + if (binding.kind !== 'contractGroup') return { status: 'invalid', why: `binding kind ${binding.kind}` } + if (base58Encode(binding.id) !== p.groupId) return { status: 'invalid', why: 'not the Forge contract group' } + if (binding.securityLevel !== KeySecurityLevel.HIGH) return { status: 'invalid', why: 'a contractGroup key other than HIGH' } + // Wallet rule 5: a contractGroup key always has a budget (and an expiry). + if (binding.totalBudget === undefined || binding.totalBudget <= 0n) return { status: 'invalid', why: 'no budget' } + if (binding.expiresAt === undefined || binding.expiresAt <= p.now) return { status: 'invalid', why: 'no usable expiry' } + if (p.expectLabel !== undefined && req.label !== p.expectLabel) return { status: 'invalid', why: `label ${JSON.stringify(req.label)}` } + return null +} + +export interface ApprovedV2 { + readonly identityId: string + /** The key this approval added. */ + readonly keyId: number + /** The key of this wallet's previous grant for the same connection id that the update disabled. */ + readonly replacedKeyId: number | null + readonly requestHash: string + readonly label: string + /** What the key was granted with. */ + readonly granted: { readonly budget: bigint; readonly expiresAt: number } +} + +/** A key as the identity files (`~/.config/dash-forge/test-identities`) record it. */ +interface IdentityFileKey { + readonly id: number + readonly purpose: string + readonly securityLevel: string + readonly keyType: string + readonly publicKeyHex: string + readonly privateKeyWif: string +} + +const grantKey = (identityId: string, connectionId: Uint8Array | undefined): string => `${identityId}:${connectionId ? bytesToHex(connectionId) : 'none'}` + +/** + * Approve `uri`. `limits` grants other limits than the request proposed (a wallet clamps to its + * presets: 0.1 DASH and up); by default the proposal is granted as asked. + */ +export async function approveV2(p: { + readonly wallet: V2Wallet + readonly uri: string + readonly identityFile: string + /** The devnet's name (`E2E_DEVNET`), or '' on testnet. */ + readonly devnet: string + readonly limits?: { readonly budget?: bigint; readonly expiresAt?: number } + readonly now?: () => number +}): Promise { + const wallet = await responder() + const { evo, sdk, dep } = await wallet.connect(p.devnet) + const groupId = String(dep.v2.contractGroupId) + const rec = JSON.parse(readFileSync(p.identityFile, 'utf8')) as { identityId: string; identityKeys: IdentityFileKey[] } + const identityId = rec.identityId + + // The parsing and sealing are the vendored module's own: parse once to check, answer from the same URI. + const parsed = parseAppConnectUri(p.uri) + const req = parsed.request + const refusal = v2RequestRefusal(req, { now: (p.now ?? Date.now)(), groupId }) + if (refusal !== null) throw new Error(`the scripted wallet refuses this request (${refusal.status}): ${refusal.why}`) + const binding = req.authBindings[0]! + const budget = p.limits?.budget ?? binding.totalBudget! + const expiresAt = p.limits?.expiresAt ?? binding.expiresAt! + + const identity = await sdk.identities.fetch(identityId) + const next = Math.max(...identity.publicKeys.map((k: { keyId: number }) => k.keyId)) + 1 + const priv = secp.utils.randomSecretKey() + const fresh = evo.PrivateKey.fromBytes(priv, 'testnet') + const master = rec.identityKeys.find((x) => x.securityLevel === 'MASTER') + if (!master) throw new Error('the identity file has no master key') + const signer = new evo.IdentitySigner() + signer.addKey(evo.PrivateKey.fromWIF(master.privateKeyWif)) + signer.addKey(fresh) + + // The previous grant for this (identity, connection id), if the chain still shows it live. + const slot = grantKey(identityId, req.connectionId) + const previous = p.wallet.grants.get(slot) ?? null + const live = previous !== null && identity.publicKeys.some((k: { keyId: number; disabledAt?: unknown }) => k.keyId === previous && k.disabledAt === undefined) + const key = new evo.IdentityPublicKeyInCreation({ + keyId: next, + purpose: 'authentication', + securityLevel: 'high', + keyType: 'ecdsa_secp256k1', + data: fresh.getPublicKey().toBytes(), + contractBounds: evo.ContractBounds.ContractGroup(groupId), + totalBudget: budget, + expiresAt: BigInt(expiresAt), + }) + // One master-signed update: the new key in, the previous grant's key out. + await sdk.identities.update({ identity, addPublicKeys: [key], ...(live ? { disablePublicKeys: [previous] } : {}), signer }) + p.wallet.grants.set(slot, next) + p.wallet.added.set(identityId, [...(p.wallet.added.get(identityId) ?? []), next]) + + // Publish the response under the identity, sealed to the request's ephemeral key. + const answer = await answerV2(p.uri, { ownerId: identityId, slots: [priv] }) + // The identity's own HIGH authentication key signs the document, built from the identity file as wallet-responder.mjs does. + const high = rec.identityKeys.find((x) => x.securityLevel === 'HIGH' && x.purpose === 'AUTHENTICATION') + if (!high) throw new Error('the identity file has no HIGH authentication key') + const identityKey = new evo.IdentityPublicKey({ + keyId: high.id, + purpose: high.purpose, + securityLevel: high.securityLevel, + keyType: high.keyType, + isReadOnly: false, + data: Buffer.from(high.publicKeyHex, 'hex'), + }) + const publisher = new evo.IdentitySigner() + publisher.addKey(evo.PrivateKey.fromWIF(high.privateKeyWif)) + const base = new evo.Document({ properties: {}, documentTypeName: 'loginKeyResponse', dataContractId: APP_CONNECT_CONTRACT_ID, ownerId: identityId }) + const document = evo.Document.fromObject( + { + ...base.toObject(), + appEphemeralPubKeyHash: answer.requestHash, + walletEphemeralPubKey: answer.walletEphemeralPubKey, + encryptedPayload: answer.encryptedPayload, + }, + sdk.version(), + ) + await sdk.documents.create({ document, identityKey, signer: publisher }) + priv.fill(0) + + return { + identityId, + keyId: next, + replacedKeyId: live ? previous : null, + requestHash: bytesToHex(answer.requestHash), + label: req.label, + granted: { budget, expiresAt }, + } +} + +/** Cleanup: disable every key this wallet added that is still live on `identityFile`'s identity. */ +export async function disableGrants(p: { readonly wallet: V2Wallet; readonly identityFile: string; readonly devnet: string }): Promise { + const wallet = await responder() + const { evo, sdk } = await wallet.connect(p.devnet) + const rec = JSON.parse(readFileSync(p.identityFile, 'utf8')) as { identityId: string; identityKeys: IdentityFileKey[] } + const mine = new Set(p.wallet.added.get(rec.identityId) ?? []) + if (mine.size === 0) return [] + const identity = await sdk.identities.fetch(rec.identityId) + const ids = identity.publicKeys.filter((k: { keyId: number; disabledAt?: unknown }) => mine.has(k.keyId) && k.disabledAt === undefined).map((k: { keyId: number }) => k.keyId) + if (ids.length === 0) return [] + const master = rec.identityKeys.find((x) => x.securityLevel === 'MASTER') + if (!master) throw new Error('the identity file has no master key') + const signer = new evo.IdentitySigner() + signer.addKey(evo.PrivateKey.fromWIF(master.privateKeyWif)) + await sdk.identities.update({ identity, disablePublicKeys: ids, signer }) + return ids +} diff --git a/forge-web/e2e/wallet-responder.mjs b/forge-web/e2e/wallet-responder.mjs index d985dad3d..79af171e1 100644 --- a/forge-web/e2e/wallet-responder.mjs +++ b/forge-web/e2e/wallet-responder.mjs @@ -88,7 +88,8 @@ function derived(login, identityId) { } // `devnet` is the devnet's name, or '' on testnet (the e2e convention: network.ts E2E_DEVNET). -async function connect(devnet) { +// Exported for the App Connect v2 responder (wallet-responder-v2.ts), which talks to the same chain. +export async function connect(devnet) { const evo = await import(node('@dashevo/evo-sdk/dist/evo-sdk.module.js')) const testnet = devnet === '' const dep = JSON.parse(readFileSync(join(ROOT, `forge-contracts/deployments/${testnet ? 'testnet' : `devnet-${devnet}`}.json`), 'utf8')) diff --git a/forge-web/hooks/use-ui-store.ts b/forge-web/hooks/use-ui-store.ts index bbd7af6dc..94f8b3b33 100644 --- a/forge-web/hooks/use-ui-store.ts +++ b/forge-web/hooks/use-ui-store.ts @@ -15,10 +15,11 @@ export type { TopUpReason } /** * A sign-in sheet view to open on directly (`renew`: Settings → Renew key, the import form worded - * as a renewal of the signed-in identity's key, QW3-031; `grant` asks the signed-in identity's - * wallet for a key on the contract named with it, when the session lacks one). + * as a renewal of the signed-in identity's key, QW3-031; `wallet-renew` renews it in the wallet + * that granted it (App Connect); `grant` asks the signed-in identity's wallet for a key on the + * contract named with it, when the session lacks one). */ -export type LoginView = 'import' | 'renew' | 'create' | 'wallet' | 'grant' | 'unlock' | 'dg' +export type LoginView = 'import' | 'renew' | 'wallet-renew' | 'create' | 'wallet' | 'grant' | 'unlock' | 'dg' /** * What a signed-out click asked to do (L-62): the sheet says "Sign in to star this repo" and what diff --git a/forge-web/hooks/use-write-guard.test.tsx b/forge-web/hooks/use-write-guard.test.tsx index 297628507..143d22be3 100644 --- a/forge-web/hooks/use-write-guard.test.tsx +++ b/forge-web/hooks/use-write-guard.test.tsx @@ -8,14 +8,16 @@ import { act } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -const state = vi.hoisted(() => ({ paused: null as string | null })) +const state = vi.hoisted(() => ({ paused: null as string | null, origin: null as 'app-connect' | null })) const toast = vi.hoisted(() => vi.fn()) const openLogin = vi.hoisted(() => vi.fn()) +const openTopUp = vi.hoisted(() => vi.fn()) +const recheckSession = vi.hoisted(() => vi.fn()) vi.mock('@/lib/devnet-notice', () => ({ writesPausedReason: () => state.paused })) vi.mock('@/hooks/use-toasts', () => ({ toast })) vi.mock('@/hooks/use-ui-store', () => ({ - useUiStore: (select: (s: unknown) => unknown) => select({ openLogin, openTopUp: vi.fn() }), + useUiStore: (select: (s: unknown) => unknown) => select({ openLogin, openTopUp }), })) vi.mock('@/contexts/auth-context', () => ({ useAuth: () => ({ @@ -25,13 +27,16 @@ vi.mock('@/contexts/auth-context', () => ({ funds: null, keyLimits: null, grants: null, - refreshBalance: vi.fn(), + refreshBalance: vi.fn(async () => undefined), + recheckSession, + origin: state.origin, resuming: false, unlockScope: null, }), })) vi.mock('@/lib/view/funds', () => ({ affordability: () => ({ ok: true }) })) +import { ConsensusRefusal } from '@/lib/sdk/write' import { useWriteGuard, type WriteGuard } from './use-write-guard' let root: Root @@ -45,6 +50,9 @@ function Probe(): null { beforeEach(() => { ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true state.paused = null + state.origin = null + openTopUp.mockClear() + recheckSession.mockReset().mockResolvedValue(undefined) toast.mockClear() openLogin.mockClear() el = document.createElement('div') @@ -72,3 +80,30 @@ describe('useWriteGuard while the devnet is moving', () => { expect(guard.disabledReason).toBe(state.paused) }) }) + +describe('useWriteGuard after a write fails on a wallet-granted key', () => { + const refusal = (code: number) => new ConsensusRefusal(code, `refused ${code}`, {}, false) + + it("reads the refusal as App Connect does: a revoked key opens the renew sheet with the wallet's words", () => { + state.origin = 'app-connect' + act(() => root.render()) + expect(guard.failed(refusal(20006))).toMatch(/^Your wallet revoked this browser's access/) + expect(openTopUp).toHaveBeenCalledWith({ blocker: 'key-disabled' }) + expect(recheckSession).not.toHaveBeenCalled() + }) + + it('checks the session again after a write outside the key\'s bounds (20014), and survives a failed read', async () => { + state.origin = 'app-connect' + recheckSession.mockRejectedValue(new Error('offline')) + act(() => root.render()) + guard.failed(refusal(20014)) + await Promise.resolve() + expect(recheckSession).toHaveBeenCalledTimes(1) + }) + + it('leaves any other key as it was', () => { + guard.failed(refusal(20014)) + expect(guard.failed(refusal(20006))).not.toMatch(/wallet revoked/) + expect(recheckSession).not.toHaveBeenCalled() + }) +}) diff --git a/forge-web/hooks/use-write-guard.ts b/forge-web/hooks/use-write-guard.ts index 3c8bc1a79..7a3d42374 100644 --- a/forge-web/hooks/use-write-guard.ts +++ b/forge-web/hooks/use-write-guard.ts @@ -13,6 +13,8 @@ * - after a failure ({@link WriteGuard.failed}): the fix Platform's answer calls for opens — * renew or top up the key, top up the balance — and the balance and key limits are read * again so the pill shows what the chain says (D-007, D-042). It returns the sentence to show. + * For a key a wallet granted through App Connect, a write refused as outside the key's bounds + * also has the session's keys checked on chain again. */ import { useCallback } from 'react' @@ -48,7 +50,7 @@ const EMPTY_REASON: Readonly s.openLogin) const openTopUp = useUiStore((s) => s.openTopUp) @@ -98,14 +100,18 @@ export function useWriteGuard(): WriteGuard { const failed = useCallback( (e: unknown): string => { - const { message, sheet } = writeFailure(e) + // A key a wallet granted reads its refusals as App Connect does (revoked, out of bounds). + const { message, sheet, recheck } = writeFailure(e, { appConnect: origin === 'app-connect' }) if (sheet !== null) { openTopUp(sheet) void refreshBalance().catch(() => undefined) } + // Refused as outside the key's bounds: read its scopes, limits and balance afresh. A read + // that fails keeps the session as it was. + if (recheck) void recheckSession().catch(() => undefined) return message }, - [openTopUp, refreshBalance], + [openTopUp, origin, recheckSession, refreshBalance], ) const disabledReason = writesPausedReason() ?? (funds?.level === 'empty' ? EMPTY_REASON[funds.reason ?? 'balance'] : null) diff --git a/forge-web/lib/auth/app-connect-port.test.ts b/forge-web/lib/auth/app-connect-port.test.ts new file mode 100644 index 000000000..c1e4e7ca7 --- /dev/null +++ b/forge-web/lib/auth/app-connect-port.test.ts @@ -0,0 +1,141 @@ +/** + * The App Connect ports over fake wasm objects: how a key is read (and when it is dropped rather + * than misread), answers sorted by owner whatever order the SDK hands them back in, and the + * chain clock. + */ + +import type { EvoSDK } from '@dashevo/evo-sdk' +import { describe, expect, it } from 'vitest' + +import type { WasmKey } from '../sdk/facade' +import { APP_CONNECT_CONTRACT_ID } from './app-connect' +import { appConnectPort, candidateOf, compareIds, toAppConnectKey, toAppConnectKeys } from './app-connect-port' +import { base58Encode } from './base58' + +const GROUP = '6dV3kMBWHGR7pLKrHToMBQgbTpjqeE2VAyCEWmLbrkWC' +const CONTRACT = 'A2KL77ngVM1ft1t1em2XKt1rWCBZANdAJMyfWrDGCcd1' + +function wasmKey(over: Partial & { bounds?: unknown } = {}): WasmKey { + const { bounds, ...rest } = over + return { + keyId: 3, + keyTypeNumber: 0, + data: '02' + 'ab'.repeat(32), + purposeNumber: 0, + securityLevelNumber: 2, + ...(bounds !== undefined ? { contractBounds: { toJSON: () => bounds as { $type: string; id: string } } } : {}), + validatePrivateKey: () => false, + ...rest, + } +} + +describe('reading keys for the verifier', () => { + it('maps a group-bound V1 key with its limits', () => { + const k = toAppConnectKey(wasmKey({ bounds: { $type: 'contractGroup', id: GROUP }, totalBudget: 5n, expiresAt: 1_800_000_000_000n, disabledAt: 1_700_000_000_000n })) + expect(k).toEqual({ + id: 3, + type: 0, + purpose: 0, + securityLevel: 2, + data: new Uint8Array([2, ...new Array(32).fill(0xab)]), + bounds: { kind: 'contractGroup', groupId: GROUP }, + totalBudget: 5n, + expiresAt: 1_800_000_000_000, + disabledAt: 1_700_000_000_000, + }) + }) + + it('maps every bounds kind, and an unbound key as unbound', () => { + expect(toAppConnectKey(wasmKey({ bounds: { $type: 'singleContract', id: CONTRACT } }))?.bounds).toEqual({ kind: 'singleContract', contractId: CONTRACT }) + expect(toAppConnectKey(wasmKey({ bounds: { $type: 'documentType', id: CONTRACT, documentTypeName: 'profile' } }))?.bounds).toEqual({ + kind: 'documentType', + contractId: CONTRACT, + documentTypeName: 'profile', + }) + const unbound = toAppConnectKey(wasmKey()) + expect(unbound).not.toBeNull() + expect(unbound?.bounds).toBeUndefined() + }) + + it('drops a key it cannot read faithfully: an unreadable bound never looks unbound', () => { + const unreadable = [ + wasmKey({ bounds: { $type: 'someFutureKind', id: GROUP } }), + wasmKey({ bounds: { $type: 'documentType', id: CONTRACT } }), + wasmKey({ bounds: { $type: 'contractGroup' } }), + wasmKey({ keyTypeNumber: undefined }), + wasmKey({ data: 'not hex' }), + wasmKey({ data: undefined }), + { ...wasmKey(), contractBounds: { toJSON: () => { throw new Error('freed') } } }, + ] + for (const k of unreadable) expect(toAppConnectKey(k)).toBeNull() + expect(toAppConnectKeys([...unreadable, wasmKey({ keyId: 9 })]).map((k) => k.id)).toEqual([9]) + }) +}) + +describe('reading answers', () => { + const ids = [new Uint8Array(32).fill(9), new Uint8Array(32).fill(1), new Uint8Array(32).fill(200)].map(base58Encode) + + it('orders owners by bytes, as Platform does (not as strings)', () => { + // As strings '2…' < 'E…' < 'm…'; as bytes 0x01 < 0x09 < 0xc8. + const sorted = [...ids].sort(compareIds) + expect(sorted).toEqual([ids[1], ids[0], ids[2]]) + }) + + it('pages the App Connect contract by request and owner, sorted by owner whatever the SDK order', async () => { + const queries: unknown[] = [] + const sdk = { + documents: { + async query(q: unknown) { + queries.push(q) + return new Map(ids.map((id, i) => [String(i), { toJSON: () => ({ $ownerId: id, walletEphemeralPubKey: btoa('\x02'.repeat(33)), encryptedPayload: btoa('x'.repeat(60)) }) }])) + }, + }, + } as unknown as EvoSDK + const port = appConnectPort(sdk) + const hash = new Uint8Array(20).fill(5) + const got = await port.listCandidates(hash, undefined, ids[1], 10) + expect(got.map((c) => c.ownerId)).toEqual([ids[1], ids[0], ids[2]]) + expect(got[0]!.encryptedPayload.length).toBe(60) + expect(queries[0]).toMatchObject({ + dataContractId: APP_CONNECT_CONTRACT_ID, + documentTypeName: 'loginKeyResponse', + where: [ + ['appEphemeralPubKeyHash', '==', btoa(String.fromCharCode(...hash))], + ['$ownerId', '>', ids[1]], + ], + limit: 10, + }) + await port.listCandidates(hash, ids[2], undefined, 10) + expect((queries[1] as { where: unknown[] }).where[1]).toEqual(['$ownerId', '==', ids[2]]) + }) + + it('keeps an answer whose bytes do not read (the verifier refuses it), and fails a row without an owner', () => { + const c = candidateOf({ $ownerId: ids[0], walletEphemeralPubKey: 42, encryptedPayload: '%%%' }) + expect(c.walletEphemeralPubKey.length).toBe(0) + expect(c.encryptedPayload.length).toBe(0) + expect(() => candidateOf({ walletEphemeralPubKey: '', encryptedPayload: '' })).toThrow(/no readable owner/) + expect(() => candidateOf({ $ownerId: 'X', walletEphemeralPubKey: '', encryptedPayload: '' })).toThrow(/no readable owner/) + }) +}) + +describe('the other reads', () => { + it('reads remaining budgets, contract keys and the chain clock', async () => { + const sdk = { + identities: { + fetch: async () => ({ publicKeys: [wasmKey({ keyId: 4 }), wasmKey({ keyId: 5, keyTypeNumber: undefined })] }), + keysRemainingBudgets: async () => new Map([[4, 7n], [5, null]]), + contractKeys: async () => [ + { identityId: { toBase58: () => 'someone else' }, keys: [wasmKey({ keyId: 1 })] }, + { identityId: { toBase58: () => 'me' }, keys: [wasmKey({ keyId: 2 })] }, + ], + }, + protocol: { versionUpgradeStateWithProof: async () => ({ metadata: { protocolVersion: 14, timeMs: 1_800_000_000_000n } }) }, + } as unknown as EvoSDK + const port = appConnectPort(sdk) + expect((await port.getIdentityFresh('me'))?.publicKeys.map((k) => k.id)).toEqual([4]) + expect(await port.remainingBudgets('me', [4, 5])).toEqual(new Map([[4, 7n], [5, undefined]])) + expect((await port.contractKeys('me', CONTRACT, 1)).map((k) => k.id)).toEqual([2]) + expect(await port.groupInfo(GROUP)).toBeNull() + expect(await port.chainClock()).toEqual({ protocolVersion: 14, timeMs: 1_800_000_000_000 }) + }) +}) diff --git a/forge-web/lib/auth/app-connect-port.ts b/forge-web/lib/auth/app-connect-port.ts new file mode 100644 index 000000000..eac0459b6 --- /dev/null +++ b/forge-web/lib/auth/app-connect-port.ts @@ -0,0 +1,195 @@ +/** + * App Connect v2's chain reads (the vendored verifier's and poller's ports, + * `lib/vendor/platform-auth/app-connect`) over Forge's SDK connection, plus the chain clock the + * request and the verifier use (`docs/design/wallet-login.md`, App Connect v2). + * + * Every read is a proved SDK read, and identity reads go to the network directly (the SDK keeps + * no identity cache): a key a wallet added moments ago is exactly what the verifier checks. + * Forge binds no contract group by request member list (its group trust is `./group-trust`), so + * `groupInfo` has nothing to read; the verifier never calls it. + */ + +import { hexToBytes } from '@noble/hashes/utils.js' +import type { EvoSDK } from '@dashevo/evo-sdk' + +import { authSdk, type WasmKey } from '../sdk/facade' +import { base64ToBytes, bytesToBase64 } from '../sdk/query' +import type { + AppConnectCandidate, + AppConnectIdentityKey, + AppConnectIdentityPort, + AppConnectKeyBounds, + AppConnectResponsePort, +} from '../vendor/platform-auth/app-connect' +import { APP_CONNECT_CONTRACT_ID } from './app-connect' +import { base58Decode, decodeIdentifier } from './base58' + +/** The latest block's time and protocol version, from a proved response's metadata. */ +export interface ChainClock { + readonly protocolVersion: number + readonly timeMs: number +} + +export interface AppConnectPort extends AppConnectIdentityPort, AppConnectResponsePort { + chainClock(): Promise +} + +/** Bytes from a key's data as the SDK hands it back: hex (the wasm getter) or bytes. */ +function keyData(value: unknown): Uint8Array | null { + if (value instanceof Uint8Array) return value + return typeof value === 'string' && /^(?:[0-9a-f]{2})+$/i.test(value) ? hexToBytes(value) : null +} + +/** A key's bounds; undefined when it has none, null when they cannot be read. */ +function keyBounds(k: Pick): AppConnectKeyBounds | 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 + switch (json.$type) { + case 'singleContract': + return { kind: 'singleContract', contractId: json.id } + case 'documentType': + return typeof json.documentTypeName === 'string' ? { kind: 'documentType', contractId: json.id, documentTypeName: json.documentTypeName } : null + case 'contractGroup': + return { kind: 'contractGroup', groupId: json.id } + default: + return null + } +} + +/** + * A wasm key in the verifier's shape (ported from EvoVote `keyMapping.ts`), or null when it + * cannot be read faithfully (no key type, undecodable data, unknown bounds). The caller drops a + * null key: an unreadable bound must never look unbound, so such a key can neither verify nor + * be matched. + */ +export function toAppConnectKey(k: WasmKey): AppConnectIdentityKey | null { + const data = keyData(k.data) + const bounds = keyBounds(k) + if (k.keyTypeNumber === undefined || data === null || bounds === null) return null + return { + id: k.keyId, + type: k.keyTypeNumber, + purpose: k.purposeNumber, + securityLevel: k.securityLevelNumber, + data, + ...(k.disabledAt !== undefined ? { disabledAt: Number(k.disabledAt) } : {}), + ...(bounds !== undefined ? { bounds } : {}), + ...(k.totalBudget !== undefined ? { totalBudget: k.totalBudget } : {}), + ...(k.expiresAt !== undefined ? { expiresAt: Number(k.expiresAt) } : {}), + } +} + +/** Every key mapped, the unreadable ones dropped. */ +export function toAppConnectKeys(keys: readonly WasmKey[]): AppConnectIdentityKey[] { + return keys.flatMap((k) => { + const mapped = toAppConnectKey(k) + return mapped ? [mapped] : [] + }) +} + +/** Byte order of two base58 ids, as Platform orders `$ownerId`. */ +export function compareIds(a: string, b: string): number { + const left = base58Decode(a) + const right = base58Decode(b) + for (let i = 0; i < Math.min(left.length, right.length); i++) { + const d = (left[i] ?? 0) - (right[i] ?? 0) + if (d !== 0) return d + } + return left.length - right.length +} + +interface ResponseJson { + $ownerId?: unknown + walletEphemeralPubKey?: unknown + encryptedPayload?: unknown +} + +function bytesOr(value: unknown): Uint8Array { + if (typeof value !== 'string') return new Uint8Array(0) + try { + return base64ToBytes(value) + } catch { + return new Uint8Array(0) + } +} + +/** + * A `loginKeyResponse` row as a candidate. A row whose bytes do not read is still returned, with + * empty bytes (the verifier refuses it as `framing`): dropping it would shorten the page, and + * the poller takes a short page for the last one. A row without a readable owner (only a node + * that lies can return one) is a read Forge cannot use: it throws, so the round counts as + * incomplete rather than as one more identity answering. + */ +export function candidateOf(json: ResponseJson): AppConnectCandidate { + if (typeof json.$ownerId !== 'string' || !isIdentifier(json.$ownerId)) throw new Error('an App Connect answer has no readable owner') + return { ownerId: json.$ownerId, walletEphemeralPubKey: bytesOr(json.walletEphemeralPubKey), encryptedPayload: bytesOr(json.encryptedPayload) } +} + +function isIdentifier(id: string): boolean { + try { + decodeIdentifier(id) + return true + } catch { + return false + } +} + +/** The App Connect ports over `sdk`. */ +export function appConnectPort(sdk: EvoSDK): AppConnectPort { + const api = authSdk(sdk) + return { + async getIdentityFresh(identityId) { + const identity = await api.identities.fetch(identityId) + // A proved fetch by id: the identity returned is the one asked for. + return identity ? { id: identityId, publicKeys: toAppConnectKeys(identity.publicKeys) } : null + }, + + async remainingBudgets(identityId, keyIds) { + const budgets = await api.identities.keysRemainingBudgets(identityId, keyIds) + const out = new Map() + for (const [keyId, remaining] of budgets) out.set(Number(keyId), remaining ?? undefined) + return out + }, + + async contractKeys(identityId, contractId, purpose) { + const entries = await api.identities.contractKeys({ identityIds: [identityId], contractId, purposes: [purpose] }) + const entry = entries.find((e) => e.identityId.toBase58() === identityId) + return entry ? toAppConnectKeys(entry.keys) : [] + }, + + async groupInfo() { + return null + }, + + async listCandidates(requestHash, hint, startAfter, limit) { + const where: unknown[][] = [['appEphemeralPubKeyHash', '==', bytesToBase64(requestHash)]] + if (hint !== undefined) where.push(['$ownerId', '==', hint]) + else if (startAfter !== undefined) where.push(['$ownerId', '>', startAfter]) + const rows = await api.documents.query({ + dataContractId: APP_CONNECT_CONTRACT_ID, + documentTypeName: 'loginKeyResponse', + where, + // The (appEphemeralPubKeyHash, $ownerId) index, as the v1 poll reads it (`./app-connect`). + orderBy: [ + ['appEphemeralPubKeyHash', 'asc'], + ['$ownerId', 'asc'], + ], + limit, + }) + const candidates = [...rows.values()].filter(Boolean).map((r) => candidateOf((r as { toJSON(): ResponseJson }).toJSON())) + // The poller relies on owner order; Platform returns it, but a Map's order is the SDK's. + return candidates.sort((a, b) => compareIds(a.ownerId, b.ownerId)) + }, + + async chainClock() { + const { metadata } = await api.protocol.versionUpgradeStateWithProof() + return { protocolVersion: metadata.protocolVersion, timeMs: Number(metadata.timeMs) } + }, + } +} diff --git a/forge-web/lib/auth/app-connect-session.test.ts b/forge-web/lib/auth/app-connect-session.test.ts new file mode 100644 index 000000000..de607a988 --- /dev/null +++ b/forge-web/lib/auth/app-connect-session.test.ts @@ -0,0 +1,324 @@ +/** + * A session on a key a wallet granted through App Connect v2: one group-bound key covering every + * Forge contract, kept across reloads, with its origin stored beside it; no new write in its last + * five minutes; renewed in the wallet without locking anything while the wallet swaps the key; + * and a master-key renewal that makes it an ordinary Forge key again. The chain is a fake; the + * vault is the real one (in-memory IndexedDB, a fake window's localStorage). The vault's unlock is + * one per page, so these tests are one tab: what another tab does in the same moment is the same + * code path (`superseded`, `supersede`) reached from its own refresh or kept-session event. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { EvoSDK } from '@dashevo/evo-sdk' + +import { NETWORKS } from '../constants' +import { forgeContractIds } from '../deployments' +import { idbGet, resetMemoryStores } from '../idb' +import { KeyUnusableError } from '../sdk/write' +import { AuthController } from './controller' +import { walletRenewalInFlight } from './connection-id' +import type { WalletKey } from './key-registration' +import { LOCKED_AT_KEY } from './session-resume' +import { hasExtraKeys, listVaults, lockVault, readStorageBlob, releaseUnlocked, writeStorageBlob } 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-moutai', v2: forgeV2Ids(DEPLOYMENTS['devnet-moutai']) } + return { ...real, NETWORKS: { ...real.NETWORKS, devnet } } +}) +// The group check before a renewal's code (its reads are `group-trust.test.ts`'s). +vi.mock('./group-trust', async (orig) => ({ ...(await orig()), assertGroupHolds: async () => ({ unknown: [], unchecked: [], notice: null }) })) +vi.mock('../view/retry', () => ({ retryWhileMissing: 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-moutai', masterWif: 'MASTER', mnemonic: null }) } +}) +// The master-key renewal: recorded, not sent; it registers key 20. +const registered = vi.hoisted(() => [] as unknown[]) +vi.mock('./limited-key', async (orig) => { + const real = await orig() + return { + ...real, + registerLimitedKey: async (_sdk: unknown, params: { persist?: (k: { keyId: number; wif: string }) => Promise }) => { + registered.push(params) + 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 } } + }, + } +}) + +interface FakeKey { + keyId: number + wif: string + purposeNumber: number + securityLevelNumber: number + disabledAt?: bigint + expiresAt?: bigint + totalBudget?: bigint + contractBounds?: { toJSON(): { $type: string; id: string } } +} + +const NET = 'devnet' as const +const ID = '9r27eDsuXEqoMNymW1A2MKFrpBhzSkepVKwXrGzq9dUD' +const FORGE = NETWORKS[NET].v2! +const NETWORK_KEY = NETWORKS[NET].key +const wifOf = (n: number): string => encodeWif(new Uint8Array(32).fill(n), NET) +/** A passkey protection (no Argon2: fast). The fake `navigator.credentials` returns this PRF. */ +const PRF = new Uint8Array(32).fill(9) +const PASSKEY = { passkey: { credentialId: new Uint8Array([1]), prfSalt: new Uint8Array(32), output: PRF } } +const WAIT = { timeout: 15_000, interval: 20 } +const MIN = 60 * 1000 + +function fakeWindow(): { localStorage: Storage } { + 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(), + } as Storage + const win: Record = { + localStorage, + location: { hostname: 'forge.dashhq.org', pathname: '/' }, + addEventListener: () => undefined, + isSecureContext: true, + PublicKeyCredential: function PublicKeyCredential() {}, + } + win.top = win + win.self = win + return win as unknown as { localStorage: Storage } +} + +function fakeNavigator(): unknown { + return { + credentials: { + get: async () => ({ + rawId: new Uint8Array([1]).buffer, + getClientExtensionResults: () => ({ prf: { results: { first: PRF.slice().buffer, second: PRF.slice().buffer } } }), + }), + }, + } +} + +/** A group-bound HIGH key with a budget and `expiresAt`: what a v2 wallet registers. */ +function groupKey(keyId: number, expiresAt = Date.now() + 90 * 24 * 60 * MIN): FakeKey { + return { + keyId, + wif: wifOf(keyId), + purposeNumber: 0, + securityLevelNumber: 2, + totalBudget: 5_000_000_000n, + expiresAt: BigInt(expiresAt), + contractBounds: { toJSON: () => ({ $type: 'contractGroup', id: FORGE.group }) }, + } +} + +/** The verified grant `awaitV2Grant` hands back for `k`. */ +function grantOf(k: FakeKey): WalletKey { + return { + 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) }, + } +} + +describe('an App Connect v2 session', () => { + let keys: FakeKey[] + 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) + 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 + } + const locked = (): boolean => window.localStorage.getItem(LOCKED_AT_KEY) !== null + + beforeEach(() => { + resetMemoryStores() + vi.stubGlobal('window', fakeWindow()) + vi.stubGlobal('navigator', fakeNavigator()) + releaseUnlocked() + registered.length = 0 + keys = [{ keyId: 0, wif: wifOf(1), purposeNumber: 0, securityLevelNumber: 0 }, groupKey(5)] + }) + afterEach(() => { + for (const off of controllers.splice(0)) off() + vi.unstubAllGlobals() + }) + + it('covers every Forge contract with one limited key, signs each, and is kept for reloads', async () => { + const c = await signIn(keys[1]!) + const s = c.getState().session! + expect(s.origin).toBe('app-connect') + expect(s.grants).toEqual({ core: true, collab: true, community: true, meta: true }) + expect(s.unlimited).toBe(false) + expect(s.unbounded).toBe(false) + for (const contract of forgeContractIds(FORGE)) expect(c.writeAuth!.getSigningKeyWif(contract)).toBe(wifOf(5)) + // "Stay signed in for public repos" keeps it: a budgeted, expiring, group-bound key. + await vi.waitFor(async () => expect(await idbGet('vault', `session:${NET}`)).toBeDefined(), WAIT) + }, 30_000) + + it('starts no write in the key’s last five minutes (renew it in the wallet), but signs before them', async () => { + keys[1] = groupKey(5, Date.now() + 4 * MIN) + const c = await signIn(keys[1]) + expect(() => c.writeAuth!.getSigningKeyWif(FORGE.core)).toThrow(KeyUnusableError) + expect(() => c.writeAuth!.getSigningKeyWif(FORGE.core)).toThrow(expect.objectContaining({ reason: 'expired' })) + + keys[1] = groupKey(5, Date.now() + 6 * MIN) + const fresh = await signIn(keys[1]) + expect(fresh.writeAuth!.getSigningKeyWif(FORGE.core)).toBe(wifOf(5)) + }, 30_000) + + it('the margin is App Connect’s: the same key from a v1 wallet still signs', async () => { + keys[1] = groupKey(5, Date.now() + 4 * MIN) + const c = make() + await c.adoptWalletKeys(ID, [grantOf(keys[1])], PASSKEY) + expect(c.getState().session?.origin).toBeUndefined() + expect(c.writeAuth!.getSigningKeyWif(FORGE.core)).toBe(wifOf(5)) + }, 30_000) + + it('keeps its origin across a lock and unlock, and across a reload of a kept session', async () => { + const c = await signIn(keys[1]!) + await vi.waitFor(async () => expect(await idbGet('vault', `session:${NET}`)).toBeDefined(), WAIT) + expect((await listVaults(NET)).find((v) => v.identityId === ID)).toMatchObject({ fromAppConnect: true }) + // A reload picks up the kept session: its origin is there before and after the chain check. + releaseUnlocked() + const next = make() + expect(await next.resume()).toBe(true) + expect(next.getState().session?.origin).toBe('app-connect') + await vi.waitFor(() => expect(next.getState().session?.balanceReadAt).toBeTypeOf('number'), WAIT) + expect(next.getState().session?.origin).toBe('app-connect') + // An interactive unlock reads it from the stored record. + c.logout() + const unlocked = await make().unlock(ID, 'passkey') + expect(unlocked.origin).toBe('app-connect') + }, 60_000) + + it('a master-key renewal makes it an ordinary Forge key (origin cleared)', async () => { + const c = await signIn(keys[1]!) + keys.push({ ...groupKey(20), wif: wifOf(20) }) + const renewed = await c.importIdentity({ fileText: '{}' }, PASSKEY, undefined, { renew: true }) + expect(registered).toHaveLength(1) + expect(renewed.keyId).toBe(20) + expect(renewed.origin).toBeUndefined() + const stored = (await listVaults(NET)).find((v) => v.identityId === ID) + expect(stored?.keyId).toBe(20) + expect(stored?.fromAppConnect).toBeUndefined() + }, 30_000) + + it('renews in the wallet: the replaced key locks nothing, and the renewal carries everything over', async () => { + const c = await signIn(keys[1]!) + await writeStorageBlob(NET, ID, { bucket: 'kept' }) + const req = await c.walletRenewalRequest() + expect(req).toMatchObject({ identityHint: ID, replacesKeyId: 5 }) + expect(walletRenewalInFlight(NETWORK_KEY, ID, 5)).toBe(true) + // The wallet's update: key 5 disabled, key 6 added. A refresh now finds its key disabled: no + // lock, and the renewing tab keeps its unlock (it stores the new key with it). + keys[1]!.disabledAt = 1n + keys.push(groupKey(6)) + await c.refreshBalance() + expect(locked()).toBe(false) + expect(c.getState().session?.keyId).toBe(5) + const renewed = await signIn(keys[2]!, c) + expect(renewed.getState().session).toMatchObject({ keyId: 6, origin: 'app-connect' }) + expect(walletRenewalInFlight(NETWORK_KEY, ID, 5)).toBe(false) + expect(locked()).toBe(false) + // Storage settings carried over; the disabled key is not held on (nothing left to disable). + expect(await readStorageBlob(NET, ID)).toEqual({ bucket: 'kept' }) + expect(await hasExtraKeys(NET, ID)).toBe(false) + }, 60_000) + + it('keeps a replaced key the wallet left live, so a later revoke disables it', async () => { + const c = await signIn(keys[1]!) + keys.push(groupKey(6)) + await signIn(keys[2]!, c) + expect(await hasExtraKeys(NET, ID)).toBe(true) + }, 30_000) + + it('a v2 sign-in over a locked vault is blocked only where unlocking would be needed', async () => { + const c = await signIn(keys[1]!) + c.logout() + // A group-bound Forge key alone: a master-key update disables it by id, locked or not. + expect(await c.walletSignInBlocker()).toBeNull() + // A shipped wallet's unlimited key: unlock first, while it still opens. + keys[1] = { ...keys[1]!, totalBudget: undefined, expiresAt: undefined, contractBounds: { toJSON: () => ({ $type: 'singleContract', id: FORGE.core }) } } + expect(await c.walletSignInBlocker()).toMatch(/Unlock first/) + }, 30_000) + + it('ends a renewal it gave up without touching another key’s mark', async () => { + const c = await signIn(keys[1]!) + const req = await c.walletRenewalRequest() + c.endWalletRenewal({ ...req, replacesKeyId: 99 }) + expect(walletRenewalInFlight(NETWORK_KEY, ID, 5)).toBe(true) + c.endWalletRenewal(req) + expect(walletRenewalInFlight(NETWORK_KEY, ID, 5)).toBe(false) + }, 30_000) + + it('without a renewal in flight, a disabled key still signs out every tab', async () => { + const c = await signIn(keys[1]!) + const req = await c.walletRenewalRequest() + c.endWalletRenewal(req) + expect(walletRenewalInFlight(NETWORK_KEY, ID, 5)).toBe(false) + keys[1]!.disabledAt = 1n + await c.refreshBalance() + expect(locked()).toBe(true) + expect(c.getState().notice).toMatch(/Signed out/) + }, 30_000) + + it('renews in the wallet only a key a wallet granted, with the whole vault open', async () => { + const v1 = make() + await v1.adoptWalletKeys(ID, [grantOf(keys[1]!)], PASSKEY) + await expect(v1.walletRenewalRequest()).rejects.toThrow(/identity file or recovery phrase/) + lockVault() + // A reload's signing-only tab must unlock first: storing the new key needs the whole vault. + const c = await signIn(keys[1]!) + await vi.waitFor(async () => expect(await idbGet('vault', `session:${NET}`)).toBeDefined(), WAIT) + releaseUnlocked() + const resumed = make() + await resumed.resume() + await expect(resumed.walletRenewalRequest()).rejects.toThrow(/Unlock this tab first/) + expect(c).toBeDefined() + }, 60_000) + + it('checks the session again on request (a write outside the key’s bounds)', async () => { + const c = await signIn(keys[1]!) + keys[1]!.totalBudget = 4_000_000_000n + const s = await c.recheckSession() + expect(s?.keyLimits?.remaining).toBe(4_000_000_000n) + keys[1]!.disabledAt = 1n + await expect(c.recheckSession()).rejects.toThrow() + expect(locked()).toBe(true) + }, 30_000) +}) diff --git a/forge-web/lib/auth/app-connect-v2.live.test.ts b/forge-web/lib/auth/app-connect-v2.live.test.ts new file mode 100644 index 000000000..0bd9105ab --- /dev/null +++ b/forge-web/lib/auth/app-connect-v2.live.test.ts @@ -0,0 +1,129 @@ +/** + * App Connect v2 wallet sign-in, live on a devnet with a scripted wallet + * (e2e/wallet-responder-v2.ts does what a wallet that speaks the profile does). SKIPPED by default + * (real spend: it creates a repository, stars it, and registers and disables keys): + * + * FORGE_LIVE=1 NEXT_PUBLIC_NETWORK=devnet NEXT_PUBLIC_DEVNET_NAME=sakura \ + * pnpm exec vitest run lib/auth/app-connect-v2.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.2 DASH of credits. The app side is Forge's own code: the v2 request, the poll on the App + * Connect contract, the vendored verifier plus Forge's key rules, the vault session, the renewal + * and writes through the WriteEngine. + * + * 1. login: request (forge group, 0.05 DASH, 90 days) → the wallet adds one group-bound key and + * publishes the response → the verified grant covers all four contracts, has a budget and an + * expiry, and opens a session of origin `app-connect`; + * 2. a forge-core write (a repository) and a forge-community write (a star) are signed by that + * one key, with no further approval; + * 3. renewal: the session's `walletRenewalRequest` names the identity and carries the same + * connection id → the wallet adds a new key and disables the old one in the same update → + * the new key is stored and signs a write; the old key is disabled on chain; + * 4. cleanup: the master key disables every key this run added. + */ + +import { existsSync } from 'node:fs' +import { homedir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it, vi } from 'vitest' + +import { DEFAULT_NETWORK, NETWORKS } from '../constants' +import { resetMemoryStores } from '../idb' +import { evoSdkService } from '../sdk' +import { createRepo, starRelation } from '../repo/writes' +import { authSdk } from '../sdk/facade' + +import { approveV2, disableGrants, newV2Wallet } from '../../e2e/wallet-responder-v2' +import { appConnectV2Available, awaitV2Grant, newV2LoginRequest, readChainClock, type V2Grant } from './app-connect-v2' +import { AuthController } from './controller' +import { defaultLimits } from './limited-key' + +// Node has no localStorage, so the connection id would be new on every request and the wallet +// could not tell a renewal from a second device: one fixed id stands in for the browser's. +const CONNECTION = new Uint8Array(16).fill(0x5a) +vi.mock('./connection-id', async (orig) => ({ ...(await orig()), connectionId: () => CONNECTION })) + +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) + +describe.skipIf(!LIVE)('live App Connect v2 sign-in (scripted wallet, App Connect contract)', () => { + it( + 'login, writes on every contract with one key, renewal in the wallet, cleanup', + async () => { + await evoSdkService.initialize({ network: 'devnet', contractIds: [], timeoutMs: 30000 }) + const sdk = evoSdkService.getSdk() + const forge = NETWORKS.devnet.v2! + const network = 'devnet' as const + const wallet = newV2Wallet() + const poll = { network, forge, intervalMs: 2000, settleMs: 2000 } + expect(await appConnectV2Available(sdk, network)).toBe(true) + + /** The app shows `req`'s code; the wallet approves it; the app's poll verifies the answer. */ + async function approve(req: Parameters[1]): Promise<{ grant: V2Grant; replacedKeyId: number | null; keyId: number }> { + const answering = awaitV2Grant(sdk, req, poll) + const approved = await approveV2({ wallet, uri: req.qrUri, identityFile: FILE, devnet: DEVNET }) + expect(approved.label).toBe('Dash Forge') + const grant = await answering + expect(grant.identityId).toBe(approved.identityId) + expect(grant.key.keyId).toBe(approved.keyId) + return { grant, replacedKeyId: approved.replacedKeyId, keyId: approved.keyId } + } + + try { + resetMemoryStores() + const controller = new AuthController(async () => sdk, network) + // The group check Forge runs before it shows a code. + await controller.checkGroup() + + // 1. Login: one request, one key, bound to the whole group, with the default budget. + const { timeMs } = await readChainClock(sdk) + const proposed = defaultLimits(timeMs) + const first = await approve(newV2LoginRequest(network, forge, { connectionId: CONNECTION, chainNow: timeMs })) + expect(first.replacedKeyId).toBeNull() + expect(first.grant.key.scope).toEqual({ core: true, collab: true, community: true, meta: true, unbounded: false }) + expect(first.grant.key.limits?.total).toBe(proposed.budgetCredits) + const expiry = first.grant.key.limits?.expiresAt ?? 0 + expect(Math.abs(expiry - proposed.expiresAt)).toBeLessThan(60 * 60_000) + + const protection = { passphrase: 'live app connect v2 passphrase' } + const session = await controller.adoptWalletKeys(first.grant.identityId, [first.grant.key], protection, { origin: 'app-connect' }) + expect(session.origin).toBe('app-connect') + expect(session.grants).toMatchObject({ core: true, collab: true, community: true }) + expect(session.unlimited).toBeFalsy() + const auth = controller.writeAuth! + + // 2. A forge-core write and a forge-community write, both signed by the one key: no grant sheet. + const name = `ac-v2-e2e-${Date.now().toString(36)}` + const repo = await createRepo(sdk, auth, forge, { name }) + expect(repo.repoId).toMatch(/^[1-9A-HJ-NP-Za-km-z]{43,44}$/) + const starOf = { kind: 'v2' as const, forge, repoId: repo.repoId, ownerId: first.grant.identityId, name, visibility: 'public' as const } + expect(await starRelation(sdk, auth, first.grant.identityId, starOf).add()).toBe(true) + + // 3. Renewal in the wallet: the same identity and connection id, so the old key goes. + const renewal = await controller.walletRenewalRequest() + expect(renewal.identityHint).toBe(first.grant.identityId) + expect(renewal.replacesKeyId).toBe(first.keyId) + const second = await approve(renewal) + expect(second.replacedKeyId).toBe(first.keyId) + expect(second.keyId).not.toBe(first.keyId) + const renewed = await controller.adoptWalletKeys(second.grant.identityId, [second.grant.key], protection, { origin: 'app-connect' }) + expect(renewed.keyId).toBe(second.keyId) + expect(renewed.origin).toBe('app-connect') + + // The wallet disabled the old key in the update that added the new one. + const identity = await authSdk(sdk).identities.fetch(first.grant.identityId) + expect(identity?.publicKeys.find((k) => k.keyId === first.keyId)?.disabledAt).toBeDefined() + expect(identity?.publicKeys.find((k) => k.keyId === second.keyId)?.disabledAt).toBeUndefined() + + // The new key signs: take the star back. + expect(await starRelation(sdk, controller.writeAuth!, first.grant.identityId, starOf).remove()).toBe(true) + } finally { + // 4. Leave the identity as it was: disable what this run added. + await disableGrants({ wallet, identityFile: FILE, devnet: DEVNET }) + } + }, + 20 * 60_000, + ) +}) diff --git a/forge-web/lib/auth/app-connect-v2.test.ts b/forge-web/lib/auth/app-connect-v2.test.ts new file mode 100644 index 000000000..09bbb8d14 --- /dev/null +++ b/forge-web/lib/auth/app-connect-v2.test.ts @@ -0,0 +1,395 @@ +/** + * App Connect v2 sign-in, offline: Forge's request against the vendored parser (bytes, callback, + * renewal), and the poll against a simulated v2 wallet (`./wallet-sim` `answerV2`) on a fake + * chain: the verifier's accepts and refusals, two answerers, and a key a node shows late. + */ + +import * as secp from '@noble/secp256k1' +import { ripemd160 } from '@noble/hashes/legacy.js' +import { sha256 } from '@noble/hashes/sha2.js' +import { bytesToHex } from '@noble/hashes/utils.js' +import type { EvoSDK } from '@dashevo/evo-sdk' +import { describe, expect, it } from 'vitest' + +import type { ForgeIds } from '../deployments' +import { CREDITS_PER_DASH } from '../sdk/cost' +import { bytesToBase64 } from '../sdk/query' +import { AppConnectTlv, KeySecurityLevel, parseAppConnectUri } from '../vendor/platform-auth/app-connect' +import { AmbiguousWalletLogin, APP_CONNECT_CONTRACT_ID, RequestExpired } from './app-connect' +import { + APP_CONNECT_LABEL, + PollTrigger, + TooManyAnswers, + WalletGrantRefused, + awaitV2Grant, + forgeV2Request, + newV2LoginRequest, + type V2LoginRequest, +} from './app-connect-v2' +import { compareIds } from './app-connect-port' +import { base58Decode, base58Encode } from './base58' +import { isUnlimited } from './key-registration' +import { answerV2 } from './wallet-sim' +import { decodeWif } from './wif' + +const FORGE: ForgeIds = { + core: 'A2KL77ngVM1ft1t1em2XKt1rWCBZANdAJMyfWrDGCcd1', + collab: 'C1zHeeG7EUudXdB5ZyDQnXVU35hrCfvd1fRCybXEqaPS', + community: 'C1zHeeG7EUudXdB5ZyDQnXVU35hrCfvd1fRCybXEqaPS', + group: '6dV3kMBWHGR7pLKrHToMBQgbTpjqeE2VAyCEWmLbrkWC', +} +const OTHER_GROUP = 'Bwr4WHCPz5rFVAD87RqTs3izo4zpzwsEdKPWUT1NS1C7' +const ALICE = 'HwhCv9N5BHsbGNLzDR4tnZnqJ6VxtwJSLsM4aUWn2Tnr' +const MALLORY = 'CJao2MVHL4x3f2Ko2xTUibnZ8G1t9exTPtvJnCbHAgDH' +const CONNECTION = new Uint8Array(16).fill(7) +const DAY = 24 * 60 * 60 * 1000 + +/** The TLVs after the fixed header (version, key, app id, label), as [type, value]. */ +function tlvs(body: Uint8Array): [number, Uint8Array][] { + let at = 1 + 33 + 32 + at += 1 + (body[at] as number) + const out: [number, Uint8Array][] = [] + while (at < body.length) { + const type = body[at] as number + const len = body[at + 1] as number + out.push([type, body.slice(at + 2, at + 2 + len)]) + at += 2 + len + } + return out +} + +describe('the request Forge makes', () => { + const chainNow = Date.UTC(2026, 9, 24) + + it('asks for one group-bound HIGH key with Forge’s default limits: 157 bytes', () => { + const req = newV2LoginRequest('devnet', FORGE, { connectionId: CONNECTION, chainNow, now: chainNow + 5000 }) + const { request, requestBytes, network, callbackUrl } = parseAppConnectUri(req.qrUri) + expect(network).toBe('devnet') + expect(callbackUrl).toBeUndefined() + expect(requestBytes.length).toBe(157) + expect(request.label).toBe(APP_CONNECT_LABEL) + expect(bytesToHex(request.appId)).toBe(bytesToHex(base58Decode(FORGE.core))) + expect(request.encBindings).toEqual([]) + expect(request.authBindings).toHaveLength(1) + const binding = request.authBindings[0]! + expect(binding.kind).toBe('contractGroup') + expect(bytesToHex(binding.id)).toBe(bytesToHex(base58Decode(FORGE.group))) + expect(binding.securityLevel).toBe(KeySecurityLevel.HIGH) + expect(binding.totalBudget).toBe(BigInt(0.05 * CREDITS_PER_DASH)) + // Expiry from chain time; CREATED_AT from this device's clock. + expect(binding.expiresAt).toBe(chainNow + 90 * DAY) + expect(request.createdAt).toBe(chainNow + 5000) + expect(bytesToHex(request.connectionId!)).toBe(bytesToHex(CONNECTION)) + const types = tlvs(requestBytes).map(([t, v]) => [t, v.length + 2]) + expect(types).toEqual([ + [AppConnectTlv.AUTH_BINDING, 52], + [AppConnectTlv.CONNECTION_ID, 18], + [AppConnectTlv.CREATED_AT, 10], + ]) + // Answers are stored under hash160 of the request's ephemeral key. + expect(bytesToHex(req.requestHash)).toBe(bytesToHex(ripemd160(sha256(request.appEphemeralPubKey)))) + expect(req.expiresAt - req.createdAt).toBe(10 * 60 * 1000) + }) + + it('puts the callback on the deep link only', () => { + let seen: Uint8Array | null = null + const req = newV2LoginRequest('devnet', FORGE, { + connectionId: CONNECTION, + chainNow, + callbackUrl: (hash) => { + seen = hash + return `https://forge.dashhq.org/connect/?r=${bytesToHex(hash)}` + }, + }) + expect(bytesToHex(seen!)).toBe(bytesToHex(req.requestHash)) + expect(req.qrUri).not.toContain('cb=') + const link = parseAppConnectUri(req.linkUri) + expect(link.callbackUrl).toBe(`https://forge.dashhq.org/connect/?r=${bytesToHex(req.requestHash)}`) + // One request: the same bytes behind both. + expect(bytesToHex(link.requestBytes)).toBe(bytesToHex(parseAppConnectUri(req.qrUri).requestBytes)) + const none = newV2LoginRequest('devnet', FORGE, { connectionId: CONNECTION, chainNow, callbackUrl: () => null }) + expect(none.linkUri).toBe(none.qrUri) + }) + + it('renews with the identity as hint and the same connection id, and no MODE', () => { + const login = forgeV2Request(FORGE, { appEphemeralPubKey: secp.getPublicKey(secp.utils.randomSecretKey(), true), connectionId: CONNECTION, chainNow, now: chainNow }) + const req = newV2LoginRequest('testnet', FORGE, { connectionId: CONNECTION, chainNow, identityHint: ALICE }) + const { request, requestBytes } = parseAppConnectUri(req.qrUri) + expect(req.identityHint).toBe(ALICE) + expect(bytesToHex(request.identityHint!)).toBe(bytesToHex(base58Decode(ALICE))) + expect(bytesToHex(request.connectionId!)).toBe(bytesToHex(login.connectionId!)) + expect(request.mode).toBeUndefined() + expect(tlvs(requestBytes).map(([t]) => t)).toEqual([AppConnectTlv.IDENTITY_HINT, AppConnectTlv.AUTH_BINDING, AppConnectTlv.CONNECTION_ID, AppConnectTlv.CREATED_AT]) + expect(requestBytes.length).toBe(157 + 34) + }) +}) + +// --------------------------------------------------------------------------- +// The poll against a simulated v2 wallet +// --------------------------------------------------------------------------- + +interface ChainKey { + keyId: number + priv: Uint8Array + bounds: { $type: string; id: string } | null + securityLevelNumber?: number + totalBudget?: bigint + expiresAt?: bigint + disabledAt?: bigint +} + +/** A fake SDK: identities with keys (as wasm reads them), and App Connect answers. */ +function fakeChain() { + const identities = new Map() + const docs: Record[] = [] + let queries = 0 + const sdk = { + identities: { + async fetch(id: string) { + const keys = identities.get(id) + if (!keys) return undefined + return { + balance: 10n ** 11n, + revision: 1n, + publicKeys: keys.map((k) => ({ + keyId: k.keyId, + keyTypeNumber: 0, + data: bytesToHex(secp.getPublicKey(k.priv, true)), + purposeNumber: 0, + securityLevelNumber: k.securityLevelNumber ?? 2, + disabledAt: k.disabledAt, + totalBudget: k.totalBudget, + expiresAt: k.expiresAt, + contractBounds: k.bounds ? { toJSON: () => k.bounds } : undefined, + validatePrivateKey: (bytes: Uint8Array) => bytesToHex(bytes) === bytesToHex(k.priv), + })), + } + }, + async keysRemainingBudgets(id: string, ids: number[]) { + const keys = identities.get(id) ?? [] + return new Map(ids.map((i) => [i, keys.find((k) => k.keyId === i)?.totalBudget ?? null])) + }, + }, + documents: { + async query(q: { dataContractId: string; where: [string, string, string][]; limit?: number }) { + queries++ + const hash = q.where.find((w) => w[0] === 'appEphemeralPubKeyHash')?.[2] + const owner = q.where.find((w) => w[0] === '$ownerId' && w[1] === '==')?.[2] + const after = q.where.find((w) => w[0] === '$ownerId' && w[1] === '>')?.[2] + const rows = docs + .filter((d) => q.dataContractId === APP_CONNECT_CONTRACT_ID && d['appEphemeralPubKeyHash'] === hash) + .filter((d) => owner === undefined || d['$ownerId'] === owner) + .filter((d) => after === undefined || compareIds(String(d['$ownerId']), after) > 0) + .sort((a, b) => compareIds(String(a['$ownerId']), String(b['$ownerId']))) + .slice(0, q.limit ?? 100) + // Reversed: the port must not rely on the SDK's map order. + return new Map(rows.reverse().map((r, i) => [String(i), { toJSON: () => r }])) + }, + }, + } + /** + * A v2 wallet approving `uri` for `identityId`: registers a fresh key (unless `register` is + * false) with the limits asked for, overridden by `register`, and publishes its answer. + */ + async function approve(uri: string, identityId: string, register: Partial | false = {}) { + const { request } = parseAppConnectUri(uri) + const binding = request.authBindings[0]! + const priv = secp.utils.randomSecretKey() + const keys = identities.get(identityId) ?? [{ keyId: 0, priv: new Uint8Array(32).fill(0x77), bounds: null, securityLevelNumber: 0 }] + identities.set(identityId, keys) + const chainKey: ChainKey = { + keyId: keys.length, + priv, + bounds: { $type: 'contractGroup', id: FORGE.group }, + totalBudget: binding.totalBudget, + expiresAt: BigInt(binding.expiresAt!), + ...(register || {}), + } + if (register !== false) keys.push(chainKey) + const answer = await answerV2(uri, { ownerId: identityId, slots: [priv] }) + docs.push({ + $ownerId: identityId, + appEphemeralPubKeyHash: bytesToBase64(answer.requestHash), + walletEphemeralPubKey: bytesToBase64(answer.walletEphemeralPubKey), + encryptedPayload: bytesToBase64(answer.encryptedPayload), + }) + return { priv, register: () => keys.push(chainKey) } + } + return { sdk: sdk as unknown as EvoSDK, identities, docs, approve, queries: () => queries } +} + +const fast = { network: 'devnet' as const, forge: FORGE, intervalMs: 1, settleMs: 0 } +const request = (identityHint?: string): V2LoginRequest => + newV2LoginRequest('devnet', FORGE, { connectionId: CONNECTION, chainNow: Date.now(), ...(identityHint ? { identityHint } : {}) }) + +describe('v2 poll against a simulated wallet', () => { + it('accepts a group-bound HIGH key with a budget and an expiry, as Forge’s own wallet key', async () => { + const chain = fakeChain() + const req = request() + const { priv } = await chain.approve(req.qrUri, ALICE) + const grant = await awaitV2Grant(chain.sdk, req, fast) + expect(grant.identityId).toBe(ALICE) + expect(grant.key.keyId).toBe(1) + expect(grant.key.scope).toEqual({ core: true, collab: true, community: true, meta: true, unbounded: false }) + expect(isUnlimited(grant.key)).toBe(false) + expect(grant.key.limits?.total).toBe(BigInt(0.05 * CREDITS_PER_DASH)) + expect(bytesToHex(decodeWif(grant.key.wif).privateKey)).toBe(bytesToHex(priv)) + // The request is spent. + expect(req.appEphemeralPriv.every((b) => b === 0)).toBe(true) + }) + + it('takes a budget the wallet raised (its presets start at 0.1 DASH)', async () => { + const chain = fakeChain() + const req = request() + await chain.approve(req.qrUri, ALICE, { totalBudget: BigInt(0.1 * CREDITS_PER_DASH) }) + const grant = await awaitV2Grant(chain.sdk, req, fast) + expect(grant.key.limits?.total).toBe(BigInt(0.1 * CREDITS_PER_DASH)) + }) + + it.each([ + ['a key without a budget', { totalBudget: undefined }, 'key-limits'], + ['a CRITICAL key', { securityLevelNumber: 1 }, 'key-level'], + ['a key bound to another group', { bounds: { $type: 'contractGroup', id: OTHER_GROUP } }, 'key-unmatched'], + ['a key expiring within the hour', { expiresAt: BigInt(Date.now() + 30 * 60 * 1000) }, 'key-expired'], + ['a disabled key', { disabledAt: 1n }, 'key-disabled'], + ] as const)('refuses %s', async (_what, register, reason) => { + const chain = fakeChain() + const req = request() + await chain.approve(req.qrUri, ALICE, register) + const outcome = awaitV2Grant(chain.sdk, req, fast) + await expect(outcome).rejects.toBeInstanceOf(WalletGrantRefused) + await expect(outcome).rejects.toMatchObject({ reason }) + }) + + it('refuses when two identities answer (someone else saw the QR)', async () => { + const chain = fakeChain() + const req = request() + await chain.approve(req.qrUri, ALICE) + await chain.approve(req.qrUri, MALLORY) + await expect(awaitV2Grant(chain.sdk, req, fast)).rejects.toBeInstanceOf(AmbiguousWalletLogin) + }) + + it('waits out the settle window: a second answer inside it is refused', async () => { + const chain = fakeChain() + const req = request() + await chain.approve(req.qrUri, ALICE) + let late: Promise | null = null + const outcome = awaitV2Grant(chain.sdk, req, { + ...fast, + settleMs: 5_000, + onStatus: (s) => { + // ALICE's answer is verified; MALLORY answers while Forge waits for competitors. + if (s === 'answered' && late === null) late = chain.approve(req.qrUri, MALLORY) + }, + }) + await expect(outcome).rejects.toBeInstanceOf(AmbiguousWalletLogin) + expect(late).not.toBeNull() + }) + + it('checks expiry against chain time, not this device’s clock', async () => { + const chain = fakeChain() + const req = request() + await chain.approve(req.qrUri, ALICE) + const expiresAt = Number(chain.identities.get(ALICE)![1]!.expiresAt) + // The chain is 30 minutes from the key's expiry while this device's clock is 90 days before it. + const late = { ...req, chainTimeAtCreation: expiresAt - 30 * 60 * 1000 } + await expect(awaitV2Grant(chain.sdk, late, fast)).rejects.toMatchObject({ reason: 'key-expired' }) + }) + + it('counts an answer whose key no node shows yet: a quick stranger does not win', async () => { + const chain = fakeChain() + const req = request() + await chain.approve(req.qrUri, ALICE, false) + await chain.approve(req.qrUri, MALLORY) + await expect(awaitV2Grant(chain.sdk, req, fast)).rejects.toBeInstanceOf(AmbiguousWalletLogin) + }) + + it('checks again when the key is not shown yet (key-not-found), and accepts it once it is', async () => { + const chain = fakeChain() + const req = request() + const { register } = await chain.approve(req.qrUri, ALICE, false) + const statuses: string[] = [] + const grant = awaitV2Grant(chain.sdk, req, { + ...fast, + onStatus: (s) => { + statuses.push(s) + // A few polls later the node shows the key. + if (statuses.length === 3) register() + }, + }) + expect((await grant).identityId).toBe(ALICE) + expect(statuses.slice(0, 3)).toEqual(['waiting', 'waiting', 'waiting']) + }) + + it('ignores answers not encrypted to this request', async () => { + const chain = fakeChain() + const req = request() + const other = request() + await chain.approve(other.qrUri, MALLORY) + // MALLORY's answer to another request, relabelled as an answer to this one. + chain.docs[0]!['appEphemeralPubKeyHash'] = bytesToBase64(req.requestHash) + await chain.approve(req.qrUri, ALICE) + expect((await awaitV2Grant(chain.sdk, req, fast)).identityId).toBe(ALICE) + }) + + it('a renewal reads only the named identity, and its refusal is final at once', async () => { + const chain = fakeChain() + const req = request(ALICE) + await chain.approve(req.qrUri, MALLORY) + await chain.approve(req.qrUri, ALICE) + expect((await awaitV2Grant(chain.sdk, req, { ...fast, settleMs: 60_000 })).identityId).toBe(ALICE) + + const chain2 = fakeChain() + const req2 = request(ALICE) + await chain2.approve(req2.qrUri, ALICE, { securityLevelNumber: 1 }) + await expect(awaitV2Grant(chain2.sdk, req2, fast)).rejects.toMatchObject({ reason: 'key-level' }) + }) + + it('stops when more answers arrive than it reads (junk)', async () => { + const chain = fakeChain() + const req = request() + for (let i = 0; i < 21; i++) { + const id = base58Encode(new Uint8Array(32).fill(i + 1)) + chain.docs.push({ $ownerId: id, appEphemeralPubKeyHash: bytesToBase64(req.requestHash), walletEphemeralPubKey: bytesToBase64(new Uint8Array(33)), encryptedPayload: bytesToBase64(new Uint8Array(60)) }) + } + await expect(awaitV2Grant(chain.sdk, req, fast)).rejects.toBeInstanceOf(TooManyAnswers) + }) + + it('does not settle on a round that could not read the answers', async () => { + const chain = fakeChain() + const req = { ...request(), expiresAt: Date.now() + 60 } + await chain.approve(req.qrUri, ALICE) + ;(chain.sdk as unknown as { documents: { query: () => Promise } }).documents.query = () => Promise.reject(new Error('node refused')) + const statuses: string[] = [] + await expect(awaitV2Grant(chain.sdk, req, { ...fast, onStatus: (s) => statuses.push(s) })).rejects.toBeInstanceOf(RequestExpired) + expect(statuses).toContain('incomplete-read') + }) + + it('polls at once when triggered, and expires', async () => { + const chain = fakeChain() + const trigger = new PollTrigger() + const req = request() + const before = chain.queries() + const outcome = awaitV2Grant(chain.sdk, req, { network: 'devnet', forge: FORGE, trigger, settleMs: 0 }) + await new Promise((r) => setTimeout(r, 20)) + trigger.fire() + await new Promise((r) => setTimeout(r, 20)) + // Two polls in well under the 2 s cadence: the second was the trigger's. + expect(chain.queries() - before).toBe(2) + await chain.approve(req.qrUri, ALICE) + trigger.fire() + expect((await outcome).identityId).toBe(ALICE) + + const stale = newV2LoginRequest('devnet', FORGE, { connectionId: CONNECTION, chainNow: Date.now(), now: Date.now() - 10 * 60 * 1000 - 1 }) + await expect(awaitV2Grant(chain.sdk, stale, fast)).rejects.toBeInstanceOf(RequestExpired) + expect(stale.appEphemeralPriv.every((b) => b === 0)).toBe(true) + }) + + it('stops on abort', async () => { + const chain = fakeChain() + const ac = new AbortController() + const outcome = awaitV2Grant(chain.sdk, request(), { network: 'devnet', forge: FORGE, signal: ac.signal }) + ac.abort() + await expect(outcome).rejects.toMatchObject({ name: 'AbortError' }) + }) +}) diff --git a/forge-web/lib/auth/app-connect-v2.ts b/forge-web/lib/auth/app-connect-v2.ts new file mode 100644 index 000000000..57ac79ce8 --- /dev/null +++ b/forge-web/lib/auth/app-connect-v2.ts @@ -0,0 +1,399 @@ +/** + * "Use my Dash wallet" with App Connect v2 (`APP_CONNECT_PROFILE.md`; docs/design/wallet-login.md, + * "Upgrade path"), beside the v1 flow in {@link ./app-connect}, which stays as it is: a wallet that + * speaks only v1 refuses a `v=2` request, so the two never share a QR code. + * + * One request asks for ONE key: AUTHENTICATION / HIGH, bound to the dash-forge contract group, with + * Forge's default budget and expiry ({@link defaultLimits}, from chain time). It covers every Forge + * contract, so no further grants are asked for. The request's app is forge-core (its owner is the + * group's owner, as the profile's owner rule needs); no encryption key is asked for, since no Forge + * contract allows a wallet-issued one (members-only content is set up in Settings). + * + * A wallet that approves registers the key (disabling the key of its previous grant for this + * browser's connection id, `./connection-id`) and publishes a `loginKeyResponse` in the App + * Connect contract under its identity. The poll pages through every answer, opens each with the + * request's ephemeral key and checks it with the vendored verifier (live key on the answering + * identity, exactly the bounds, level and limits asked for, not about to expire or spent), then + * once more with Forge's own rules ({@link findWalletKey}), which yields the {@link WalletKey} the + * controller stores (`adoptWalletKeys`, origin `app-connect`) like any wallet key. + * + * Who answered is not proven (anyone who saw the QR can answer from their own identity): two + * answers are refused, and without an identity hint the UI asks "Continue as …?". A renewal names + * the identity (`IDENTITY_HINT`) and carries the same connection id, and no `MODE`: wallets do not + * know `MODE` = renew yet, and its type is even, so a wallet that does not know it refuses the + * whole request. + * + * Clocks: `CREATED_AT` is this device's clock (the wallet compares it with its own); the proposed + * expiry and the verifier's "now" are chain time (the latest block's), falling back to this + * device's clock when it cannot be read. + */ + +import * as secp from '@noble/secp256k1' +import type { EvoSDK } from '@dashevo/evo-sdk' + +import { NETWORKS, type Network } from '../constants' +import { withTimeout } from '../timeout' +import type { ForgeIds } from '../deployments' +import { + APP_CONNECT_MAX_REQUEST_AGE_MS, + KeySecurityLevel, + appConnectCandidateKey, + appConnectPollDelayMs, + appConnectRequestHash, + buildAppConnectUri, + listAppConnectCandidates, + verifyAppConnectCandidate, + type AppConnectGrant, + type AppConnectRejectReason, + type AppConnectRequest, +} from '../vendor/platform-auth/app-connect' +import { AmbiguousWalletLogin, RequestExpired, type PollStatus } from './app-connect' +import { appConnectPort } from './app-connect-port' +import { decodeIdentifier } from './base58' +import { PLATFORM_READ_MS } from './connect' +import { findWalletKey, isUnlimited, RevokedWalletKey, UnusableWalletKey, type WalletKey } from './key-registration' +import { defaultLimits } from './limited-key' +import { encodeWif } from './wif' + +/** The name a wallet shows for Forge. */ +export const APP_CONNECT_LABEL = 'Dash Forge' + +/** + * Whether a renewal carries `MODE` = renew. Off: no wallet supports it yet, and a wallet that + * does not know the (even, so mandatory) type refuses the request. A renewal is a new grant for + * the same identity and connection id instead, which disables the old key. + */ +export const RENEW_MODE = false + +/** The App Connect contract and v2 requests exist from protocol 14. */ +export const APP_CONNECT_MIN_PROTOCOL = 14 + +/** The request Forge makes: one group-bound HIGH key with Forge's default limits. */ +export function forgeV2Request( + forge: ForgeIds, + p: { + readonly appEphemeralPubKey: Uint8Array + readonly connectionId: Uint8Array + /** Chain time (ms): the proposed expiry counts from it. */ + readonly chainNow: number + /** This device's clock (ms): `CREATED_AT`. */ + readonly now: number + /** The identity a renewal is for. */ + readonly identityHint?: string + }, +): AppConnectRequest { + const limits = defaultLimits(p.chainNow) + return { + appEphemeralPubKey: p.appEphemeralPubKey, + appId: decodeIdentifier(forge.core), + label: APP_CONNECT_LABEL, + authBindings: [ + { + kind: 'contractGroup', + id: decodeIdentifier(forge.group), + securityLevel: KeySecurityLevel.HIGH, + totalBudget: limits.budgetCredits, + expiresAt: limits.expiresAt, + }, + ], + encBindings: [], + createdAt: p.now, + connectionId: p.connectionId, + ...(p.identityHint !== undefined ? { identityHint: decodeIdentifier(p.identityHint) } : {}), + ...(RENEW_MODE && p.identityHint !== undefined ? { mode: 'renew' as const } : {}), + } +} + +export interface V2LoginRequest { + readonly request: AppConnectRequest + /** For the QR code: no callback (a shorter code, and the phone has no Forge tab to return to). */ + readonly qrUri: string + /** For a wallet on this device: the same request, with the callback when one was given. */ + readonly linkUri: string + /** `hash160(appEphemeralPub)`: what the answers are stored under (the callback's `r`). */ + readonly requestHash: Uint8Array + /** `CREATED_AT`, this device's clock (ms). */ + readonly createdAt: number + /** When the poll stops: the protocol's 10 minutes after `createdAt`. */ + readonly expiresAt: number + /** Chain time at `createdAt`: the verifier's clock is this plus the time elapsed here. */ + readonly chainTimeAtCreation: number + /** The identity a renewal is for (`IDENTITY_HINT`); null for a sign-in. */ + readonly identityHint: string | null + /** Held only in memory; zeroed by {@link disposeV2Request}. */ + readonly appEphemeralPriv: Uint8Array +} + +/** + * A fresh v2 request. `callbackUrl` builds the deep link's `cb` from the request hash (null: + * none); only {@link V2LoginRequest.linkUri} carries it. + */ +export function newV2LoginRequest( + network: Network, + forge: ForgeIds, + p: { + readonly connectionId: Uint8Array + readonly chainNow: number + readonly identityHint?: string + readonly now?: number + readonly callbackUrl?: (requestHash: Uint8Array) => string | null + }, +): V2LoginRequest { + const now = p.now ?? Date.now() + const priv = secp.utils.randomSecretKey() + const request = forgeV2Request(forge, { + appEphemeralPubKey: secp.getPublicKey(priv, true), + connectionId: p.connectionId, + chainNow: p.chainNow, + now, + ...(p.identityHint !== undefined ? { identityHint: p.identityHint } : {}), + }) + const requestHash = appConnectRequestHash(request) + const callback = p.callbackUrl?.(requestHash) + const qrUri = buildAppConnectUri(request, network) + return { + request, + qrUri, + linkUri: callback ? buildAppConnectUri(request, network, callback) : qrUri, + requestHash, + createdAt: now, + expiresAt: now + APP_CONNECT_MAX_REQUEST_AGE_MS, + chainTimeAtCreation: p.chainNow, + identityHint: p.identityHint ?? null, + appEphemeralPriv: priv, + } +} + +export function disposeV2Request(req: V2LoginRequest): void { + req.appEphemeralPriv.fill(0) +} + +/** Chain time (ms) and protocol version; this device's clock and null when the read fails. */ +export async function readChainClock(sdk: EvoSDK): Promise<{ readonly timeMs: number; readonly protocolVersion: number | null }> { + try { + const clock = await withTimeout(appConnectPort(sdk).chainClock(), PLATFORM_READ_MS, 'Reading the time on Platform') + if (Number.isSafeInteger(clock.timeMs) && clock.timeMs > 0) return clock + } catch { + /* fall back below */ + } + return { timeMs: Date.now(), protocolVersion: null } +} + +/** + * Whether a v2 request can be offered here: Forge is deployed on the network (its contract group + * exists) and the chain runs protocol 14 or later. The caller also runs the group check + * (`AuthController.checkGroup`) before showing a code. + */ +export async function appConnectV2Available(sdk: EvoSDK, network: Network): Promise { + if (NETWORKS[network].v2 === null) return false + const { protocolVersion } = await readChainClock(sdk) + return protocolVersion !== null && protocolVersion >= APP_CONNECT_MIN_PROTOCOL +} + +/** Why Forge refused a wallet's v2 answer, in a user's words. */ +const REFUSED: Partial> = { + 'key-disabled': 'The key your wallet sent is already disabled.', + 'key-expired': 'The key your wallet sent expires within the hour.', + 'budget-exhausted': 'The key your wallet sent has no budget left.', + 'key-limits': 'The key your wallet sent has no spending limit or no expiry.', + 'key-level': 'The key your wallet sent can do more than Forge asked for.', + 'key-master': 'Your wallet sent its master key.', + 'key-unmatched': 'The key your wallet sent is for something other than Dash Forge.', + 'key-unbound': 'The key your wallet sent is not limited to Dash Forge.', +} + +/** A wallet's v2 answer that Forge will not use (the verifier's `reason`). */ +export class WalletGrantRefused extends UnusableWalletKey { + constructor(readonly reason: AppConnectRejectReason) { + super(`${REFUSED[reason] ?? "Your wallet's answer doesn't match what Forge asked for."} Forge didn't use it. Start again; if it happens again, sign in another way.`) + this.name = 'WalletGrantRefused' + } +} + +/** More answers reached the request than Forge reads (junk): it cannot tell which is the user's. */ +export class TooManyAnswers extends Error { + constructor() { + super("So many answers reached this sign-in request that Forge can't check them all. Start again and keep the QR code private.") + this.name = 'TooManyAnswers' + } +} + +/** + * Cuts the poll's wait short: the UI fires it when the tab regains focus or the wallet's callback + * page says it answered. A fire while nothing waits makes the next wait return at once. + */ +export class PollTrigger { + private wake: (() => void) | null = null + private pending = false + + fire(): void { + if (this.wake) this.wake() + else this.pending = true + } + + /** Wait `ms`, or until fired; rejects with AbortError on `signal`. */ + wait(ms: number, signal?: AbortSignal): Promise { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(new DOMException('cancelled', 'AbortError')) + return + } + if (this.pending) { + this.pending = false + resolve() + return + } + const end = (): void => { + clearTimeout(t) + signal?.removeEventListener('abort', onAbort) + this.wake = null + } + const onAbort = (): void => { + end() + reject(new DOMException('cancelled', 'AbortError')) + } + const t = setTimeout(() => { + end() + resolve() + }, ms) + this.wake = () => { + end() + resolve() + } + signal?.addEventListener('abort', onAbort, { once: true }) + }) + } +} + +/** A verified v2 grant: the answering identity and its key, checked by Forge's own rules. */ +export interface V2Grant { + readonly identityId: string + readonly key: WalletKey +} + +/** Rejections that mean "not an answer to this request" (another request's, or tampered). */ +const NOT_AN_ANSWER: ReadonlySet = new Set(['decrypt', 'framing', 'hint-mismatch']) + +/** + * The verifier's grant as a {@link V2Grant}: its key as a WIF, read back and checked with + * {@link findWalletKey} (group-bound, AUTHENTICATION / HIGH, live, with its budget and expiry). + * Null when the node read does not show the key yet. The grant's private keys are zeroed. + */ +async function grantOf(sdk: EvoSDK, grant: AppConnectGrant, p: { readonly network: Network; readonly forge: ForgeIds }): Promise { + try { + const [main, ...others] = grant.authKeys + if (!main || others.length > 0 || grant.encryptionKeys.length > 0 || main.role !== 'contractGroup') throw new WalletGrantRefused('framing') + let key: WalletKey | null + try { + key = await findWalletKey(sdk, { identityId: grant.identityId, wif: encodeWif(main.privateKey, p.network), forge: p.forge, network: p.network }) + } catch (e) { + // Disabled since the verifier read it: v1's wording (a key derived the same every time) is wrong here. + throw e instanceof RevokedWalletKey ? new WalletGrantRefused('key-disabled') : e + } + if (key === null) return null + if (key.keyId !== main.key.id || isUnlimited(key) || key.scope.unbounded) throw new WalletGrantRefused('key-limits') + return { identityId: grant.identityId, key } + } finally { + for (const g of [...grant.authKeys, ...grant.encryptionKeys]) g.privateKey.fill(0) + } +} + +/** + * Poll the App Connect contract until an identity's answer to `req` is verified, then keep + * polling for `settleMs` for a competing answer before returning it; only rounds that read every + * answer count towards that window. Refuses ({@link AmbiguousWalletLogin}) when two identities + * answered: every answer that opens with this request's key counts, accepted or not, so an + * attacker's quick answer cannot win over the user's slow one. More answers than the poller reads + * is {@link TooManyAnswers}. + * + * A renewal (`req.identityHint`) reads only that identity's answer, so nothing can compete with + * it: no settle window, and its refusal is final at once. An answer whose key a node does not + * show yet (or whose budget it has not seen) is checked again on the next poll. + * + * Polls on the protocol's cadence ({@link appConnectPollDelayMs}: every 2 s for a minute, then + * every 4 s), at once when `trigger` fires. Rejects with {@link RequestExpired} after 10 minutes, + * AbortError on `signal`, {@link WalletGrantRefused} (or another {@link UnusableWalletKey}) for + * the sole answer Forge will not use. The request is spent either way ({@link disposeV2Request}). + */ +export async function awaitV2Grant( + sdk: EvoSDK, + req: V2LoginRequest, + p: { + readonly network: Network + readonly forge: ForgeIds + readonly signal?: AbortSignal + readonly trigger?: PollTrigger + readonly intervalMs?: number + readonly settleMs?: number + readonly now?: () => number + readonly onStatus?: (status: PollStatus) => void + }, +): Promise { + const now = p.now ?? Date.now + const hint = req.identityHint ?? undefined + const settleMs = hint !== undefined ? 0 : (p.settleMs ?? 3000) + const trigger = p.trigger ?? new PollTrigger() + const port = appConnectPort(sdk) + /** Per answering identity: its grant, null (check again), or why Forge will not use it. */ + const answered = new Map() + /** Every identity whose answer opened with this request's key. */ + const responders = new Set() + /** Answers already found not to be answers to this request, by exact contents. */ + const notAnswers = new Set() + let cleanSince = 0 + let firstAt = 0 + try { + for (;;) { + if (p.signal?.aborted) throw new DOMException('cancelled', 'AbortError') + // A failed read is never "no answers": the round does not count towards the settle window. + const page = await listAppConnectCandidates(port, req.requestHash, hint !== undefined ? { hint } : {}).catch(() => null) + if (page?.truncated) throw new TooManyAnswers() + const complete = page !== null + for (const c of page?.candidates ?? []) { + const prior = answered.get(c.ownerId) + if (prior !== undefined && prior !== null) continue + const contents = appConnectCandidateKey(c) + if (notAnswers.has(contents)) continue + let answer: V2Grant | UnusableWalletKey | null = null + try { + const chainNow = req.chainTimeAtCreation + (now() - req.createdAt) + const verdict = await verifyAppConnectCandidate({ request: req.request, appEphemeralPrivateKey: req.appEphemeralPriv, candidate: c, identity: port, now: chainNow }) + if (!verdict.ok && NOT_AN_ANSWER.has(verdict.reason)) { + notAnswers.add(contents) + continue + } + // It opened: this identity saw the QR and answered, whatever its key turns out to be. + responders.add(c.ownerId) + if (verdict.ok) answer = await grantOf(sdk, verdict.grant, { network: p.network, forge: p.forge }) + else if (!verdict.retryable) answer = new WalletGrantRefused(verdict.reason) + } catch (e) { + // Only reads fail past the decryption: this identity answered; check it again next poll. + responders.add(c.ownerId) + if (e instanceof UnusableWalletKey) answer = e + } + // The one identity a renewal listens to: its refusal is final. + if (answer instanceof UnusableWalletKey && hint !== undefined) throw answer + answered.set(c.ownerId, answer) + if (answer !== null && firstAt === 0) firstAt = now() + } + if (responders.size > 1) throw new AmbiguousWalletLogin([...responders]) + const t = now() + if (complete) { + if (cleanSince === 0) cleanSince = t + } else { + cleanSince = 0 + } + p.onStatus?.(!complete ? 'incomplete-read' : firstAt !== 0 ? 'answered' : 'waiting') + const only = [...answered.values()].find((a) => a !== null) + if (only && cleanSince !== 0 && t - Math.max(firstAt, cleanSince) >= settleMs) { + if (only instanceof UnusableWalletKey) throw only + return only + } + const delay = p.intervalMs ?? appConnectPollDelayMs(t - req.createdAt) + if (t >= req.expiresAt || delay === null) throw new RequestExpired() + await trigger.wait(delay, p.signal) + } + } finally { + disposeV2Request(req) + } +} diff --git a/forge-web/lib/auth/connect-callback.test.ts b/forge-web/lib/auth/connect-callback.test.ts new file mode 100644 index 000000000..0cf112944 --- /dev/null +++ b/forge-web/lib/auth/connect-callback.test.ts @@ -0,0 +1,169 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it, vi } from 'vitest' +import { buildAppConnectUri, parseAppConnectUri } from '../vendor/platform-auth/app-connect' +import { + CALLBACK_CHANNEL, + CALLBACK_STATUS_COPY, + callbackStatusCopy, + connectCallbackUrl, + isConnectCallbackAck, + isConnectCallbackMessage, + listenForCallback, + parseConnectCallback, +} from './connect-callback' +import { newV2LoginRequest } from './app-connect-v2' +import type { ForgeIds } from '../deployments' + +const HASH = new Uint8Array(20).fill(0xab) +const HEX = 'ab'.repeat(20) +const SITE = 'https://forge.dashhq.org/' +const FORGE: ForgeIds = { + core: 'A2KL77ngVM1ft1t1em2XKt1rWCBZANdAJMyfWrDGCcd1', + collab: 'C1zHeeG7EUudXdB5ZyDQnXVU35hrCfvd1fRCybXEqaPS', + community: 'C1zHeeG7EUudXdB5ZyDQnXVU35hrCfvd1fRCybXEqaPS', + group: '6dV3kMBWHGR7pLKrHToMBQgbTpjqeE2VAyCEWmLbrkWC', +} + +afterEach(() => vi.restoreAllMocks()) + +describe('connectCallbackUrl', () => { + it('points at /connect/ on the canonical site with the request hash', () => { + expect(connectCallbackUrl(HASH, { siteUrl: SITE, origin: 'https://forge.dashhq.org', ipfs: false })).toBe(`${SITE}connect/?r=${HEX}`) + }) + + it('keeps a base path', () => { + expect(connectCallbackUrl(HASH, { siteUrl: 'https://example.org/dash-forge/', origin: 'https://example.org', ipfs: false })).toBe(`https://example.org/dash-forge/connect/?r=${HEX}`) + }) + + it('is omitted on an IPFS build', () => { + expect(connectCallbackUrl(HASH, { siteUrl: SITE, origin: 'https://forge.dashhq.org', ipfs: true })).toBeNull() + }) + + it('is omitted when this page is not on the canonical origin', () => { + expect(connectCallbackUrl(HASH, { siteUrl: SITE, origin: 'https://bafy.ipfs.dweb.link', ipfs: false })).toBeNull() + expect(connectCallbackUrl(HASH, { siteUrl: SITE, origin: null, ipfs: false })).toBeNull() + }) + + it('is omitted when the site is not https (the profile requires it)', () => { + expect(connectCallbackUrl(HASH, { siteUrl: 'http://localhost:3000/', origin: 'http://localhost:3000', ipfs: false })).toBeNull() + }) + + it('rides on the request as cb, and only on the link', () => { + const req = newV2LoginRequest('devnet', FORGE, { + connectionId: new Uint8Array(16).fill(1), + chainNow: 1_700_000_000_000, + callbackUrl: (h) => connectCallbackUrl(h, { siteUrl: SITE, origin: 'https://forge.dashhq.org', ipfs: false }), + }) + expect(parseAppConnectUri(req.qrUri).callbackUrl).toBeUndefined() + const link = parseAppConnectUri(req.linkUri).callbackUrl + expect(link).toMatch(/^https:\/\/forge\.dashhq\.org\/connect\/\?r=[0-9a-f]{40}$/) + expect(link?.endsWith(Buffer.from(req.requestHash).toString('hex'))).toBe(true) + expect(req.linkUri).toBe(buildAppConnectUri(req.request, 'devnet', link)) + }) +}) + +describe('parseConnectCallback', () => { + it('reads the request hash and status', () => { + expect(parseConnectCallback(`?r=${HEX}&ac=ok`)).toEqual({ requestHash: HEX, status: 'ok' }) + expect(parseConnectCallback(`?ac=declined&r=${HEX.toUpperCase()}`)).toEqual({ requestHash: HEX, status: 'declined' }) + expect(parseConnectCallback(`?r=${HEX}`)).toEqual({ requestHash: HEX, status: null }) + }) + + it('refuses anything that is not a request hash', () => { + expect(parseConnectCallback('')).toBeNull() + expect(parseConnectCallback('?r=not-a-hash&ac=ok')).toBeNull() + expect(parseConnectCallback(`?r=${HEX}00`)).toBeNull() + }) + + it('drops a status of the wrong shape', () => { + expect(parseConnectCallback(`?r=${HEX}&ac=