From a4ea1515c226ca9dbed851c60d0ec5395d6a60cf Mon Sep 17 00:00:00 2001 From: pasta Date: Mon, 5 Oct 2026 02:16:30 -0400 Subject: [PATCH 1/7] feat(web): keep the wallet-derived encryption key in the vault and unlock once per tab MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A wallet login now seals the encryption key its login key stands for (HKDF(loginKey, identityId, "encryption"), the key the wallet registers beside the auth key) into the vault beside the wallet key, at the first login and at a returning one, but only when its public key is the identity's usable ENCRYPTION key. Otherwise nothing is stored and the sign-in says: Your encryption key is held elsewhere. Import it under Settings → Private repos. The unlock was already per tab: one passkey or passphrase gesture opens the encryption key for every repo. UNLOCK_MEMBERS_ONLY and encryptionKeyState give members-only content the same prompt. Session persistence is unchanged: only the spend-capped key survives a reload. Co-Authored-By: Claude Opus 5.5 (1M context) --- forge-web/components/auth/unlock-more.tsx | 8 + .../auth/wallet-connect-flow.test.tsx | 26 +- .../components/auth/wallet-connect-flow.tsx | 77 +++-- forge-web/lib/auth/app-connect.ts | 53 +++- forge-web/lib/auth/controller.ts | 41 ++- forge-web/lib/auth/encryption-key.ts | 76 ++++- forge-web/lib/auth/wallet-encryption.test.ts | 289 ++++++++++++++++++ forge-web/lib/auth/wallet-login.live.test.ts | 62 +++- forge-web/lib/auth/wallet-protocol.test.ts | 12 +- 9 files changed, 587 insertions(+), 57 deletions(-) create mode 100644 forge-web/lib/auth/wallet-encryption.test.ts diff --git a/forge-web/components/auth/unlock-more.tsx b/forge-web/components/auth/unlock-more.tsx index 603976721..017a3726e 100644 --- a/forge-web/components/auth/unlock-more.tsx +++ b/forge-web/components/auth/unlock-more.tsx @@ -16,6 +16,14 @@ import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { errorMessage } from '@/lib/utils' +/** + * The prompt over members-only content this tab cannot read yet (DESIGN §4.8, §10): + * ``. The unlock is per tab, not per repo: one gesture + * opens the encryption key for every repo in the tab (`encryptionKeyState` says whether it is + * needed), and every private read re-resolves when `useAuth().unlockScope` turns `full`. + */ +export const UNLOCK_MEMBERS_ONLY = 'Unlock to read members-only content' + export function UnlockMore({ title, testId = 'unlock-more', diff --git a/forge-web/components/auth/wallet-connect-flow.test.tsx b/forge-web/components/auth/wallet-connect-flow.test.tsx index 3473e02e9..12d3b216d 100644 --- a/forge-web/components/auth/wallet-connect-flow.test.tsx +++ b/forge-web/components/auth/wallet-connect-flow.test.tsx @@ -1,7 +1,8 @@ // @vitest-environment jsdom /** * 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. + * 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). */ import { act } from 'react' @@ -9,9 +10,11 @@ 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 } = vi.hoisted(() => ({ +const { ID, FORGE, answered } = 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[] }, })) const FAKE_VAULT_PASSPHRASE = 'fake-vault-passphrase-000' const FAKE_RENEWAL_PASSPHRASE = 'fake-renewal-passphrase-789' @@ -30,7 +33,10 @@ vi.mock('@/lib/auth/app-connect', async (importOriginal) => ({ ...(await importOriginal()), responseSources: async () => [{}], newLoginRequest: () => ({ uri: 'dash-key:fake', expiresAt: Date.now() + 60_000 }), - awaitWalletAnswer: async () => ({ kind: 'keys', identityId: ID, keys: [{ scope: {}, limits: {} }] }), + awaitWalletAnswer: async () => { + answered.keys = [new Uint8Array(32).fill(0x42)] + return { kind: 'keys', identityId: ID, keys: [{ scope: {}, limits: {} }], encryptionKeys: answered.keys } + }, })) vi.mock('@/lib/auth/key-registration', async (importOriginal) => ({ ...(await importOriginal()), @@ -99,7 +105,21 @@ describe('WalletConnectFlow: a locked unfinished renewal', () => { expect(adoptWalletKeys).toHaveBeenLastCalledWith(ID, expect.anything(), expect.anything(), { discardPendingRenewal: true, renewalUnlock: { passphrase: FAKE_RENEWAL_PASSPHRASE }, + encryptionKeys: answered.keys, + justRegistered: false, }) expect(onDone).toHaveBeenCalled() + // Passed intact on each of the three attempts, and wiped once signed in. + expect(adoptWalletKeys).toHaveBeenCalledTimes(3) + expect(answered.keys[0]!.every((b) => b === 0)).toBe(true) + }) + + it("wipes the wallet's encryption key when the sheet closes before signing in", async () => { + act(() => root.render()) + await flush() + expect(host.querySelector('[data-testid="wallet-confirm"]')).not.toBeNull() + expect(answered.keys[0]!.every((b) => b === 0x42)).toBe(true) + act(() => root.render(<>)) + expect(answered.keys[0]!.every((b) => b === 0)).toBe(true) }) }) diff --git a/forge-web/components/auth/wallet-connect-flow.tsx b/forge-web/components/auth/wallet-connect-flow.tsx index 2aeb9a1b8..b0b4ddfc4 100644 --- a/forge-web/components/auth/wallet-connect-flow.tsx +++ b/forge-web/components/auth/wallet-connect-flow.tsx @@ -20,7 +20,9 @@ * 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. * - * Granted keys are held in refs, never React state, and dropped when the sheet closes. + * Granted keys are held in refs, never React state, and dropped when the sheet closes. So is the + * encryption key the wallet's login key stands for: signing in seals it into the vault beside the + * wallet key when it is the identity's (DESIGN D27), and the bytes are wiped once the sheet is done. */ import { useCallback, useEffect, useRef, useState } from 'react' @@ -35,7 +37,18 @@ import { Qr } from '@/components/ui/qr' import { ErrorBox, useProtection } from '@/components/auth/protection-fields' import { Waiting } from '@/components/auth/step-status' import { ACTIVE_NETWORK } from '@/lib/constants' -import { REQUEST_TTL_MS, RequestExpired, awaitRegisteredKey, awaitWalletAnswer, newLoginRequest, responseSources, walletSignInSupported, type PollStatus } from '@/lib/auth/app-connect' +import { + REQUEST_TTL_MS, + RequestExpired, + awaitRegisteredKey, + awaitWalletAnswer, + newLoginRequest, + responseSources, + walletSignInSupported, + wipeAnswer, + type PollStatus, + type WalletAnswer, +} from '@/lib/auth/app-connect' import { isUnlimited, keyRegistrationUri, scopeCovers, type WalletKey } from '@/lib/auth/key-registration' import { responderProfile, type ResponderProfile } from '@/lib/auth/responder-profile' import { isAbort } from '@/lib/sdk/facade' @@ -96,7 +109,12 @@ 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[] } | null>(null) + const grant = useRef<{ identityId: string; keys: readonly WalletKey[]; answer: WalletAnswer } | null>(null) + /** Wipe the held answer's private key bytes and drop the grant. */ + const dropGrant = useCallback(() => { + if (grant.current) wipeAnswer(grant.current.answer) + grant.current = null + }, []) const mobile = onMobile() const unlimited = step?.kind === 'confirm' && step.unlimited const { fields, protection, problem } = useProtection({ preferPasskey: unlimited }) @@ -126,8 +144,10 @@ export function WalletConnectFlow({ onDone, mode = 'login', contractId }: { onDo discardPendingRenewal: discard, ...(renewalUnlock ? { renewalUnlock } : {}), ...(drop ? { dropUnopened: true } : {}), + encryptionKeys: g.answer.encryptionKeys, + justRegistered: g.answer.kind === 'register', }) - grant.current = null + dropGrant() setPendingRenewal(null) setRenewalLocked(null) if (renewalPassphraseRef.current) renewalPassphraseRef.current.value = '' @@ -173,27 +193,34 @@ export function WalletConnectFlow({ onDone, mode = 'login', contractId }: { onDo ...(mode === 'grant' && grantFor ? { identityId: grantFor } : {}), }) let keys: readonly WalletKey[] - if (answer.kind === 'register') { - // First login from this wallet: QR #2 registers the key, then wait for it on chain. - const until = Date.now() + REQUEST_TTL_MS - const uri = await keyRegistrationUri(sdk, { identityId: answer.identityId, keys: answer.keys, contractId: target, network: ACTIVE_NETWORK.network }) - if (signal.aborted) return - setStep({ kind: 'register', uri, expiresAt: until }) - keys = [await awaitRegisteredKey(sdk, { identityId: answer.identityId, wif: answer.wif, network: ACTIVE_NETWORK.network, forge, until, signal })] - } else { - keys = answer.keys - } - if (signal.aborted) return - if (mode === 'grant') { - // The key that covers what was asked for (a wallet may grant several, or the wrong one). - const key = keys.find((k) => scopeCovers(k.scope, forge, target)) - if (!key) throw new Error("The wallet's answer does not cover issues and pull requests. Try again, or sign in with your identity file.") - await latest.current.addWalletGrant(answer.identityId, key, target) + // Its private key bytes are wiped here unless the confirm step holds them (`grant`). + let held = false + try { + if (answer.kind === 'register') { + // First login from this wallet: QR #2 registers the key, then wait for it on chain. + const until = Date.now() + REQUEST_TTL_MS + const uri = await keyRegistrationUri(sdk, { identityId: answer.identityId, keys: answer.keys, contractId: target, network: ACTIVE_NETWORK.network }) + if (signal.aborted) return + setStep({ kind: 'register', uri, expiresAt: until }) + keys = [await awaitRegisteredKey(sdk, { identityId: answer.identityId, wif: answer.wif, network: ACTIVE_NETWORK.network, forge, until, signal })] + } else { + keys = answer.keys + } if (signal.aborted) return - latest.current.onDone() - return + if (mode === 'grant') { + // The key that covers what was asked for (a wallet may grant several, or the wrong one). + const key = keys.find((k) => scopeCovers(k.scope, forge, target)) + if (!key) throw new Error("The wallet's answer does not cover issues and pull requests. Try again, or sign in with your identity file.") + await latest.current.addWalletGrant(answer.identityId, key, target) + if (signal.aborted) return + latest.current.onDone() + return + } + grant.current = { identityId: answer.identityId, keys, answer } + held = true + } finally { + if (!held) wipeAnswer(answer) } - grant.current = { identityId: answer.identityId, keys } const profile = await responderProfile(sdk, answer.identityId, ACTIVE_NETWORK.network, latest.current.stored) if (signal.aborted) return setStep({ kind: 'confirm', profile, unlimited: keys.some(isUnlimited), unbounded: keys.some((k) => k.scope.unbounded) }) @@ -205,10 +232,10 @@ export function WalletConnectFlow({ onDone, mode = 'login', contractId }: { onDo })() return () => { controller.abort() - grant.current = null + dropGrant() } // `attempt` restarts the whole request (a new ephemeral key and QR). - }, [attempt, forge, target, mode, grantFor]) + }, [attempt, forge, target, mode, grantFor, dropGrant]) const restart = useCallback(() => setAttempt((a) => a + 1), []) diff --git a/forge-web/lib/auth/app-connect.ts b/forge-web/lib/auth/app-connect.ts index aab6d7ff6..81acfda99 100644 --- a/forge-web/lib/auth/app-connect.ts +++ b/forge-web/lib/auth/app-connect.ts @@ -38,7 +38,7 @@ import { hash160 } from './asset-lock' import { base58Decode } from './base58' import { findWalletKey, loginKeys, scopeCovers, UnusableWalletKey, type LoginKeys, type WalletKey } from './key-registration' import { encodeWif } from './wif' -import { authKeyFromLogin, encodeKeyRequest, openEnvelope, protocolUri } from './wallet-protocol' +import { authKeyFromLogin, encodeKeyRequest, encryptionKeyFromLogin, openEnvelope, protocolUri } from './wallet-protocol' /** The App Connect system contract (the same id on every network, protocol 14). */ export const APP_CONNECT_CONTRACT_ID = 'H8F9mP1BM55TE1ShsxPZHzhyinaMdY9bMmP85mkDhcJJ' @@ -216,12 +216,37 @@ async function appConnectRows(sdk: EvoSDK, hash: string): Promise { const found: WalletKey[] = [] + /** The encryption key of each login key whose auth key was found. */ + const encryption: Uint8Array[] = [] let unregistered: { keys: LoginKeys; wif: string } | null = null /** A key of this answer Forge must not use; thrown only if the answer has no usable key. */ let refused: UnusableWalletKey | null = null @@ -279,11 +306,14 @@ async function answerFor(sdk: EvoSDK, r: WalletResponse, loginKeysRaw: Uint8Arra refused = e continue } - if (key) found.push(key) - else if (r.source === 'legacy') unregistered = { keys: loginKeys(login, r.ownerId), wif } + if (key) { + found.push(key) + encryption.push(encryptionKeyFromLogin(login, r.ownerId)) + } else if (r.source === 'legacy') unregistered = { keys: loginKeys(login, r.ownerId), wif } } } catch (e) { zeroLoginKeys(unregistered?.keys) + for (const k of encryption) k.fill(0) throw e } finally { for (const k of loginKeysRaw) k.fill(0) @@ -292,13 +322,16 @@ async function answerFor(sdk: EvoSDK, r: WalletResponse, loginKeysRaw: Uint8Arra zeroLoginKeys(unregistered?.keys) // The key for the contract asked for first. found.sort((a, b) => Number(scopeCovers(b.scope, p.forge, p.contractId)) - Number(scopeCovers(a.scope, p.forge, p.contractId))) - return { kind: 'keys', identityId: r.ownerId, keys: found, source: r.source } + return { kind: 'keys', identityId: r.ownerId, keys: found, encryptionKeys: encryption, source: r.source } } if (refused) { zeroLoginKeys(unregistered?.keys) throw refused } - if (unregistered) return { kind: 'register', identityId: r.ownerId, ...unregistered, source: 'legacy' } + if (unregistered) { + // A copy: QR #2 wipes the login keys once its transition is built. + return { kind: 'register', identityId: r.ownerId, ...unregistered, encryptionKeys: [new Uint8Array(unregistered.keys.encPriv)], source: 'legacy' } + } return null } @@ -395,8 +428,8 @@ export async function awaitWalletAnswer( } } finally { disposeRequest(req) - // Registration keys of answers not handed back. - for (const a of answered.values()) if (a && !(a instanceof Error) && a !== result && a.kind === 'register') zeroLoginKeys(a.keys) + // The private keys of answers not handed back. + for (const a of answered.values()) if (a && !(a instanceof Error) && a !== result) wipeAnswer(a) } } diff --git a/forge-web/lib/auth/controller.ts b/forge-web/lib/auth/controller.ts index 55f6195ce..ad1018765 100644 --- a/forge-web/lib/auth/controller.ts +++ b/forge-web/lib/auth/controller.ts @@ -46,6 +46,7 @@ import { PLATFORM_READ_MS, withPlatformRead } from './connect' import { withTimeout } from '../timeout' import { clearLedger } from '../spend' import { clearInbox } from '../view/inbox' +import { ENCRYPTION_KEY_ELSEWHERE, adoptWalletEncryptionKey } from './encryption-key' import { clearDrafts } from '../view/draft-text' import { forgetLastIdentity, rememberLastIdentity } from './last-identity' import { checkWalletKey, hasNoLimits, isForgeContract, keyScope, scopeCovers, type KeyScope, type WalletKey } from './key-registration' @@ -898,8 +899,8 @@ export class AuthController { } /** Tell the user what a renewal could not carry over (one notice, both parts). */ - private noteDropped(outcome: StoreOutcome, storageText: string): void { - const parts = [...(outcome.storageSettingsDropped ? [storageText] : []), ...(outcome.encryptionKeyDropped ? [ENCRYPTION_KEY_DROPPED] : [])] + private noteDropped(outcome: StoreOutcome, storageText: string, extra: string | null = null): void { + const parts = [...(outcome.storageSettingsDropped ? [storageText] : []), ...(outcome.encryptionKeyDropped ? [ENCRYPTION_KEY_DROPPED] : []), ...(extra !== null ? [extra] : [])] if (parts.length > 0) this.setState({ notice: parts.join(' ') }) } @@ -962,6 +963,14 @@ export class AuthController { readonly renewalUnlock?: { passphrase: string } | 'passkey' /** Give it up even though it cannot be opened (its key then stays live until it expires). */ readonly dropUnopened?: boolean + /** + * The encryption private keys the wallet's login keys stand for (`WalletAnswer`): the one + * the identity uses is sealed beside the wallet key (DESIGN D27). Copied, not wiped: the + * caller wipes them. + */ + readonly encryptionKeys?: readonly Uint8Array[] + /** The wallet registered its keys just now (QR #2): a node may not show them yet. */ + readonly justRegistered?: boolean } = {}, ): Promise { return this.run(async () => { @@ -1014,9 +1023,13 @@ export class AuthController { const kept = [...held, ...(given ? [given] : [])].filter((h, i, all) => !fresh.has(h.keyId) && all.findIndex((x) => x.keyId === h.keyId) === i) const extra = [...rest.map((k) => toExtraKey(k, forge)), ...kept] const secret: VaultSecret = { identityId, keyId: main.keyId, wif: main.wif, ...(extra.length ? { extra } : {}) } + const stored = await storeInVault(this.network, secret, protection, pending !== null ? { dropStagedKeyId: pending.keyId } : {}) + const encryption = await this.keepWalletEncryptionKey(identityId, forge, options) this.noteDropped( - await storeInVault(this.network, secret, protection, pending !== null ? { dropStagedKeyId: pending.keyId } : {}), + // An encryption key the vault could not carry over is replaced by the wallet's own. + encryption.stored ? { ...stored, encryptionKeyDropped: false } : stored, 'Your storage settings could not be carried over to the new key. Add your storage again in Settings → Storage.', + encryption.notice, ) try { return await this.open(secret, 'vault', main.limits ?? undefined) @@ -1025,6 +1038,28 @@ export class AuthController { } } + /** + * Seal the encryption key a wallet login stands for beside the wallet key just stored, when it + * is the identity's (DESIGN D27, {@link adoptWalletEncryptionKey}). Signing in never fails on + * it: `notice` says why private repos were not enabled (another key is the identity's, or a read + * failed), and nothing is stored then. + */ + private async keepWalletEncryptionKey( + identityId: string, + forge: ForgeIds, + options: { readonly encryptionKeys?: readonly Uint8Array[]; readonly justRegistered?: boolean }, + ): Promise<{ readonly stored: boolean; readonly notice: string | null }> { + if (!options.encryptionKeys?.length) return { stored: false, notice: null } + this.step('Enabling private repos') + try { + const sdk = await this.getSdk() + const outcome = await adoptWalletEncryptionKey(sdk, this.network, identityId, forge.core, options.encryptionKeys, options.justRegistered === true ? { attempts: 5 } : {}) + return { stored: outcome.kind === 'stored', notice: outcome.kind === 'elsewhere' ? ENCRYPTION_KEY_ELSEWHERE : null } + } catch (e) { + return { stored: false, notice: `Signed in, but private repos could not be enabled: ${errorMessage(e)}.` } + } + } + /** * Add a wallet grant for another Forge contract to the signed-in identity (a shipped wallet * grants one contract per approval). The key must belong to the session's identity. diff --git a/forge-web/lib/auth/encryption-key.ts b/forge-web/lib/auth/encryption-key.ts index 00abc6144..fba5640d1 100644 --- a/forge-web/lib/auth/encryption-key.ts +++ b/forge-web/lib/auth/encryption-key.ts @@ -6,8 +6,9 @@ * ECDSA_SECP256K1, and unbound or bound to forge-core. Writers wrap to the recipient's * highest-id usable key and record its id ({@link usableEncryptionKey}). * - Getting it into the vault: from an identity file (its ENCRYPTION key, or derived from its - * mnemonic), a recovery phrase, or a pasted WIF/hex key. Every route checks that the public - * key matches an enabled ENCRYPTION key on the identity before anything is stored. + * mnemonic), a recovery phrase, a pasted WIF/hex key, or a wallet login (the key its login + * key stands for, {@link adoptWalletEncryptionKey}). Every route checks that the public key + * matches an enabled ENCRYPTION key on the identity before anything is stored. * - Registering one (Settings → Private repos): an `IdentityUpdate` signed once by * the master key, adding the next key id, derived from the recovery phrase at * `m/9'/'/5'/0'/0'/'/'` (the CLI's path, so either client can @@ -17,6 +18,7 @@ * reaches React, storage outside the vault, a URL or a log. */ +import * as secp from '@noble/secp256k1' import type { DataContract, Document, EvoSDK, IdentityPublicKey, PrivateKey as WasmPrivateKey } from '@dashevo/evo-sdk' import type { Network } from '../constants' @@ -114,6 +116,76 @@ export async function adoptEncryptionKey(sdk: EvoSDK, network: Network, identity } } +/** + * A wallet login's encryption key is not the one the identity uses (it registered another from + * `dg`, say), so it was not kept. Shown at sign-in. + */ +export const ENCRYPTION_KEY_ELSEWHERE = 'Your encryption key is held elsewhere. Import it under Settings → Private repos.' + +/** What became of the encryption key a wallet login stands for ({@link adoptWalletEncryptionKey}). */ +export type WalletEncryptionOutcome = + /** It is the identity's usable encryption key, now sealed in the vault. */ + | { readonly kind: 'stored'; readonly keyId: number } + /** It is not, and the vault already holds the one the identity uses. */ + | { readonly kind: 'held'; readonly keyId: number } + /** It is not, and this browser does not hold the one the identity uses ({@link ENCRYPTION_KEY_ELSEWHERE}). */ + | { readonly kind: 'elsewhere'; readonly keyId: number } + /** The identity has no usable encryption key. */ + | { readonly kind: 'none' } + +/** + * Keep the encryption key a wallet login stands for (DESIGN D27): the wallet derives + * `HKDF(loginKey, identityId, "encryption")` for each login key and registers it beside the auth + * key at the first login, and a returning login derives the same one. `candidates` are those + * private keys. One is sealed into the vault (beside the wallet key, under the same protection) + * only when its public key is the identity's usable encryption key, the one writers wrap to + * ({@link usableEncryptionKey}). Anything else would be a key no wrap is sealed to, so nothing is + * stored. `attempts` re-reads the identity while none of the candidates is on it yet (a node a + * block behind the wallet's registration). Copies are taken: the caller still wipes `candidates`. + */ +export async function adoptWalletEncryptionKey( + sdk: EvoSDK, + network: Network, + identityId: string, + coreId: string, + candidates: readonly Uint8Array[], + options: { readonly attempts?: number; readonly intervalMs?: number } = {}, +): Promise { + const secrets = candidates.filter((c) => c.length === 32).map((c) => new Uint8Array(c)) + try { + const pubs = secrets.map((s) => bytesToHex(secp.getPublicKey(s, true))) + for (let attempt = 1; ; attempt++) { + const keys = await timed(PRIVATE_REPOS_FLOW, 'read identity keys (wallet)', () => requireIdentityKeys(sdk, identityId)) + const usable = usableEncryptionKey(keys, coreId) + const at = usable === null ? -1 : pubs.indexOf(usable.data.toLowerCase()) + if (usable !== null && at >= 0) { + await timed(PRIVATE_REPOS_FLOW, 'seal into the vault', () => storeEncryptionKey(network, identityId, usable.keyId, secrets[at] as Uint8Array)) + return { kind: 'stored', keyId: usable.keyId } + } + const onChain = keys.some((k) => k.purposeNumber === PURPOSE_ENCRYPTION && pubs.includes(k.data.toLowerCase())) + if (!onChain && attempt < (options.attempts ?? 1)) { + await sleep(options.intervalMs ?? 1500) + continue + } + if (usable === null) return { kind: 'none' } + if ((await storedEncryptionKeyId(network, identityId)) === usable.keyId) return { kind: 'held', keyId: usable.keyId } + return { kind: 'elsewhere', keyId: usable.keyId } + } + } finally { + for (const s of secrets) s.fill(0) + } +} + +/** + * Whether this tab can use the encryption key of (network, identity) now: `open` (unlocked), + * `locked` (stored, but this tab must unlock first: one passkey or passphrase gesture opens it + * for every repo in the tab), or `none` (this browser holds none). Readable while locked. + */ +export async function encryptionKeyState(network: Network, identityId: string): Promise<'open' | 'locked' | 'none'> { + if ((await storedEncryptionKeyId(network, identityId)) === null) return 'none' + return unlockScope(network, identityId) === 'full' ? 'open' : 'locked' +} + /** A pasted WIF or 64-hex private key → the 32 bytes (the caller wipes them). */ export function parseEncryptionKeyInput(input: string): Uint8Array { return parsePrivateKey(input).privateKey diff --git a/forge-web/lib/auth/wallet-encryption.test.ts b/forge-web/lib/auth/wallet-encryption.test.ts new file mode 100644 index 000000000..259c94bea --- /dev/null +++ b/forge-web/lib/auth/wallet-encryption.test.ts @@ -0,0 +1,289 @@ +/** + * A wallet login keeps the encryption key its login key stands for (DESIGN D27, §4.8): sealed + * into the vault beside the wallet key when it is the identity's usable ENCRYPTION key, at the + * first login and at a returning one; after a reload one unlock opens it for every repo in the + * tab; and when the identity uses another key (registered from `dg`), nothing is stored and the + * sign-in says where to import it. The chain is a fake; the vault is the real one (in-memory + * IndexedDB), behind a fake window whose passkey counts its prompts. + */ + +import * as secp from '@noble/secp256k1' +import { bytesToHex } from '@noble/hashes/utils.js' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { EvoSDK } from '@dashevo/evo-sdk' + +import { NETWORKS } from '../constants' +import { idbEntries, resetMemoryStores } from '../idb' +import { AuthController } from './controller' +import { ENCRYPTION_KEY_ELSEWHERE, adoptWalletEncryptionKey, encryptionKeyState, encryptionOps } from './encryption-key' +import type { WalletKey } from './key-registration' +import { lockVault, releaseUnlocked, storeEncryptionKey, storeInVault, storedEncryptionKeyId, withEncryptionKey } from './vault' +import { encryptionKeyFromLogin } from './wallet-protocol' +import { decodeWif, 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 SDK's private key only carries its bytes here; an unwrap reports the key it was handed. +vi.mock('@dashevo/evo-sdk', () => ({ + PrivateKey: { + fromWIF: (wif: string) => ({ toBytes: () => new TextEncoder().encode(wif), free: () => undefined }), + fromBytes: (b: Uint8Array) => ({ hex: Array.from(b, (x) => x.toString(16).padStart(2, '0')).join(''), free: () => undefined }), + }, + Document: { fromJSON: (j: unknown) => j }, +})) +vi.mock('../private', async (orig) => ({ + ...(await orig()), + unwrapKey: async (_facade: unknown, p: { readerPrivateKey: { hex: string }; repoId: Uint8Array }) => ({ reader: p.readerPrivateKey.hex, repo: bytesToHex(p.repoId) }), +})) + +interface FakeKey { + keyId: number + wif?: string + purposeNumber: number + securityLevelNumber: number + keyTypeNumber: number + data: string + disabledAt?: bigint + contractBounds?: { toJSON(): { $type: string; id: string } } + validatePrivateKey(bytes: Uint8Array): boolean +} + +const NET = 'devnet' as const +const FORGE = NETWORKS[NET].v2! +const ID = 'HwhCv9N5BHsbGNLzDR4tnZnqJ6VxtwJSLsM4aUWn2Tnr' +const AUTH_WIF = encodeWif(new Uint8Array(32).fill(5), NET) +/** The wallet's login key and the encryption key it stands for (what the wallet registers). */ +const LOGIN = new Uint8Array(32).fill(0x11) +const WALLET_ENC = encryptionKeyFromLogin(LOGIN, ID) +/** A key registered from `dg`: not the wallet's. */ +const DG_ENC = new Uint8Array(32).fill(0x33) +const pub = (priv: Uint8Array): string => bytesToHex(secp.getPublicKey(priv, true)) + +/** 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 } } +let gestures = 0 + +function fakeWindow(): unknown { + const data = new Map() + const localStorage = { + get length() { + return data.size + }, + key: (i: number) => [...data.keys()][i] ?? null, + getItem: (k: string) => data.get(k) ?? null, + setItem: (k: string, v: string) => void data.set(k, String(v)), + removeItem: (k: string) => void data.delete(k), + clear: () => data.clear(), + } + const win: Record = { + localStorage, + location: { hostname: 'forge.dashhq.org', pathname: '/' }, + addEventListener: () => undefined, + isSecureContext: true, + PublicKeyCredential: function PublicKeyCredential() {}, + } + win.top = win + win.self = win + return win +} + +const fakeNavigator = { + credentials: { + get: async () => { + gestures += 1 + return { + rawId: new Uint8Array([1]).buffer, + getClientExtensionResults: () => ({ prf: { results: { first: PRF.slice().buffer, second: PRF.slice().buffer } } }), + } + }, + }, +} + +function authKey(keyId: number, wif: string): FakeKey { + return { + keyId, + wif, + purposeNumber: 0, + securityLevelNumber: 2, + keyTypeNumber: 2, + data: '', + contractBounds: { toJSON: () => ({ $type: 'singleContract', id: FORGE.core }) }, + validatePrivateKey: (bytes) => bytesToHex(bytes) === bytesToHex(decodeWif(wif).privateKey), + } +} + +function encKey(keyId: number, priv: Uint8Array, extra: Partial = {}): FakeKey { + return { keyId, purposeNumber: 1, securityLevelNumber: 2, keyTypeNumber: 0, data: pub(priv), validatePrivateKey: () => false, ...extra } +} + +describe('wallet login and the encryption key (D27)', () => { + let keys: FakeKey[] + let fetches = 0 + const sdk = { + identities: { + fetch: async () => { + fetches += 1 + return { balance: 10n ** 11n, publicKeys: keys, getPublicKeyById: () => ({}) } + }, + keysRemainingBudgets: async () => new Map(), + }, + contracts: { fetch: async () => ({}) }, + version: () => 10, + encryptedFor: {}, + } as unknown as EvoSDK + const walletKey: WalletKey = { keyId: 5, wif: AUTH_WIF, scope: { core: true, collab: false, community: false, unbounded: false }, limits: null } + const detach: (() => void)[] = [] + const make = (): AuthController => { + const c = new AuthController(async () => sdk, NET) + detach.push(c.attach()) + return c + } + /** What the sign-in sheet hands over: the wallet's encryption key (a copy it wipes itself). */ + const login = (c: AuthController, justRegistered = false) => + c.adoptWalletKeys(ID, [walletKey], PASSKEY, { encryptionKeys: [new Uint8Array(WALLET_ENC)], justRegistered }) + + beforeEach(() => { + resetMemoryStores() + vi.stubGlobal('window', fakeWindow()) + vi.stubGlobal('navigator', fakeNavigator) + lockVault() + gestures = 0 + fetches = 0 + // The first wallet login's update: the auth key, and the encryption key right after it. + keys = [authKey(5, AUTH_WIF), encKey(6, WALLET_ENC)] + }) + afterEach(() => { + for (const off of detach.splice(0)) off() + vi.unstubAllGlobals() + }) + + it('a first login seals the key whose public key is the identity ENCRYPTION key, never in plaintext', async () => { + const c = make() + await login(c, true) + expect(c.getState().notice ?? null).toBeNull() + expect(await storedEncryptionKeyId(NET, ID)).toBe(6) + const held = await withEncryptionKey(NET, ID, async (keyId, secret) => ({ keyId, pub: pub(secret) })) + expect(held).toEqual({ keyId: 6, pub: keys.find((k) => k.keyId === 6)!.data }) + const dump = JSON.stringify(await idbEntries('vault'), (_k, v: unknown) => (v instanceof Uint8Array ? bytesToHex(v) : v)) + expect(dump).not.toContain(bytesToHex(WALLET_ENC)) + }, 30_000) + + it('a returning login (another browser) re-derives and stores the same key', async () => { + await login(make()) + resetMemoryStores() + lockVault() + await login(make()) + expect(await storedEncryptionKeyId(NET, ID)).toBe(6) + expect(await withEncryptionKey(NET, ID, async (_k, s) => bytesToHex(s))).toBe(bytesToHex(WALLET_ENC)) + }, 30_000) + + it('over a locked vault whose copy cannot be carried over, the wallet key replaces it without a "not carried over" notice', async () => { + // An earlier sign-in with a limited key from the identity file, its encryption key beside it. + await storeInVault(NET, { identityId: ID, keyId: 9, wif: encodeWif(new Uint8Array(32).fill(9), NET) }, PASSKEY) + await storeEncryptionKey(NET, ID, 6, new Uint8Array(WALLET_ENC)) + lockVault() + const c = make() + await login(c) + expect(c.getState().notice ?? null).toBeNull() + expect(await withEncryptionKey(NET, ID, async (k, s) => [k, bytesToHex(s)])).toEqual([6, bytesToHex(WALLET_ENC)]) + }, 30_000) + + it('after a reload the key is locked; one unlock opens it for two different repos', async () => { + await login(make()) + releaseUnlocked() // a reload: the page's memory is gone + const tab = make() + // A wallet key has no budget or expiry, so it is never kept: nothing resumes. + expect(await tab.resume()).toBe(false) + expect(await encryptionKeyState(NET, ID)).toBe('locked') + await expect(withEncryptionKey(NET, ID, async () => 1)).rejects.toThrow(/unlock/) + await tab.unlock(ID, 'passkey') + expect(gestures).toBe(1) + expect(await encryptionKeyState(NET, ID)).toBe('open') + const ops = await encryptionOps(sdk, NET, ID, FORGE.collab) + expect(ops?.keyId).toBe(6) + const read = (repo: number) => + ops!.unwrap({ document: {}, counterpartyKey: {} as never, repoId: new Uint8Array(32).fill(repo), epoch: 0 }) as unknown as Promise<{ reader: string; repo: string }> + const a = await read(0xa1) + const b = await read(0xb2) + expect([a.reader, b.reader]).toEqual([bytesToHex(WALLET_ENC), bytesToHex(WALLET_ENC)]) + expect(a.repo).not.toBe(b.repo) + // Both repos read with the one gesture. + expect(gestures).toBe(1) + }, 30_000) + + it('the identity uses a key from dg: says where to import it, and stores nothing', async () => { + keys = [authKey(5, AUTH_WIF), encKey(7, DG_ENC)] + const c = make() + await login(c) + expect(c.getState().notice).toBe(ENCRYPTION_KEY_ELSEWHERE) + expect(ENCRYPTION_KEY_ELSEWHERE).toBe('Your encryption key is held elsewhere. Import it under Settings → Private repos.') + expect(await storedEncryptionKeyId(NET, ID)).toBeNull() + expect((await idbEntries('vault')).some(([k]) => String(k).includes('enc'))).toBe(false) + // The sign-in itself went through. + expect(c.getState().session?.identityId).toBe(ID) + }, 30_000) + + it("the wallet's key is on the identity but a newer key from dg is the one writers use: not stored", async () => { + keys = [authKey(5, AUTH_WIF), encKey(6, WALLET_ENC), encKey(7, DG_ENC)] + const c = make() + await login(c) + expect(c.getState().notice).toBe(ENCRYPTION_KEY_ELSEWHERE) + expect(await storedEncryptionKeyId(NET, ID)).toBeNull() + }, 30_000) + + it('a disabled wallet key, or one bound to another contract, is not stored', async () => { + keys = [authKey(5, AUTH_WIF), encKey(6, WALLET_ENC, { disabledAt: 1n })] + const c = make() + await login(c) + expect(c.getState().notice ?? null).toBeNull() + expect(await storedEncryptionKeyId(NET, ID)).toBeNull() + keys = [authKey(5, AUTH_WIF), encKey(6, WALLET_ENC, { contractBounds: { toJSON: () => ({ $type: 'singleContract', id: FORGE.collab }) } })] + resetMemoryStores() + lockVault() + await login(make()) + expect(await storedEncryptionKeyId(NET, ID)).toBeNull() + }, 30_000) + + it('the vault already holds the key from dg: no notice, and it stays', async () => { + keys = [authKey(5, AUTH_WIF), encKey(7, DG_ENC)] + const c = make() + await login(c) + await storeEncryptionKey(NET, ID, 7, new Uint8Array(DG_ENC)) + c.clearNotice() + await login(c) + expect(c.getState().notice ?? null).toBeNull() + expect(await withEncryptionKey(NET, ID, async (k, s) => [k, bytesToHex(s)])).toEqual([7, bytesToHex(DG_ENC)]) + }, 30_000) + + it("waits for a node a block behind the wallet's registration, and wipes only its own copies", async () => { + keys = [authKey(5, AUTH_WIF)] + const late = encKey(6, WALLET_ENC) + const c = make() + await login(c) + const mine = new Uint8Array(WALLET_ENC) + const pending = (async () => { + await vi.waitFor(() => expect(fetches).toBeGreaterThan(0)) + keys = [...keys, late] + })() + fetches = 0 + const outcome = await adoptWalletEncryptionKey(sdk, NET, ID, FORGE.core, [mine], { attempts: 5, intervalMs: 5 }) + await pending + expect(outcome).toEqual({ kind: 'stored', keyId: 6 }) + expect(bytesToHex(mine)).toBe(bytesToHex(WALLET_ENC)) + }, 30_000) +}) diff --git a/forge-web/lib/auth/wallet-login.live.test.ts b/forge-web/lib/auth/wallet-login.live.test.ts index 35af007f8..8716785db 100644 --- a/forge-web/lib/auth/wallet-login.live.test.ts +++ b/forge-web/lib/auth/wallet-login.live.test.ts @@ -15,7 +15,11 @@ * 3. returning login: a new request is answered with the already-registered key, no QR #2; * 4. cleanup: the master key disables the keys this run added. * - * Uses the RELAY fixture identity (unused by the other suites) and a chain key fixed per run. + * Both logins keep the encryption key the wallet registered beside the auth key in the vault + * (DESIGN D27): its public key is the identity's usable ENCRYPTION key. + * + * Uses the RELAY fixture identity (unused by the other suites), or the identity file named by + * FORGE_WALLET_IDENTITY_FILE, and a chain key fixed per run. */ import { randomBytes } from 'node:crypto' @@ -29,12 +33,17 @@ import { DEFAULT_NETWORK, NETWORKS } from '../constants' import { resetMemoryStores } from '../idb' import { evoSdkService } from '../sdk' import { createRepo, starRelation } from '../repo/writes' -import { awaitRegisteredKey, awaitWalletAnswer, newLoginRequest, responseSources } from './app-connect' +import * as secp from '@noble/secp256k1' +import { bytesToHex } from '@noble/hashes/utils.js' + +import { awaitRegisteredKey, awaitWalletAnswer, newLoginRequest, responseSources, wipeAnswer } from './app-connect' import { AuthController, MissingGrantError } from './controller' +import { fetchIdentityKeys, usableEncryptionKey } from './encryption-key' import { keyRegistrationUri, RevokedWalletKey, type WalletKey } from './key-registration' +import { lockVault, storedEncryptionKeyId, withEncryptionKey } from './vault' const DEVNET = NETWORKS.devnet.devnetName ?? '' -const FILE = join(homedir(), '.config/dash-forge/test-identities', `devnet-${DEVNET}`, 'RELAY.identity.json') +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) const CHAIN_KEY = randomBytes(32).toString('hex') @@ -54,32 +63,49 @@ describe.skipIf(!LIVE)('live wallet sign-in (scripted Dash Wallet, legacy key-ex const opts = { network, forge, sources, intervalMs: 2000, settleMs: 2000 } /** The app shows `contractId`'s request; the wallet approves and, if asked, registers. */ - async function signIn(contractId: string, identityId?: string): Promise<{ identityId: string; key: WalletKey; registered: boolean }> { + async function signIn( + contractId: string, + identityId?: string, + ): Promise<{ identityId: string; key: WalletKey; registered: boolean; encryptionKeys: readonly Uint8Array[]; wipe: () => void }> { const req = newLoginRequest(network, contractId) const answering = awaitWalletAnswer(sdk, req, { ...opts, ...(identityId ? { identityId } : {}) }) const approved = await wallet.approve({ uri: req.uri, identityFile: FILE, chainKeyHex: CHAIN_KEY, devnet: DEVNET }) expect(approved.contractId).toBe(contractId) expect(approved.label).toBe('Dash Forge') const answer = await answering - if (answer.kind === 'keys') return { identityId: answer.identityId, key: answer.keys[0]!, registered: false } + const held = { encryptionKeys: answer.encryptionKeys, wipe: () => wipeAnswer(answer) } + if (answer.kind === 'keys') return { identityId: answer.identityId, key: answer.keys[0]!, registered: false, ...held } const until = Date.now() + 5 * 60_000 const uri = await keyRegistrationUri(sdk, { identityId: answer.identityId, keys: answer.keys, contractId, network }) await wallet.register({ uri, identityFile: FILE, chainKeyHex: CHAIN_KEY, contractId, devnet: DEVNET }) const key = await awaitRegisteredKey(sdk, { identityId: answer.identityId, wif: answer.wif, network, forge, until }) - return { identityId: answer.identityId, key, registered: true } + return { identityId: answer.identityId, key, registered: true, ...held } + } + + /** The vault holds an encryption key whose public key is the identity's usable ENCRYPTION key. */ + async function expectEncryptionKeyKept(identityId: string): Promise { + const usable = usableEncryptionKey((await fetchIdentityKeys(sdk, identityId)) ?? [], forge.core) + expect(usable).not.toBeNull() + expect(await storedEncryptionKeyId(network, identityId)).toBe(usable!.keyId) + const pub = await withEncryptionKey(network, identityId, async (_k, secret) => bytesToHex(secp.getPublicKey(secret, true))) + expect(pub).toBe(usable!.data.toLowerCase()) } try { // 1. First login on forge-core: QR #2 registers the key, bound to forge-core, no limits. const first = await signIn(forge.core) expect(first.registered).toBe(true) - expect(first.key.scope).toEqual({ core: true, collab: false, unbounded: false }) + expect(first.key.scope).toEqual({ core: true, collab: false, community: false, unbounded: false }) expect(first.key.limits).toBeNull() resetMemoryStores() const controller = new AuthController(async () => sdk, network) - const session = await controller.adoptWalletKeys(first.identityId, [first.key], { passphrase: 'live wallet e2e passphrase' }) - expect(session.grants).toEqual({ core: true, collab: false }) + const protection = { passphrase: 'live wallet e2e passphrase' } + const session = await controller.adoptWalletKeys(first.identityId, [first.key], protection, { encryptionKeys: first.encryptionKeys, justRegistered: true }) + first.wipe() + expect(controller.getState().notice ?? null).toBeNull() + await expectEncryptionKeyKept(first.identityId) + expect(session.grants).toEqual({ core: true, collab: false, community: false }) expect(session.unlimited).toBe(true) const auth = controller.writeAuth! @@ -94,15 +120,24 @@ describe.skipIf(!LIVE)('live wallet sign-in (scripted Dash Wallet, legacy key-ex // 2. The one-tap grant for forge-collab, then the star lands. const grant = await signIn(forge.collab, first.identityId) - expect(grant.key.scope).toEqual({ core: false, collab: true, unbounded: false }) + expect(grant.key.scope).toEqual({ core: false, collab: true, community: false, unbounded: false }) + grant.wipe() const after = await controller.addWalletGrant(first.identityId, grant.key, forge.collab) - expect(after.grants).toEqual({ core: true, collab: true }) + expect(after.grants).toEqual({ core: true, collab: true, community: false }) expect(await starRelation(sdk, controller.writeAuth!, first.identityId, starOf).add()).toBe(true) // 3. Returning login: the registered key answers straight away. const again = await signIn(forge.core) expect(again.registered).toBe(false) expect(again.key.keyId).toBe(first.key.keyId) + // On a browser that holds nothing yet: the same encryption key, derived again and kept. + lockVault() + resetMemoryStores() + const returning = new AuthController(async () => sdk, network) + await returning.adoptWalletKeys(again.identityId, [again.key], { passphrase: 'live wallet e2e passphrase' }, { encryptionKeys: again.encryptionKeys }) + again.wipe() + expect(returning.getState().notice ?? null).toBeNull() + await expectEncryptionKeyKept(again.identityId) } finally { // 4. Leave the identity as it was: disable what this run added. await wallet.disableDerived({ identityFile: FILE, chainKeyHex: CHAIN_KEY, contractIds: [forge.core, forge.collab], devnet: DEVNET }) @@ -132,14 +167,15 @@ describe.skipIf(!LIVE)('live wallet sign-in (scripted Dash Wallet, legacy key-ex await wallet.register({ uri, identityFile: FILE, chainKeyHex: chainKey, contractId: forge.core, devnet: DEVNET, android: true }) const key = await awaitRegisteredKey(sdk, { identityId: answer.identityId, wif: answer.wif, network, forge, until: Date.now() + 5 * 60_000 }) // Android drops the bound: the key covers both contracts (and any other), no limits. - expect(key.scope).toEqual({ core: true, collab: true, unbounded: true }) + expect(key.scope).toEqual({ core: true, collab: true, community: true, unbounded: true }) expect(key.limits).toBeNull() resetMemoryStores() const controller = new AuthController(async () => sdk, network) const session = await controller.adoptWalletKeys(answer.identityId, [key], { passphrase: 'live wallet e2e passphrase' }) - expect(session.grants).toEqual({ core: true, collab: true }) + expect(session.grants).toEqual({ core: true, collab: true, community: true }) expect(session.unbounded).toBe(true) + wipeAnswer(answer) // Revoke it; a new login from the same wallet derives the same key: refused. await wallet.disableDerived({ identityFile: FILE, chainKeyHex: chainKey, contractIds: [forge.core], devnet: DEVNET }) diff --git a/forge-web/lib/auth/wallet-protocol.test.ts b/forge-web/lib/auth/wallet-protocol.test.ts index cc8c14ffd..747990c45 100644 --- a/forge-web/lib/auth/wallet-protocol.test.ts +++ b/forge-web/lib/auth/wallet-protocol.test.ts @@ -21,6 +21,7 @@ import { sameIdentifier, newLoginRequest, walletSignInSupported, + wipeAnswer, type ResponseSource, } from './app-connect' import { buildKeyRegistration, isUnlimited, keyScope, loginKeys, nextGrant, scopeCovers, RevokedWalletKey } from './key-registration' @@ -335,10 +336,12 @@ describe('login poll against a simulated wallet', () => { it('a returning shipped wallet (legacy contract): a forge-core key, unlimited', async () => { const chain = fakeChain() const req = newLoginRequest('devnet', FORGE.core) - const { authPriv } = await chain.answer(req.uri, ALICE, { source: 'legacy' }) + const { authPriv, login } = await chain.answer(req.uri, ALICE, { source: 'legacy' }) const a = await awaitWalletAnswer(chain.sdk, req, fast) expect(a.kind).toBe('keys') if (a.kind !== 'keys') throw new Error('unreachable') + // The encryption key the login key stands for travels with the answer (DESIGN D27). + expect(a.encryptionKeys.map(bytesToHex)).toEqual([bytesToHex(encryptionKeyFromLogin(login, ALICE))]) expect(a.identityId).toBe(ALICE) expect(a.source).toBe('legacy') expect(a.keys[0]!.scope).toEqual({ core: true, collab: false, community: false, unbounded: false }) @@ -355,6 +358,13 @@ describe('login poll against a simulated wallet', () => { expect(a.kind).toBe('register') if (a.kind !== 'register') throw new Error('unreachable') expect(bytesToHex(a.keys.authData)).toBe(bytesToHex(loginKeys(login, ALICE).authData)) + // A copy of the encryption key: building QR #2 wipes the login keys, not this one. + const enc = bytesToHex(encryptionKeyFromLogin(login, ALICE)) + expect(a.encryptionKeys.map(bytesToHex)).toEqual([enc]) + a.keys.encPriv.fill(0) + expect(bytesToHex(a.encryptionKeys[0]!)).toBe(enc) + wipeAnswer(a) + expect(a.encryptionKeys[0]!.every((b) => b === 0)).toBe(true) }) it('an App Connect wallet: a group-bound key with limits', async () => { From ece72cd9023325ac41c7031f6575c9e9e768dd10 Mon Sep 17 00:00:00 2001 From: pasta Date: Mon, 5 Oct 2026 02:37:53 -0400 Subject: [PATCH 2/7] test(web): run the live wallet login's returning check before a grant, and grant forge-community for the star A star is a forge-community write since RC1 and a key scope has a community field: the live test still asked for forge-collab. The returning login on a fresh browser now runs before the grant, since a first approval for another contract registers another encryption key. Co-Authored-By: Claude Opus 5.5 (1M context) --- forge-web/lib/auth/wallet-login.live.test.ts | 37 +++++++++++--------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/forge-web/lib/auth/wallet-login.live.test.ts b/forge-web/lib/auth/wallet-login.live.test.ts index 8716785db..f90b3bf93 100644 --- a/forge-web/lib/auth/wallet-login.live.test.ts +++ b/forge-web/lib/auth/wallet-login.live.test.ts @@ -10,9 +10,10 @@ * * 1. first login: request (forge-core) → wallet approves → register (QR #2) → key lands bound * to forge-core, without limits → session → a forge-core write (a repo) is signed by it; - * a forge-collab write (a star) is refused locally with MissingGrantError, nothing sent; - * 2. the one-tap grant: request (forge-collab) → wallet approves → register → the star lands; - * 3. returning login: a new request is answered with the already-registered key, no QR #2; + * a forge-community write (a star) is refused locally with MissingGrantError, nothing sent; + * 2. returning login on a fresh browser: a new request is answered with the already-registered + * key, no QR #2; + * 3. the one-tap grant: request (forge-community) → wallet approves → register → the star lands; * 4. cleanup: the master key disables the keys this run added. * * Both logins keep the encryption key the wallet registered beside the auth key in the vault @@ -51,7 +52,7 @@ type Responder = typeof import('../../e2e/wallet-responder.mjs') describe.skipIf(!LIVE)('live wallet sign-in (scripted Dash Wallet, legacy key-exchange contract)', () => { it( - 'first login, one-tap forge-collab grant, returning login, cleanup', + 'first login, returning login, one-tap forge-community grant, cleanup', async () => { const wallet: Responder = await import(pathToFileURL(resolve(__dirname, '../../e2e/wallet-responder.mjs')).href) await evoSdkService.initialize({ network: 'devnet', contractIds: [], timeoutMs: 30000 }) @@ -114,33 +115,35 @@ describe.skipIf(!LIVE)('live wallet sign-in (scripted Dash Wallet, legacy key-ex const repo = await createRepo(sdk, auth, forge, { name }) expect(repo.repoId).toMatch(/^[1-9A-HJ-NP-Za-km-z]{43,44}$/) - // A forge-collab write: refused before signing (nothing broadcast, nothing charged). + // A forge-community write: refused before signing (nothing broadcast, nothing charged). const starOf = { kind: 'v2' as const, forge, repoId: repo.repoId, ownerId: first.identityId, name, visibility: 'public' as const } await expect(starRelation(sdk, auth, first.identityId, starOf).add()).rejects.toBeInstanceOf(MissingGrantError) - // 2. The one-tap grant for forge-collab, then the star lands. - const grant = await signIn(forge.collab, first.identityId) - expect(grant.key.scope).toEqual({ core: false, collab: true, community: false, unbounded: false }) - grant.wipe() - const after = await controller.addWalletGrant(first.identityId, grant.key, forge.collab) - expect(after.grants).toEqual({ core: true, collab: true, community: false }) - expect(await starRelation(sdk, controller.writeAuth!, first.identityId, starOf).add()).toBe(true) - - // 3. Returning login: the registered key answers straight away. + // 2. Returning login, on a browser that holds nothing yet: the registered key answers + // straight away (no QR #2), and the same encryption key is derived again and kept. (Before + // the grant below: each first approval for another contract registers another encryption + // key, which then becomes the identity's usable one.) const again = await signIn(forge.core) expect(again.registered).toBe(false) expect(again.key.keyId).toBe(first.key.keyId) - // On a browser that holds nothing yet: the same encryption key, derived again and kept. lockVault() resetMemoryStores() const returning = new AuthController(async () => sdk, network) - await returning.adoptWalletKeys(again.identityId, [again.key], { passphrase: 'live wallet e2e passphrase' }, { encryptionKeys: again.encryptionKeys }) + await returning.adoptWalletKeys(again.identityId, [again.key], protection, { encryptionKeys: again.encryptionKeys }) again.wipe() expect(returning.getState().notice ?? null).toBeNull() await expectEncryptionKeyKept(again.identityId) + + // 3. The one-tap grant for forge-community (a star is a forge-community write), then the star lands. + const grant = await signIn(forge.community, first.identityId) + expect(grant.key.scope).toEqual({ core: false, collab: false, community: true, unbounded: false }) + grant.wipe() + const after = await returning.addWalletGrant(first.identityId, grant.key, forge.community) + expect(after.grants).toEqual({ core: true, collab: false, community: true }) + expect(await starRelation(sdk, returning.writeAuth!, first.identityId, starOf).add()).toBe(true) } finally { // 4. Leave the identity as it was: disable what this run added. - await wallet.disableDerived({ identityFile: FILE, chainKeyHex: CHAIN_KEY, contractIds: [forge.core, forge.collab], devnet: DEVNET }) + await wallet.disableDerived({ identityFile: FILE, chainKeyHex: CHAIN_KEY, contractIds: [forge.core, forge.community], devnet: DEVNET }) } }, 20 * 60_000, From 74a05b835449f68a6d2a21b6f5bcf626c0d901cf Mon Sep 17 00:00:00 2001 From: pasta Date: Mon, 5 Oct 2026 02:55:30 -0400 Subject: [PATCH 3/7] fix(web): copy the wallet's encryption key at once, keep a grant's new key, and point to the approval that brings it Review findings on the wallet-derived encryption key: - adoptWalletKeys and addWalletGrant copy the key bytes before anything waits, so the sheet closing mid sign-in (and wiping its bytes) no longer turns the key into zeros. - A wallet's first approval for another contract registers another encryption key, which becomes the identity's usable one: the grant now keeps it, and a login whose key was superseded that way says to approve again rather than to import a key no file holds. - The "not carried over" notice is hidden only when the wallet's key replaced that same key, and the failure notice no longer claims the sign-in finished. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../components/auth/wallet-connect-flow.tsx | 8 +- forge-web/contexts/auth-context.tsx | 2 +- forge-web/lib/auth/controller.ts | 64 ++++++++++----- forge-web/lib/auth/encryption-key.ts | 21 ++++- forge-web/lib/auth/wallet-encryption.test.ts | 81 ++++++++++++++----- 5 files changed, 131 insertions(+), 45 deletions(-) diff --git a/forge-web/components/auth/wallet-connect-flow.tsx b/forge-web/components/auth/wallet-connect-flow.tsx index b0b4ddfc4..884cb2314 100644 --- a/forge-web/components/auth/wallet-connect-flow.tsx +++ b/forge-web/components/auth/wallet-connect-flow.tsx @@ -21,8 +21,9 @@ * since only answers from the signed-in identity are read. * * Granted keys are held in refs, never React state, and dropped when the sheet closes. So is the - * encryption key the wallet's login key stands for: signing in seals it into the vault beside the - * wallet key when it is the identity's (DESIGN D27), and the bytes are wiped once the sheet is done. + * encryption key the wallet's login key stands for: signing in (or a grant) seals it into the vault + * beside the wallet key when it is the identity's (DESIGN D27), and the bytes are wiped once the + * sheet is done. */ import { useCallback, useEffect, useRef, useState } from 'react' @@ -211,7 +212,8 @@ export function WalletConnectFlow({ onDone, mode = 'login', contractId }: { onDo // The key that covers what was asked for (a wallet may grant several, or the wrong one). const key = keys.find((k) => scopeCovers(k.scope, forge, target)) if (!key) throw new Error("The wallet's answer does not cover issues and pull requests. Try again, or sign in with your identity file.") - await latest.current.addWalletGrant(answer.identityId, key, target) + // Its first approval registered an encryption key too: the sign-in keeps it. + await latest.current.addWalletGrant(answer.identityId, key, target, { encryptionKeys: answer.encryptionKeys, justRegistered: answer.kind === 'register' }) if (signal.aborted) return latest.current.onDone() return diff --git a/forge-web/contexts/auth-context.tsx b/forge-web/contexts/auth-context.tsx index 24d2215d6..cf221dd59 100644 --- a/forge-web/contexts/auth-context.tsx +++ b/forge-web/contexts/auth-context.tsx @@ -110,7 +110,7 @@ interface AuthContextValue { /** Store the keys a wallet granted (verified on chain) and open the session. */ adoptWalletKeys: (identityId: string, keys: readonly WalletKey[], protection: Protection, options?: Parameters[3]) => Promise /** Add a wallet grant for another Forge contract to the signed-in identity. */ - addWalletGrant: (identityId: string, key: WalletKey, requested: string) => Promise + addWalletGrant: (identityId: string, key: WalletKey, requested: string, options?: Parameters[3]) => Promise /** Which Forge contracts the session's keys cover, and whether a held key is unlimited. */ readonly grants: AuthSession['grants'] | null readonly unlimitedKey: boolean diff --git a/forge-web/lib/auth/controller.ts b/forge-web/lib/auth/controller.ts index ad1018765..10416f556 100644 --- a/forge-web/lib/auth/controller.ts +++ b/forge-web/lib/auth/controller.ts @@ -46,7 +46,8 @@ import { PLATFORM_READ_MS, withPlatformRead } from './connect' import { withTimeout } from '../timeout' import { clearLedger } from '../spend' import { clearInbox } from '../view/inbox' -import { ENCRYPTION_KEY_ELSEWHERE, adoptWalletEncryptionKey } from './encryption-key' +import { ENCRYPTION_KEY_ELSEWHERE, ENCRYPTION_KEY_OTHER_APPROVAL, adoptWalletEncryptionKey, type WalletEncryptionOutcome } from './encryption-key' +import { storedEncryptionKeyId } from './vault' import { clearDrafts } from '../view/draft-text' import { forgetLastIdentity, rememberLastIdentity } from './last-identity' import { checkWalletKey, hasNoLimits, isForgeContract, keyScope, scopeCovers, type KeyScope, type WalletKey } from './key-registration' @@ -963,16 +964,11 @@ export class AuthController { readonly renewalUnlock?: { passphrase: string } | 'passkey' /** Give it up even though it cannot be opened (its key then stays live until it expires). */ readonly dropUnopened?: boolean - /** - * The encryption private keys the wallet's login keys stand for (`WalletAnswer`): the one - * the identity uses is sealed beside the wallet key (DESIGN D27). Copied, not wiped: the - * caller wipes them. - */ - readonly encryptionKeys?: readonly Uint8Array[] - /** The wallet registered its keys just now (QR #2): a node may not show them yet. */ - readonly justRegistered?: boolean - } = {}, + } & WalletEncryption = {}, ): Promise { + // Copied before anything waits: the sheet wipes its bytes when it closes. + const encryptionKeys = copyKeys(options.encryptionKeys) + const withCopies = { ...options, encryptionKeys } return this.run(async () => { const [main, ...rest] = keys if (!main) throw new Error('the wallet granted no key') @@ -988,12 +984,12 @@ export class AuthController { // that stores it. As this identity's one writer: no other tab's stage is dropped instead. return serialized(identityId, async () => { try { - return await this.storeWalletKeys(identityId, main, rest, forge, protection, options) + return await this.storeWalletKeys(identityId, main, rest, forge, protection, withCopies) } finally { forgetPasskeyOutputs() } }) - }) + }).finally(() => wipeKeys(encryptionKeys)) } private async storeWalletKeys( @@ -1023,11 +1019,14 @@ export class AuthController { const kept = [...held, ...(given ? [given] : [])].filter((h, i, all) => !fresh.has(h.keyId) && all.findIndex((x) => x.keyId === h.keyId) === i) const extra = [...rest.map((k) => toExtraKey(k, forge)), ...kept] const secret: VaultSecret = { identityId, keyId: main.keyId, wif: main.wif, ...(extra.length ? { extra } : {}) } + const heldBefore = await storedEncryptionKeyId(this.network, identityId) const stored = await storeInVault(this.network, secret, protection, pending !== null ? { dropStagedKeyId: pending.keyId } : {}) const encryption = await this.keepWalletEncryptionKey(identityId, forge, options) + // A key the vault could not carry over is not reported when the wallet's own key replaced + // that same key, or when the notice already says where the identity's key is. + const replaced = encryption.outcome?.kind === 'stored' && encryption.outcome.keyId === heldBefore this.noteDropped( - // An encryption key the vault could not carry over is replaced by the wallet's own. - encryption.stored ? { ...stored, encryptionKeyDropped: false } : stored, + replaced || encryption.outcome?.kind === 'elsewhere' ? { ...stored, encryptionKeyDropped: false } : stored, 'Your storage settings could not be carried over to the new key. Add your storage again in Settings → Storage.', encryption.notice, ) @@ -1047,16 +1046,17 @@ export class AuthController { private async keepWalletEncryptionKey( identityId: string, forge: ForgeIds, - options: { readonly encryptionKeys?: readonly Uint8Array[]; readonly justRegistered?: boolean }, - ): Promise<{ readonly stored: boolean; readonly notice: string | null }> { - if (!options.encryptionKeys?.length) return { stored: false, notice: null } + options: WalletEncryption, + ): Promise<{ readonly outcome: WalletEncryptionOutcome | null; readonly notice: string | null }> { + if (!options.encryptionKeys?.length) return { outcome: null, notice: null } this.step('Enabling private repos') try { const sdk = await this.getSdk() const outcome = await adoptWalletEncryptionKey(sdk, this.network, identityId, forge.core, options.encryptionKeys, options.justRegistered === true ? { attempts: 5 } : {}) - return { stored: outcome.kind === 'stored', notice: outcome.kind === 'elsewhere' ? ENCRYPTION_KEY_ELSEWHERE : null } + const notice = outcome.kind === 'elsewhere' ? ENCRYPTION_KEY_ELSEWHERE : outcome.kind === 'other-approval' ? ENCRYPTION_KEY_OTHER_APPROVAL : null + return { outcome, notice } } catch (e) { - return { stored: false, notice: `Signed in, but private repos could not be enabled: ${errorMessage(e)}.` } + return { outcome: null, notice: `Private repos could not be enabled: ${errorMessage(e)}` } } } @@ -1064,7 +1064,9 @@ export class AuthController { * Add a wallet grant for another Forge contract to the signed-in identity (a shipped wallet * grants one contract per approval). The key must belong to the session's identity. */ - async addWalletGrant(identityId: string, key: WalletKey, requested: string): Promise { + async addWalletGrant(identityId: string, key: WalletKey, requested: string, options: WalletEncryption = {}): Promise { + // Copied before anything waits: the sheet wipes its bytes when it closes. + const encryptionKeys = copyKeys(options.encryptionKeys) return this.run(async () => { const session = this.state.session const forge = NETWORKS[this.network].v2 @@ -1080,6 +1082,10 @@ export class AuthController { const opened = await this.open(secret, 'vault', session.keyLimits ?? undefined, false) const want = contractKind(forge, requested) if (want === null || !opened.grants?.[want]) throw new Error('the granted key is not live on the identity yet') + // A first approval for this contract registered an encryption key too, now the + // identity's usable one: keep it (never throws). + const encryption = await this.keepWalletEncryptionKey(identityId, forge, { ...options, encryptionKeys }) + if (encryption.notice !== null) this.setState({ notice: encryption.notice }) return opened } catch (e) { // The grant is stored; keep the session that was working (unless it locked meanwhile: @@ -1087,7 +1093,7 @@ export class AuthController { if (unlockedSecret(this.network, identityId) !== null) this.setState({ session }) throw new Error(`The approval was saved, but checking it on Platform failed (${errorMessage(e)}). It will be checked again when you next unlock.`) } - }) + }).finally(() => wipeKeys(encryptionKeys)) } /** Open the session of a key already in the vault and unlocked (identity creation). */ @@ -1670,3 +1676,19 @@ function toExtraKey(key: WalletKey, forge: ForgeIds, requested?: string): ExtraK const contractId = requested !== undefined && scopeCovers(key.scope, forge, requested) ? requested : forge[covered] return { contractId, keyId: key.keyId, wif: key.wif } } + +/** + * What a wallet answer brings for the encryption key (DESIGN D27): the encryption private keys + * its login keys stand for (`WalletAnswer.encryptionKeys`), the one the identity uses being sealed + * beside the wallet key. Copied on the way in, so the caller wipes its own bytes whenever it likes. + */ +interface WalletEncryption { + readonly encryptionKeys?: readonly Uint8Array[] + /** The wallet registered its keys just now (QR #2): a node may not show them yet. */ + readonly justRegistered?: boolean +} + +const copyKeys = (keys: readonly Uint8Array[] | undefined): Uint8Array[] => (keys ?? []).map((k) => new Uint8Array(k)) +const wipeKeys = (keys: readonly Uint8Array[]): void => { + for (const k of keys) k.fill(0) +} diff --git a/forge-web/lib/auth/encryption-key.ts b/forge-web/lib/auth/encryption-key.ts index fba5640d1..3f6181cbe 100644 --- a/forge-web/lib/auth/encryption-key.ts +++ b/forge-web/lib/auth/encryption-key.ts @@ -122,6 +122,18 @@ export async function adoptEncryptionKey(sdk: EvoSDK, network: Network, identity */ export const ENCRYPTION_KEY_ELSEWHERE = 'Your encryption key is held elsewhere. Import it under Settings → Private repos.' +/** + * The identity's encryption key came with another of the wallet's approvals: each first approval + * for another Forge contract registers its own (QR #2 adds exactly an auth and an encryption + * key), and the latest is the one writers use. Approving that contract here again brings it. + */ +export const ENCRYPTION_KEY_OTHER_APPROVAL = + "Your encryption key came with another approval in your wallet. Approve it again under Settings → This browser's key to read private repos." + +/** AUTHENTICATION, and ECDSA_HASH160: the auth key a wallet registers (DPP enums). */ +const PURPOSE_AUTHENTICATION = 0 +const KEY_TYPE_ECDSA_HASH160 = 2 + /** What became of the encryption key a wallet login stands for ({@link adoptWalletEncryptionKey}). */ export type WalletEncryptionOutcome = /** It is the identity's usable encryption key, now sealed in the vault. */ @@ -130,6 +142,11 @@ export type WalletEncryptionOutcome = | { readonly kind: 'held'; readonly keyId: number } /** It is not, and this browser does not hold the one the identity uses ({@link ENCRYPTION_KEY_ELSEWHERE}). */ | { readonly kind: 'elsewhere'; readonly keyId: number } + /** + * It is not: the identity's is the one another approval of the wallet registered, right after + * its auth key ({@link ENCRYPTION_KEY_OTHER_APPROVAL}). Its grant for that contract brings it. + */ + | { readonly kind: 'other-approval'; readonly keyId: number } /** The identity has no usable encryption key. */ | { readonly kind: 'none' } @@ -169,7 +186,9 @@ export async function adoptWalletEncryptionKey( } if (usable === null) return { kind: 'none' } if ((await storedEncryptionKeyId(network, identityId)) === usable.keyId) return { kind: 'held', keyId: usable.keyId } - return { kind: 'elsewhere', keyId: usable.keyId } + // A wallet registers its encryption key right after the auth key, in one update. + const companion = keys.some((k) => k.keyId === usable.keyId - 1 && k.purposeNumber === PURPOSE_AUTHENTICATION && k.keyTypeNumber === KEY_TYPE_ECDSA_HASH160) + return { kind: companion ? 'other-approval' : 'elsewhere', keyId: usable.keyId } } } finally { for (const s of secrets) s.fill(0) diff --git a/forge-web/lib/auth/wallet-encryption.test.ts b/forge-web/lib/auth/wallet-encryption.test.ts index 259c94bea..dd1e5b2b1 100644 --- a/forge-web/lib/auth/wallet-encryption.test.ts +++ b/forge-web/lib/auth/wallet-encryption.test.ts @@ -15,7 +15,7 @@ import type { EvoSDK } from '@dashevo/evo-sdk' import { NETWORKS } from '../constants' import { idbEntries, resetMemoryStores } from '../idb' import { AuthController } from './controller' -import { ENCRYPTION_KEY_ELSEWHERE, adoptWalletEncryptionKey, encryptionKeyState, encryptionOps } from './encryption-key' +import { ENCRYPTION_KEY_ELSEWHERE, ENCRYPTION_KEY_OTHER_APPROVAL, adoptWalletEncryptionKey, encryptionKeyState, encryptionOps } from './encryption-key' import type { WalletKey } from './key-registration' import { lockVault, releaseUnlocked, storeEncryptionKey, storeInVault, storedEncryptionKeyId, withEncryptionKey } from './vault' import { encryptionKeyFromLogin } from './wallet-protocol' @@ -114,7 +114,7 @@ const fakeNavigator = { }, } -function authKey(keyId: number, wif: string): FakeKey { +function authKey(keyId: number, wif: string, contract = FORGE.core): FakeKey { return { keyId, wif, @@ -122,7 +122,7 @@ function authKey(keyId: number, wif: string): FakeKey { securityLevelNumber: 2, keyTypeNumber: 2, data: '', - contractBounds: { toJSON: () => ({ $type: 'singleContract', id: FORGE.core }) }, + contractBounds: { toJSON: () => ({ $type: 'singleContract', id: contract }) }, validatePrivateKey: (bytes) => bytesToHex(bytes) === bytesToHex(decodeWif(wif).privateKey), } } @@ -133,13 +133,9 @@ function encKey(keyId: number, priv: Uint8Array, extra: Partial = {}): describe('wallet login and the encryption key (D27)', () => { let keys: FakeKey[] - let fetches = 0 const sdk = { identities: { - fetch: async () => { - fetches += 1 - return { balance: 10n ** 11n, publicKeys: keys, getPublicKeyById: () => ({}) } - }, + fetch: async () => ({ balance: 10n ** 11n, publicKeys: keys, getPublicKeyById: () => ({}) }), keysRemainingBudgets: async () => new Map(), }, contracts: { fetch: async () => ({}) }, @@ -163,7 +159,6 @@ describe('wallet login and the encryption key (D27)', () => { vi.stubGlobal('navigator', fakeNavigator) lockVault() gestures = 0 - fetches = 0 // The first wallet login's update: the auth key, and the encryption key right after it. keys = [authKey(5, AUTH_WIF), encKey(6, WALLET_ENC)] }) @@ -272,18 +267,66 @@ describe('wallet login and the encryption key (D27)', () => { it("waits for a node a block behind the wallet's registration, and wipes only its own copies", async () => { keys = [authKey(5, AUTH_WIF)] - const late = encKey(6, WALLET_ENC) - const c = make() - await login(c) + await login(make()) + // The node shows the encryption key from its third read on. + const behind = [authKey(5, AUTH_WIF)] + const caughtUp = [authKey(5, AUTH_WIF), encKey(6, WALLET_ENC)] + let reads = 0 + const lagging = { + ...sdk, + identities: { ...(sdk as unknown as { identities: object }).identities, fetch: async () => ({ balance: 10n ** 11n, publicKeys: ++reads >= 3 ? caughtUp : behind }) }, + } as unknown as EvoSDK const mine = new Uint8Array(WALLET_ENC) - const pending = (async () => { - await vi.waitFor(() => expect(fetches).toBeGreaterThan(0)) - keys = [...keys, late] - })() - fetches = 0 - const outcome = await adoptWalletEncryptionKey(sdk, NET, ID, FORGE.core, [mine], { attempts: 5, intervalMs: 5 }) - await pending + const outcome = await adoptWalletEncryptionKey(lagging, NET, ID, FORGE.core, [mine], { attempts: 5, intervalMs: 5 }) expect(outcome).toEqual({ kind: 'stored', keyId: 6 }) + expect(reads).toBe(3) expect(bytesToHex(mine)).toBe(bytesToHex(WALLET_ENC)) + // Without retries (a returning login), one read decides. + reads = 0 + expect(await adoptWalletEncryptionKey(lagging, NET, ID, FORGE.core, [mine])).toEqual({ kind: 'none' }) + expect(reads).toBe(1) + }, 30_000) + + it('copies the key at once: the sheet wiping its bytes mid sign-in does not matter', async () => { + const theirs = new Uint8Array(WALLET_ENC) + const c = make() + const signingIn = c.adoptWalletKeys(ID, [walletKey], PASSKEY, { encryptionKeys: [theirs] }) + theirs.fill(0) // the sheet closed + await signingIn + expect(c.getState().notice ?? null).toBeNull() + expect(await withEncryptionKey(NET, ID, async (k, s) => [k, bytesToHex(s)])).toEqual([6, bytesToHex(WALLET_ENC)]) + }, 30_000) + + it("a grant's first approval registers the identity's new usable key: the grant keeps it", async () => { + const c = make() + await login(c, true) + // The wallet's first approval for forge-collab: another auth key, and another encryption key. + const COLLAB_WIF = encodeWif(new Uint8Array(32).fill(7), NET) + const collabEnc = encryptionKeyFromLogin(new Uint8Array(32).fill(0x22), ID) + keys = [...keys, authKey(7, COLLAB_WIF, FORGE.collab), encKey(8, collabEnc)] + const grant: WalletKey = { keyId: 7, wif: COLLAB_WIF, scope: { core: false, collab: true, community: false, unbounded: false }, limits: null } + await c.addWalletGrant(ID, grant, FORGE.collab, { encryptionKeys: [new Uint8Array(collabEnc)], justRegistered: true }) + expect(c.getState().notice ?? null).toBeNull() + expect(await withEncryptionKey(NET, ID, async (k, s) => [k, bytesToHex(s)])).toEqual([8, bytesToHex(collabEnc)]) + // A later forge-core login elsewhere: its key is no longer the identity's, and the notice + // points to the approval that brings it (not to an import no file could make). + resetMemoryStores() + lockVault() + const other = make() + await login(other) + expect(other.getState().notice).toBe(ENCRYPTION_KEY_OTHER_APPROVAL) + expect(await storedEncryptionKeyId(NET, ID)).toBeNull() + }, 30_000) + + it('replacing a different key the vault could not carry over still says it was dropped', async () => { + const OLD = new Uint8Array(32).fill(0x44) + keys = [encKey(4, OLD), authKey(5, AUTH_WIF), encKey(6, WALLET_ENC)] + await storeInVault(NET, { identityId: ID, keyId: 9, wif: encodeWif(new Uint8Array(32).fill(9), NET) }, PASSKEY) + await storeEncryptionKey(NET, ID, 4, new Uint8Array(OLD)) + lockVault() + const c = make() + await login(c) + expect(c.getState().notice).toMatch(/not carried over/) + expect(await withEncryptionKey(NET, ID, async (k) => k)).toBe(6) }, 30_000) }) From 7555cc8698169c892adeee44beb436159c67814d Mon Sep 17 00:00:00 2001 From: pasta Date: Mon, 5 Oct 2026 03:29:26 -0400 Subject: [PATCH 4/7] feat(web): keep every encryption key this browser has held, and read each wrap with the key it names MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each first wallet approval for another Forge contract registers another encryption key, so one vault slot stranded wraps made to the earlier key. The vault now keeps a set of sealed keys per identity, one entry per on-chain key id; a wallet approval, an imported file or a dg key adds to it and never replaces another. A vault written with a single entry reads as a set of one. Readers open a wrap with the held key its recipientKeyId (or senderKeyId) names, trying each held key when it names none; writers still send from the newest. One unlock opens the whole set, with the same protection and zeroing. The session opens wraps to any held key, and a repo wrapped only to keys this browser lacks says so: the "another approval" notice when a wallet approval registered that key, "held elsewhere" otherwise. Settings → Private repos lists every held key and always offers to add another. Co-Authored-By: Claude Opus 5.5 (1M context) --- forge-web/components/encryption-key-panel.tsx | 224 +++++++++--------- forge-web/components/repo/private-banner.tsx | 12 +- forge-web/lib/auth/controller.ts | 26 +- forge-web/lib/auth/encryption-key.test.ts | 28 +++ forge-web/lib/auth/encryption-key.ts | 208 ++++++++++------ forge-web/lib/auth/vault.ts | 151 ++++++++---- forge-web/lib/auth/wallet-encryption.test.ts | 125 ++++++++-- forge-web/lib/repo/private-members.ts | 6 +- forge-web/lib/repo/private-rotation.test.ts | 1 + forge-web/lib/repo/private-session.test.ts | 39 +++ forge-web/lib/repo/private-session.ts | 27 ++- forge-web/lib/repo/private-writes.test.ts | 1 + 12 files changed, 571 insertions(+), 277 deletions(-) diff --git a/forge-web/components/encryption-key-panel.tsx b/forge-web/components/encryption-key-panel.tsx index 70c7812f4..88bef2881 100644 --- a/forge-web/components/encryption-key-panel.tsx +++ b/forge-web/components/encryption-key-panel.tsx @@ -31,7 +31,7 @@ import { usableEncryptionKey, wipeMaterial, } from '@/lib/auth/encryption-key' -import { onEncryptionKeyChange, removeEncryptionKey, storedEncryptionKeyId } from '@/lib/auth/vault' +import { onEncryptionKeyChange, removeEncryptionKey, storedEncryptionKeyIds } from '@/lib/auth/vault' import { errorMessage } from '@/lib/utils' import { otherIdentityFileMessage } from '@/lib/auth/controller' import { PRIVATE_REPOS_ANCHOR } from '@/lib/settings-links' @@ -42,6 +42,13 @@ import { useConfirmAction } from '@/components/ui/confirm-action' type Mode = 'phrase' | 'file' | 'paste' | 'register' +/** "Encryption key 6 is" / "Encryption keys 6 and 7 are" / "Encryption keys 4, 6 and 7 are". */ +function heldKeys(ids: readonly number[]): string { + const sorted = [...ids].sort((a, b) => a - b) + if (sorted.length === 1) return `Encryption key ${sorted[0]} is` + return `Encryption keys ${sorted.slice(0, -1).join(', ')} and ${sorted[sorted.length - 1]} are` +} + /** An identity update adding one key (measured like the limited-key registration). */ const REGISTER_COST = '~0.0005 DASH' @@ -49,7 +56,8 @@ export function EncryptionKeyPanel(): JSX.Element | null { const { identity, storage, controller, unlockScope } = useAuth() const { sdk, ready, network } = useSdk() const core = NETWORKS[network].v2?.core ?? null - const [keyId, setKeyId] = useState(undefined) + /** The key ids this browser holds for the identity (null: none; undefined: not read yet). */ + const [keyIds, setKeyIds] = useState(undefined) const [mode, setMode] = useState('phrase') const [busy, setBusy] = useState(false) const [error, setError] = useState(null) @@ -63,9 +71,9 @@ export function EncryptionKeyPanel(): JSX.Element | null { if (identity === null) return let live = true const read = (): void => { - storedEncryptionKeyId(network, identity).then( - (k) => live && setKeyId(k), - () => live && setKeyId(null), + storedEncryptionKeyIds(network, identity).then( + (k) => live && setKeyIds(k.length > 0 ? k : null), + () => live && setKeyIds(null), ) } read() @@ -181,114 +189,118 @@ export function EncryptionKeyPanel(): JSX.Element | null {
- ) : keyId !== null && keyId !== undefined ? ( -
- - {storage === 'session' - ? `Encryption key ${keyId} is held for this tab only; it is forgotten on reload or lock.` - : `Encryption key ${keyId} is stored in this browser and unlocked now: private repos you're a member of open here. It locks again with this browser's key (Lock, or after 12 hours).`} - - -
- ) : keyId === null ? ( -
-

Enable private repos

-
- {( - [ - ['phrase', 'Recovery phrase'], - ['file', 'Identity file'], - ['paste', 'Paste key'], - ['register', 'Register a new key'], - ] as const - ).map(([m, label]) => ( - - ))} -
- {mode === 'phrase' ? ( -
- + {keyIds !== null ? ( +
+ + {storage === 'session' + ? `${heldKeys(keyIds)} held for this tab only; ${keyIds.length === 1 ? 'it is' : 'they are'} forgotten on reload or lock.` + : `${heldKeys(keyIds)} stored in this browser and unlocked now: private repos you're a member of open here. It locks again with this browser's key (Lock, or after 12 hours).`} + +