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..884cb2314 100644 --- a/forge-web/components/auth/wallet-connect-flow.tsx +++ b/forge-web/components/auth/wallet-connect-flow.tsx @@ -20,7 +20,10 @@ * 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 (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' @@ -35,7 +38,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 +110,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 +145,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 +194,35 @@ 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.") + // 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 + } + 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 +234,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/components/encryption-key-panel.tsx b/forge-web/components/encryption-key-panel.tsx index 70c7812f4..bba239705 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,12 +189,12 @@ export function EncryptionKeyPanel(): JSX.Element | null {
- ) : keyId !== null && keyId !== undefined ? ( + ) : keyIds !== null && keyIds !== 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).`} + ? `${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).`}
- ) : keyId === null ? ( + ) : null} + {/* Another key can always be added: one held here never blocks a newer one (DESIGN D27). */} + {unlockScope !== 'signing' && keyIds !== undefined ? (
-

Enable private repos

+

{keyIds === null ? 'Enable private repos' : 'Add another encryption key'}

{( [ diff --git a/forge-web/components/repo/private-banner.tsx b/forge-web/components/repo/private-banner.tsx index cafb43f25..9fb3170c5 100644 --- a/forge-web/components/repo/private-banner.tsx +++ b/forge-web/components/repo/private-banner.tsx @@ -27,6 +27,7 @@ import { Author } from '@/components/author' import { Button } from '@/components/ui/button' import { ConfirmDialog } from '@/components/confirm-dialog' import { PRIVATE_REPOS_SETTINGS } from '@/lib/settings-links' +import { ENCRYPTION_KEY_ELSEWHERE, ENCRYPTION_KEY_OTHER_APPROVAL } from '@/lib/auth/encryption-key' function Note({ tone, icon, children, testId }: { tone: 'caution' | 'danger' | 'info'; icon: React.ReactNode; children: React.ReactNode; testId?: string }): JSX.Element { const klass = @@ -99,7 +100,9 @@ function MemberAlerts({ home, session }: { home: RepoHome; session: PrivateSessi const maintainer = isMaintainer(session, identity) const alerts = r.alerts.filter((a) => a.kind !== 'rotationRequired') const closed = currentBurned(r) - const cannotReadCurrent = r.currentEpoch !== null && r.writeEpoch === null && !closed + // Wrapped to this reader, but only to keys this browser does not hold: say which way to get one. + const missing = session.missingKey ?? null + const cannotReadCurrent = r.currentEpoch !== null && r.writeEpoch === null && !closed && missing === null const repair = identity === null ? null : planRepair(session, identity, home.repo.forge.core) const parts: JSX.Element[] = [] if (alerts.length > 0) { @@ -111,6 +114,13 @@ function MemberAlerts({ home, session }: { home: RepoHome; session: PrivateSessi , ) } + if (missing !== null) { + parts.push( + } testId="private-missing-key"> + {missing.otherApproval ? ENCRYPTION_KEY_OTHER_APPROVAL : ENCRYPTION_KEY_ELSEWHERE} + , + ) + } if (cannotReadCurrent) { const setBy = r.currentEpoch === null ? undefined : session.anchors.get(r.currentEpoch)?.owner parts.push( @@ -156,7 +166,7 @@ function RepairNote({ home, session, self, plan }: { home: RepoHome; session: Pr const [open, setOpen] = useState(false) let cost = null try { - cost = write.context === null ? null : repairCost(session, plan, self, home.repo.forge.core, write.context.ops.keyId) + cost = write.context === null ? null : repairCost(session, plan, self, home.repo.forge.core, write.context.ops.keyIds) } catch { cost = null } diff --git a/forge-web/components/repo/private-members.tsx b/forge-web/components/repo/private-members.tsx index 00feb8e95..cafe8e1ff 100644 --- a/forge-web/components/repo/private-members.tsx +++ b/forge-web/components/repo/private-members.tsx @@ -148,7 +148,7 @@ export function PrivateMembers({ home, session }: { home: RepoHome; session: Pri try { const exclude = effect === 'rotate-exclude' ? [removing.member] : [] const from = chainFrom(session, removing.member, removing.role) - return { plan: planRotation(session, identity, exclude, repo.forge.core, write.context.ops.keyId, from), error: null } + return { plan: planRotation(session, identity, exclude, repo.forge.core, write.context.ops.keyIds, from), error: null } } catch (e) { return { plan: null, error: e instanceof Error ? e.message : String(e) } } 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/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 fff99b256..5e3af85ae 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, type WalletEncryptionOutcome } 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' @@ -912,8 +913,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(' ') }) } @@ -976,8 +977,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 - } = {}, + } & 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') @@ -993,12 +997,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( @@ -1028,9 +1032,16 @@ 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) + // Keys the vault could not carry over (by id, from its stored entries) are not reported only + // when the wallet's own keys put every one of them back. + const dropped = stored.encryptionKeysDropped ?? [] + const restored = dropped.length > 0 && dropped.every((id) => encryption.outcome?.stored.includes(id) === true) this.noteDropped( - await storeInVault(this.network, secret, protection, pending !== null ? { dropStagedKeyId: pending.keyId } : {}), + restored ? { ...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) @@ -1039,11 +1050,36 @@ export class AuthController { } } + /** + * Add the encryption keys a wallet answer stands for to the vault's keys, each that is a usable + * ENCRYPTION key of the identity (DESIGN D27, {@link adoptWalletEncryptionKey}). Signing in + * never fails on it. `notice`: the identity's usable key is held elsewhere (a key from `dg`, + * not one of the wallet's approvals), or a read failed. A usable key that another approval of + * the wallet registered is said on the repo that needs it, not here. + */ + private async keepWalletEncryptionKey( + identityId: string, + forge: ForgeIds, + 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 { outcome, notice: outcome.missing !== null && !outcome.missing.otherApproval ? ENCRYPTION_KEY_ELSEWHERE : null } + } catch (e) { + return { outcome: null, notice: `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. */ - 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 @@ -1059,6 +1095,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: @@ -1066,7 +1106,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). */ @@ -1649,3 +1689,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.test.ts b/forge-web/lib/auth/encryption-key.test.ts index 149d3ec2d..2490fca70 100644 --- a/forge-web/lib/auth/encryption-key.test.ts +++ b/forge-web/lib/auth/encryption-key.test.ts @@ -8,7 +8,7 @@ import { bytesToHex } from '@noble/hashes/utils.js' import { beforeEach, describe, expect, it } from 'vitest' -import { idbEntries, resetMemoryStores } from '../idb' +import { idbEntries, idbGet, idbPut, resetMemoryStores } from '../idb' import { encryptionMaterialFromFile, isUsableEncryptionKey, @@ -16,7 +16,11 @@ import { usableEncryptionKey, wipeMaterial, type EncKeyLike, + openLetterAs, + sealLetterAs, } from './encryption-key' +import { getPublicKey } from '@noble/secp256k1' +import { openLetter, privateId, sealLetter, type LetterRecipient, type OwnerKey, type PrivateDoc } from '../private' import { forgetVault, holdForSession, @@ -26,6 +30,8 @@ import { storeEncryptionKey, storeInVault, storedEncryptionKeyId, + storedEncryptionKeyIds, + EncryptionKeyNotHeldError, unlockWithPassphrase, withEncryptionKey, } from './vault' @@ -85,6 +91,50 @@ describe('the vault encryption-key slot', () => { expect(await storedEncryptionKeyId('devnet', ID)).toBeNull() }, 60_000) + it('keeps every key by id (a second never replaces the first), and carries all of them across a renewal', async () => { + const ENC2 = new Uint8Array(32).fill(0x43) + await storeInVault('devnet', SECRET, { passphrase: PASS }) + await storeEncryptionKey('devnet', ID, 4, new Uint8Array(ENC)) + await storeEncryptionKey('devnet', ID, 7, new Uint8Array(ENC2)) + expect(await storedEncryptionKeyIds('devnet', ID)).toEqual([7, 4]) + expect(await storedEncryptionKeyId('devnet', ID)).toBe(7) + await storeInVault('devnet', { ...SECRET, keyId: 6 }, { passphrase: 'another passphrase!' }) + expect(await withEncryptionKey('devnet', ID, async (k, s) => [k, bytesToHex(s)], 4)).toEqual([4, bytesToHex(ENC)]) + expect(await withEncryptionKey('devnet', ID, async (k, s) => [k, bytesToHex(s)], 7)).toEqual([7, bytesToHex(ENC2)]) + // No default other than the newest; a key it does not hold is named as such. + expect(await withEncryptionKey('devnet', ID, async (k) => k)).toBe(7) + await expect(withEncryptionKey('devnet', ID, async (k) => k, 5)).rejects.toBeInstanceOf(EncryptionKeyNotHeldError) + // Removing removes them all. + await removeEncryptionKey('devnet', ID) + expect(await storedEncryptionKeyIds('devnet', ID)).toEqual([]) + }, 60_000) + + it('a renewal carries every key that opens and reports the one that does not, by id', async () => { + const ENC2 = new Uint8Array(32).fill(0x43) + await storeInVault('devnet', SECRET, { passphrase: PASS }) + await storeEncryptionKey('devnet', ID, 4, new Uint8Array(ENC)) + await storeEncryptionKey('devnet', ID, 7, new Uint8Array(ENC2)) + // Key 7's entry is damaged on disk: it no longer opens. + const at = (await idbEntries('vault')).map(([k]) => String(k)).find((k) => k.startsWith('vault-enc:'))! + const entries = (await idbGet<{ keyId: number; iv: Uint8Array; ciphertext: Uint8Array }[]>('vault', at))! + const bad = entries.find((e) => e.keyId === 7)! + bad.ciphertext[0] = (bad.ciphertext[0] ?? 0) ^ 0xff + await idbPut('vault', at, entries) + const outcome = await storeInVault('devnet', { ...SECRET, keyId: 6 }, { passphrase: 'another passphrase!' }) + expect(outcome.encryptionKeyDropped).toBe(true) + expect(outcome.encryptionKeysDropped).toEqual([7]) + expect(await storedEncryptionKeyIds('devnet', ID)).toEqual([4]) + expect(await withEncryptionKey('devnet', ID, async (k, s) => [k, bytesToHex(s)])).toEqual([4, bytesToHex(ENC)]) + }, 60_000) + + it('a tab-only session keeps several keys too', async () => { + holdForSession('devnet', SECRET) + await storeEncryptionKey('devnet', ID, 4, new Uint8Array(ENC)) + await storeEncryptionKey('devnet', ID, 7, new Uint8Array(32).fill(0x43)) + expect(await storedEncryptionKeyIds('devnet', ID)).toEqual([7, 4]) + expect(await withEncryptionKey('devnet', ID, async (_k, s) => bytesToHex(s), 4)).toBe(bytesToHex(ENC)) + }) + it('can be removed on its own', async () => { await storeInVault('devnet', SECRET, { passphrase: PASS }) await storeEncryptionKey('devnet', ID, 4, new Uint8Array(ENC)) @@ -107,6 +157,37 @@ describe('the vault encryption-key slot', () => { }) }) +describe('specific-people letters with several held keys (DESIGN D27)', () => { + const OLD = new Uint8Array(32).fill(0x51) + const NEW = new Uint8Array(32).fill(0x52) + const ALICE = new Uint8Array(32).fill(0x61) + const REPO_ID = new Uint8Array(32).fill(0x11) + const me = (secret: Uint8Array): LetterRecipient => ({ identityId: privateId(ID), publicKey: getPublicKey(secret, true) }) + const alice: LetterRecipient = { identityId: new Uint8Array(32).fill(0xa1), publicKey: getPublicKey(ALICE, true) } + beforeEach(async () => { + resetMemoryStores() + lockVault() + await storeInVault('devnet', SECRET, { passphrase: PASS }) + await storeEncryptionKey('devnet', ID, 4, new Uint8Array(OLD)) + await storeEncryptionKey('devnet', ID, 7, new Uint8Array(NEW)) + }, 30_000) + + it('opens a letter sealed to the older held key', async () => { + const doc: PrivateDoc = { type: 'comment', vis: 'public', ownerId: alice.identityId, epoch: 0, targetId: new Uint8Array(32).fill(0x33) } + const enc = await sealLetter(REPO_ID, ALICE, 3, doc, { body: 'to the old key' }, [alice, me(OLD)]) + const owner: OwnerKey[] = [{ id: 3, purpose: 1, keyType: 0, data: alice.publicKey }] + expect(await openLetterAs('devnet', ID, { repoId: REPO_ID, doc: { ...doc, enc }, ownerKeys: owner })).toMatchObject({ status: 'readable', fields: { body: 'to the old key' } }) + }) + + it('seals from the held key its sender slot names, and refuses one this browser does not hold', async () => { + const doc: PrivateDoc = { type: 'comment', vis: 'public', ownerId: privateId(ID), epoch: 0, targetId: new Uint8Array(32).fill(0x33) } + const enc = await sealLetterAs('devnet', ID, { repoId: REPO_ID, doc, fields: { body: 'from key 4' }, recipients: [me(OLD), alice] }) + const owner: OwnerKey[] = [{ id: 4, purpose: 1, keyType: 0, data: getPublicKey(OLD, true) }] + expect(await openLetter(REPO_ID, { ...doc, enc }, owner, { identityId: alice.identityId, secrets: [ALICE] })).toMatchObject({ status: 'readable', fields: { body: 'from key 4' } }) + await expect(sealLetterAs('devnet', ID, { repoId: REPO_ID, doc, fields: { body: 'x' }, recipients: [me(new Uint8Array(32).fill(0x53)), alice] })).rejects.toThrow(/does not hold/) + }) +}) + describe('which encryption key counts', () => { const k = (keyId: number, extra: Partial = {}): EncKeyLike => ({ keyId, purposeNumber: 1, keyTypeNumber: 0, data: '02', ...extra }) const bound = (id: string, $type = 'singleContract') => ({ toJSON: () => ({ $type, id }) }) diff --git a/forge-web/lib/auth/encryption-key.ts b/forge-web/lib/auth/encryption-key.ts index 120fe71ea..04bac9a35 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 @@ -18,10 +19,12 @@ * The raw key never 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' import { + WrapError, bytesToHex, openLetter, privateId, @@ -44,7 +47,17 @@ import { deriveAt, deriveMasterKey, identityKeyPath, isValidMnemonic, invalidMne import { parsePrivateKey } from './wif' import { WrongMasterKeyError, assertMasterKeyOf, sendIdentityUpdate } from './limited-key' import { shortId } from '../utils' -import { VaultLockedError, storeEncryptionKey, storedEncryptionKeyId, unlockScope, unlockedSecret, withEncryptionKey } from './vault' +import { + EncryptionKeyNotHeldError, + VaultLockedError, + storeEncryptionKey, + storedEncryptionKeyId, + storedEncryptionKeyIds, + unlockScope, + unlockedSecret, + withEncryptionKey, + withEncryptionKeys, +} from './vault' /** The step-timing flow of enabling private repos at sign-in (L-20). */ export const PRIVATE_REPOS_FLOW = 'enable-private-repos' @@ -132,6 +145,99 @@ export async function adoptEncryptionKey(sdk: EvoSDK, network: Network, identity } } +/** + * The identity's usable encryption key (the one writers wrap to) is not one this browser holds, + * and no approval of the wallet registered it (a key from `dg`, say). Shown at sign-in. + */ +export const ENCRYPTION_KEY_ELSEWHERE = 'Your encryption key is held elsewhere. Import it under Settings → Private repos.' + +/** + * A repo was wrapped only to keys this browser does not hold, and the one it was wrapped to last + * 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). Approving that contract + * here again brings it. Shown on the repo. + */ +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 + +/** + * Whether encryption key `keyId` of an identity is one a wallet registered: a wallet adds its + * encryption key right after its HASH160 auth key, in one update. + */ +export function walletRegistered(keys: readonly Pick[], keyId: number): boolean { + return keys.some((k) => k.keyId === keyId - 1 && k.purposeNumber === PURPOSE_AUTHENTICATION && k.keyTypeNumber === KEY_TYPE_ECDSA_HASH160) +} + +/** What became of the encryption keys a wallet answer stands for ({@link adoptWalletEncryptionKey}). */ +export interface WalletEncryptionOutcome { + /** The key ids of the wallet's keys now sealed in the vault (each a usable ENCRYPTION key of the identity). */ + readonly stored: readonly number[] + /** + * The identity's usable key (the one writers wrap to) when this browser holds none by that id + * (null: held, or the identity has none). `otherApproval`: an approval of the wallet registered it. + */ + readonly missing: { readonly keyId: number; readonly otherApproval: boolean } | null +} + +/** + * Keep the encryption keys a wallet answer stands for (DESIGN D27): the wallet derives + * `HKDF(loginKey, identityId, "encryption")` for each login key and registers it beside the auth + * key the first time it approves a contract; a returning login derives the same one. `candidates` + * are those private keys. Each whose public key is an enabled, usable ENCRYPTION key of the + * identity is ADDED to the vault's keys (beside the wallet key, under the same protection); no key + * already there is replaced, so wraps made to an older key still open. Anything else is a key no + * wrap could be sealed to, and is not 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 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 + } + const stored: number[] = [] + for (const k of keys) { + const at = pubs.indexOf(k.data.toLowerCase()) + if (at < 0 || !isUsableEncryptionKey(k, coreId)) continue + await timed(PRIVATE_REPOS_FLOW, 'seal into the vault', () => storeEncryptionKey(network, identityId, k.keyId, secrets[at] as Uint8Array)) + stored.push(k.keyId) + } + const usable = usableEncryptionKey(keys, coreId) + const held = usable === null || (await storedEncryptionKeyIds(network, identityId)).includes(usable.keyId) + return { stored, missing: held ? null : { keyId: usable.keyId, otherApproval: walletRegistered(keys, 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 @@ -332,14 +438,28 @@ export async function registerEncryptionKey( } } +/** "encryption key 6" / "encryption keys 6 and 8" (held key ids, in any order). */ +export function heldKeysText(held: readonly number[]): string { + const ids = [...held].sort((a, b) => a - b) + return ids.length === 1 ? `encryption key ${ids[0]}` : `encryption keys ${ids.slice(0, -1).join(', ')} and ${ids[ids.length - 1]}` +} + /** What a private-repo read or write may do with the vault's encryption key. */ export interface EncryptionOps { - /** The key id of the stored encryption key on this identity. */ + /** + * The highest key id this browser holds for the identity. Not necessarily still enabled: a + * writer sends from the newest USABLE key among {@link keyIds} (`usableEncryptionKey` over the + * identity's keys filtered to them). + */ readonly keyId: number + /** Every key id this browser holds for the identity, highest first ({@link keyId} among them). */ + readonly keyIds: readonly number[] /** * Decrypt a `repoKey` (the reader's own, or one it sent) and check its version and `KCV_e`. * `counterpartyKey` is the other side's ENCRYPTION public key: the sender's for a wrap to - * this identity (its own key for a self-wrap), the recipient's for a wrap it sent. + * this identity (its own key for a self-wrap), the recipient's for a wrap it sent. The private + * key is the held one the document names (`recipientKeyId`, else `senderKeyId`); a document + * naming neither is tried with each held key in turn. */ unwrap(p: UnwrapInput): Promise /** {@link unwrap}, also returning the raw epoch key (wipe it after use). */ @@ -351,6 +471,23 @@ export interface EncryptionOps { wrap(p: { keys: EpochKeys; raw: Uint8Array; senderKey: IdentityPublicKey; recipientKey: IdentityPublicKey }): Promise> } +/** A key id a `repoKey` document names (`recipientKeyId` / `senderKeyId`), when it is one. */ +function namedKeyId(doc: Record, field: string): number | null { + const v = doc[field] + const n = typeof v === 'bigint' ? Number(v) : v + return typeof n === 'number' && Number.isSafeInteger(n) && n >= 0 ? n : null +} + +/** + * Which held keys may open `doc`, in order: the held ones it names (the reader's own key is the + * recipient of a wrap to it and the sender of one it sent), else, naming none, every held key. + */ +export function keysToTry(doc: Record, held: readonly number[]): number[] { + const named = [namedKeyId(doc, 'recipientKeyId'), namedKeyId(doc, 'senderKeyId')].filter((n): n is number => n !== null) + if (named.length === 0) return [...held] + return [...new Set(named)].filter((n) => held.includes(n)) +} + export interface UnwrapInput { /** The `repoKey` document as a query returns it (the `toJSON` form). */ readonly document: Record @@ -366,25 +503,47 @@ export interface UnwrapInput { * key from the unlocked vault and wipes it after; a locked vault makes the call throw. */ export async function encryptionOps(sdk: EvoSDK, network: Network, identityId: string, repoKeyContractId: string): Promise { - const keyId = await storedEncryptionKeyId(network, identityId) - if (keyId === null) return null + const keyIds = await storedEncryptionKeyIds(network, identityId) + const keyId = keyIds[0] + if (keyId === undefined) return null const facade = (sdk as unknown as { encryptedFor: WrapFacade }).encryptedFor const { Document, PrivateKey } = await import('@dashevo/evo-sdk') const contract = (await authSdk(sdk).contracts.fetch(repoKeyContractId)) as DataContract | undefined if (contract === undefined) throw new Error('forge-collab could not be read') const version = (sdk as unknown as { version(): number }).version() const net = wasmNetwork(network) - const withPrivate = (use: (pk: WasmPrivateKey) => Promise): Promise => - withEncryptionKey(network, identityId, async (heldId, secret) => { - // The stored key was replaced since these ops were made: their key id no longer matches. - if (heldId !== keyId) throw new VaultLockedError('the encryption key in this browser changed; reload') - const pk = PrivateKey.fromBytes(secret, net) + const withPrivate = (id: number, use: (pk: WasmPrivateKey) => Promise): Promise => + withEncryptionKey( + network, + identityId, + async (_heldId, secret) => { + const pk = PrivateKey.fromBytes(secret, net) + try { + return await use(pk) + } finally { + pk.free() + } + }, + id, + ).catch((e: unknown) => { + // The stored keys changed since these ops were made (removed here or in another tab). + throw e instanceof EncryptionKeyNotHeldError ? new VaultLockedError('the encryption keys in this browser changed; reload') : e + }) + /** Open `p` with each held key it may be wrapped to, in turn: the first that opens it wins. */ + const withReader = async (p: UnwrapInput, open: (pk: WasmPrivateKey) => Promise): Promise => { + const ids = keysToTry(p.document, keyIds) + if (ids.length === 0) throw new WrapError('wrapUnreadable') + let last: unknown + for (const id of ids) { try { - return await use(pk) - } finally { - pk.free() + return await withPrivate(id, open) + } catch (e) { + if (!(e instanceof WrapError)) throw e + last = e } - }) + } + throw last + } const params = (p: UnwrapInput, pk: WasmPrivateKey) => ({ dataContract: contract, document: Document.fromJSON(p.document as Parameters[0], version) as Document, @@ -395,10 +554,12 @@ export async function encryptionOps(sdk: EvoSDK, network: Network, identityId: s }) return { keyId, - unwrap: (p) => withPrivate((pk) => unwrapKey(facade, params(p, pk))), - unwrapRaw: (p) => withPrivate((pk) => unwrapKeyRaw(facade, params(p, pk))), + keyIds, + unwrap: (p) => withReader(p, (pk) => unwrapKey(facade, params(p, pk))), + unwrapRaw: (p) => withReader(p, (pk) => unwrapKeyRaw(facade, params(p, pk))), + // Sent from the held key the caller named as the sender (the identity's newest usable one). wrap: (p) => - withPrivate((pk) => + withPrivate(p.senderKey.keyId, (pk) => sealWrap(facade, p.keys, p.raw, { dataContract: contract, senderKey: p.senderKey, senderPrivateKey: pk, recipientKey: p.recipientKey }), ), } @@ -407,29 +568,36 @@ export async function encryptionOps(sdk: EvoSDK, network: Network, identityId: s /** * Seal a specific-people letter (`enc` v0x04, `lib/private/named`) from this browser's stored * encryption key for (network, identity): the sender's slot is `recipients[0]`, which must be - * this identity and that key. The key is opened from the vault for the call and wiped after; a - * locked vault makes the call throw. + * this identity, and the held key whose public key it names sends it (this browser may hold + * several, DESIGN D27). The keys are opened from the vault for the call and wiped after; a locked + * vault makes the call throw, and so does a sender key this browser does not hold. */ export function sealLetterAs( network: Network, identityId: string, p: { readonly repoId: Uint8Array; readonly doc: PrivateDoc; readonly fields: DocFields; readonly recipients: readonly LetterRecipient[] }, ): Promise { - return withEncryptionKey(network, identityId, (keyId, secret) => sealLetter(p.repoId, secret, keyId, p.doc, p.fields, p.recipients)) + const senderPub = p.recipients[0] === undefined ? '' : bytesToHex(p.recipients[0].publicKey) + return withEncryptionKeys(network, identityId, async (keys) => { + const sender = keys.find((k) => bytesToHex(secp.getPublicKey(k.secret, true)) === senderPub) + if (sender === undefined) throw new VaultLockedError("this browser does not hold the encryption key the letter's sender slot names") + return sealLetter(p.repoId, sender.secret, sender.keyId, p.doc, p.fields, p.recipients) + }) } /** - * Open a specific-people letter as (network, identity) with this browser's stored encryption - * key; `ownerKeys` are the document owner's identity keys, where the sender key is looked up. - * The key is wiped after the call; a locked vault makes the call throw. + * Open a specific-people letter as (network, identity) with every encryption key this browser + * holds for it (a letter does not say which of the reader's keys it was sealed to); `ownerKeys` + * are the document owner's identity keys, where the sender key is looked up. The keys are wiped + * after the call; a locked vault makes the call throw. */ export function openLetterAs( network: Network, identityId: string, p: { readonly repoId: Uint8Array; readonly doc: StoredPrivateDoc; readonly ownerKeys: readonly OwnerKey[] }, ): Promise { - return withEncryptionKey(network, identityId, (_keyId, secret) => - openLetter(p.repoId, p.doc, p.ownerKeys, { identityId: privateId(identityId), secrets: [secret] }), + return withEncryptionKeys(network, identityId, (keys) => + openLetter(p.repoId, p.doc, p.ownerKeys, { identityId: privateId(identityId), secrets: keys.map((k) => k.secret) }), ) } @@ -450,12 +618,15 @@ export type WebhookSealer = * the vault and wipes it; a locked vault makes the call throw. */ export async function webhookSealer(sdk: EvoSDK, network: Network, identityId: string, communityId: string): Promise { - const keyId = await storedEncryptionKeyId(network, identityId) - if (keyId === null) return { kind: 'no-key' } + const held = await storedEncryptionKeyIds(network, identityId) + if (held.length === 0) return { kind: 'no-key' } const mine = await requireIdentityKeys(sdk, identityId) - const senderKey = mine.find((k) => k.keyId === keyId) - if (senderKey === undefined || senderKey.disabledAt !== undefined || senderKey.purposeNumber !== PURPOSE_ENCRYPTION) return { kind: 'unusable' } - if (!isUsableEncryptionKey(senderKey, communityId)) return { kind: 'wrong-contract' } + // The highest held key that is still an enabled ENCRYPTION key of the identity, usable here. + const live = held.map((id) => mine.find((k) => k.keyId === id)).filter((k): k is NonNullable => k !== undefined && k.disabledAt === undefined && k.purposeNumber === PURPOSE_ENCRYPTION) + if (live.length === 0) return { kind: 'unusable' } + const senderKey = live.find((k) => isUsableEncryptionKey(k, communityId)) + if (senderKey === undefined) return { kind: 'wrong-contract' } + const keyId = senderKey.keyId const facade = (sdk as unknown as { encryptedFor: WrapFacade }).encryptedFor const { PrivateKey } = await import('@dashevo/evo-sdk') const net = wasmNetwork(network) @@ -466,22 +637,28 @@ export async function webhookSealer(sdk: EvoSDK, network: Network, identityId: s if (recipientKey === null) throw new Error(`relay ${recipientIdentityId} has no enabled ECDSA_SECP256K1 ENCRYPTION key to encrypt the secret to`) const contract = (await authSdk(sdk).contracts.fetch(communityId)) as DataContract | undefined if (contract === undefined) throw new Error('forge-community could not be read') - return withEncryptionKey(network, identityId, async (heldId, secret) => { - if (heldId !== keyId) throw new VaultLockedError('the encryption key in this browser changed; reload') - const pk = PrivateKey.fromBytes(secret, net) - try { - return await facade.encrypt({ - dataContract: contract, - documentTypeName: 'webhook', - property: 'secret', - plaintext, - senderKey, - senderPrivateKey: pk, - recipientKey, - }) - } finally { - pk.free() - } + return withEncryptionKey( + network, + identityId, + async (_heldId, secret) => { + const pk = PrivateKey.fromBytes(secret, net) + try { + return await facade.encrypt({ + dataContract: contract, + documentTypeName: 'webhook', + property: 'secret', + plaintext, + senderKey, + senderPrivateKey: pk, + recipientKey, + }) + } finally { + pk.free() + } + }, + keyId, + ).catch((e: unknown) => { + throw e instanceof EncryptionKeyNotHeldError ? new VaultLockedError('the encryption keys in this browser changed; reload') : e }) } return { kind: 'ready', seal } diff --git a/forge-web/lib/auth/vault.ts b/forge-web/lib/auth/vault.ts index fba3a6710..825ab9975 100644 --- a/forge-web/lib/auth/vault.ts +++ b/forge-web/lib/auth/vault.ts @@ -545,9 +545,12 @@ export interface StoreOutcome { readonly storageSettingsDropped: boolean /** * An encryption key was stored but could not be carried across (the vault was locked when the - * key was renewed). It is deleted; the user imports it again in Settings → Keys. + * key was renewed, or this tab holds a tab-only key that cannot open the stored ones). It is + * deleted; the user imports it again in Settings → Private repos. */ readonly encryptionKeyDropped: boolean + /** The key ids of the dropped encryption keys (the ones that did carry across are kept). */ + readonly encryptionKeysDropped?: readonly number[] /** * The record was written but did not read back: this browser's storage may not keep it. The * session works; the UI warns to keep the identity file handy. @@ -762,15 +765,10 @@ export async function recoverStaged( // Carry the old record's blobs across when this session has them open (the old key was // unlocked just before), sealed under the staged record's blob keys. const carried = await readStorageBlob(network, identityId).catch(() => null) - const carriedEnc = unlocked?.sessionEnc === undefined ? await readEncryptionBlob(network, identityId).catch(() => null) : null + const carriedEnc = unlocked?.sessionEnc === undefined ? await readEncryptionBlobs(network, identityId).catch(() => []) : [] const hadBlob = (await idbGet('vault', storageBlobKey(network, identityId))) !== undefined - const hadEnc = (await idbGet('vault', encryptionBlobKey(network, identityId))) !== undefined - let encBlob: EncryptionBlob | undefined - try { - encBlob = carriedEnc !== null ? await sealEncryptionBlob(opened.blobKeys.encryption, network, identityId, carriedEnc.keyId, carriedEnc.secret) : undefined - } finally { - carriedEnc?.secret.fill(0) - } + const droppedEnc = await droppedEncryptionIds(network, identityId, carriedEnc) + const encBlob = await sealEncryptionBlobs(opened.blobKeys.encryption, network, identityId, carriedEnc) const blob = carried !== null ? await sealBlob(opened.blobKeys.storage, network, identityId, carried) : undefined const { replaces: _replaces, ...promoted } = record let raced = false @@ -801,7 +799,7 @@ export async function recoverStaged( return { status: 'adopted', secret: opened.secret, - outcome: { storageSettingsDropped: hadBlob && carried === null, encryptionKeyDropped: hadEnc && carriedEnc === null }, + outcome: { storageSettingsDropped: hadBlob && carried === null, encryptionKeyDropped: droppedEnc.length > 0, encryptionKeysDropped: droppedEnc }, } } @@ -917,8 +915,9 @@ export async function storeInVault( const carried = hadBlob ? await readStorageBlob(network, identityId).catch(() => null) : null // The encryption key is carried the same way, but only from the stored vault blob: a tab-only // session's key stays in that session. One that cannot be opened is dropped, and reported. - const hadEnc = (await idbGet('vault', encryptionBlobKey(network, identityId))) !== undefined - const carriedEnc = hadEnc && unlocked?.sessionEnc === undefined ? await readEncryptionBlob(network, identityId).catch(() => null) : null + // Each key that opens is carried; any other is dropped, and reported by id. + const carriedEnc = unlocked?.sessionEnc === undefined ? await readEncryptionBlobs(network, identityId).catch(() => []) : [] + const droppedEnc = await droppedEncryptionIds(network, identityId, carriedEnc) const dataKey = random(32) let storageKey: CryptoKey let encryptionKey: CryptoKey @@ -931,14 +930,7 @@ export async function storeInVault( const blob = carried !== null ? await sealBlob(storageKey, network, identityId, carried) : undefined const extraBlob = extra?.length ? await sealBlob(storageKey, network, identityId, extra, 'extra') : undefined encryptionKey = await deriveEncryptionKey(dataKey, network, identityId) - let encBlob: EncryptionBlob | undefined - if (carriedEnc !== null) { - try { - encBlob = await sealEncryptionBlob(encryptionKey, network, identityId, carriedEnc.keyId, carriedEnc.secret) - } finally { - carriedEnc.secret.fill(0) - } - } + const encBlob = await sealEncryptionBlobs(encryptionKey, network, identityId, carriedEnc) // One transaction: a crash between the writes must not leave settings sealed under a // data key no record holds any more. The key is now the main record, so a staged copy of // THIS key (the renewal that registered it) is done; a stage of another key (a renewal @@ -960,7 +952,8 @@ export async function storeInVault( setUnlocked(network, secret, { storage: storageKey, encryption: encryptionKey }, { lockMarkerAt }) return { storageSettingsDropped: hadBlob && carried === null, - encryptionKeyDropped: hadEnc && carriedEnc === null, + encryptionKeyDropped: droppedEnc.length > 0, + encryptionKeysDropped: droppedEnc, ...(readBackOk ? {} : { readBackFailed: true }), } } @@ -1042,7 +1035,7 @@ function unlockedStorageKey(network: Network, identityId: string): CryptoKey | n /** The vaults stored for `network` (no secrets). */ export async function listVaults(network: Network): Promise { const rows = await idbEntries('vault', `vault:${network}:`) - const withEnc = new Set((await idbEntries('vault', `vault-enc:${network}:`)).map(([k]) => k)) + const withEnc = new Set((await idbEntries('vault', `vault-enc:${network}:`)).filter(([, v]) => encryptionEntries(v).length > 0).map(([k]) => k)) const out: VaultInfo[] = rows.map(([, r]) => ({ identityId: r.identityId, keyId: r.keyId, @@ -1188,7 +1181,7 @@ interface Unlocked { at: number blobKeys: BlobKeys | null /** Tab-only sessions: the encryption key, sealed under a random per-session key. */ - sessionEnc?: { key: CryptoKey; blob: EncryptionBlob | null } + sessionEnc?: { key: CryptoKey; blobs: readonly EncryptionBlob[] } /** * `signing`: picked up from a kept session. Only the limited signing key is here; the * encryption key, storage settings and wallet grants need an interactive unlock @@ -1419,13 +1412,27 @@ export function releaseUnlocked(): void { // The identity's ENCRYPTION key (private repos, `docs/security/private-repos.md` §5.2) // --------------------------------------------------------------------------- -/** The sealed encryption key: its key id on the identity (public) and the sealed private key. */ +/** One sealed encryption key: its key id on the identity (public) and the sealed private key. */ interface EncryptionBlob { readonly keyId: number readonly iv: Uint8Array readonly ciphertext: Uint8Array } +/** + * What the vault keeps for an identity's encryption keys: every key this browser has held for it, + * one sealed entry per on-chain key id (DESIGN D27: a wallet registers a new one with each first + * approval for another contract, and wraps made to an older key must still open). A vault written + * before that holds a single entry, read as a set of one. + */ +type StoredEncryption = EncryptionBlob | readonly EncryptionBlob[] + +/** The entries of a stored value, highest key id first (a legacy single entry: a set of one). */ +function encryptionEntries(v: StoredEncryption | undefined | null): EncryptionBlob[] { + if (v === undefined || v === null) return [] + return (Array.isArray(v) ? [...(v as readonly EncryptionBlob[])] : [v as EncryptionBlob]).sort((a, b) => b.keyId - a.keyId) +} + function encryptionAad(network: Network, identityId: string, keyId: number): Uint8Array { return aad(network, identityId, `encryption|${keyId}`) } @@ -1437,6 +1444,22 @@ async function sealEncryptionBlob(key: CryptoKey, network: Network, identityId: return { keyId, iv, ciphertext: new Uint8Array(ct) } } +/** Seal every carried key under `key` (each secret is wiped); undefined when there is none. */ +async function sealEncryptionBlobs( + key: CryptoKey, + network: Network, + identityId: string, + carried: readonly { readonly keyId: number; readonly secret: Uint8Array }[], +): Promise { + try { + const sealed: EncryptionBlob[] = [] + for (const c of carried) sealed.push(await sealEncryptionBlob(key, network, identityId, c.keyId, c.secret)) + return sealed.length > 0 ? sealed : undefined + } finally { + for (const c of carried) c.secret.fill(0) + } +} + async function openEncryptionBlob(key: CryptoKey, network: Network, identityId: string, blob: EncryptionBlob): Promise { try { const plain = new Uint8Array( @@ -1452,26 +1475,49 @@ async function openEncryptionBlob(key: CryptoKey, network: Network, identityId: } } -/** The unlocked session's encryption blob and the key it is sealed under, or null. */ -async function encryptionSource(network: Network, identityId: string): Promise<{ key: CryptoKey; blob: EncryptionBlob } | null> { +/** The unlocked session's encryption entries and the key they are sealed under, or null (none). */ +async function encryptionSource(network: Network, identityId: string): Promise<{ key: CryptoKey; blobs: EncryptionBlob[] } | null> { if (unlockedSecret(network, identityId) === null || unlocked === null) return null - if (unlocked.sessionEnc !== undefined) return unlocked.sessionEnc.blob === null ? null : { key: unlocked.sessionEnc.key, blob: unlocked.sessionEnc.blob } + if (unlocked.sessionEnc !== undefined) { + const blobs = encryptionEntries(unlocked.sessionEnc.blobs) + return blobs.length === 0 ? null : { key: unlocked.sessionEnc.key, blobs } + } const k = unlocked.blobKeys?.encryption if (k === undefined) return null - const blob = await idbGet('vault', encryptionBlobKey(network, identityId)) - return blob === undefined ? null : { key: k, blob } + const blobs = encryptionEntries(await idbGet('vault', encryptionBlobKey(network, identityId))) + return blobs.length === 0 ? null : { key: k, blobs } } -/** The stored encryption key's plaintext, for re-sealing on renewal. Needs the vault unlocked. */ -async function readEncryptionBlob(network: Network, identityId: string): Promise<{ keyId: number; secret: Uint8Array } | null> { +/** + * The plaintext of every stored encryption key this unlocked session can open, for re-sealing on + * renewal: an entry that does not open is left out (and reported dropped), never the whole set. + */ +async function readEncryptionBlobs(network: Network, identityId: string): Promise<{ keyId: number; secret: Uint8Array }[]> { const src = await encryptionSource(network, identityId) - if (src === null) return null - return { keyId: src.blob.keyId, secret: await openEncryptionBlob(src.key, network, identityId, src.blob) } + if (src === null) return [] + const out: { keyId: number; secret: Uint8Array }[] = [] + for (const b of src.blobs) { + try { + out.push({ keyId: b.keyId, secret: await openEncryptionBlob(src.key, network, identityId, b) }) + } catch { + /* not carried: reported by droppedEncryptionIds */ + } + } + return out +} + +/** + * The key ids stored in the vault for the identity (its raw entries, whatever this tab can open) + * that `carried` does not include: what a re-key is about to delete. + */ +async function droppedEncryptionIds(network: Network, identityId: string, carried: readonly { readonly keyId: number }[]): Promise { + const stored = encryptionEntries(await idbGet('vault', encryptionBlobKey(network, identityId))).map((b) => b.keyId) + return stored.filter((id) => !carried.some((c) => c.keyId === id)) } const encListeners = new Set<() => void>() -/** Be told when the encryption key is added, removed, or becomes unusable (lock). */ +/** Be told when an encryption key is added, removed, or becomes unusable (lock). */ export function onEncryptionKeyChange(listener: () => void): () => void { encListeners.add(listener) return () => { @@ -1484,31 +1530,37 @@ function notifyEncryptionKeyChange(): void { } /** The tab-only session's encryption slot for (network, identity), or undefined. */ -function sessionEncFor(network: Network, identityId: string): { key: CryptoKey; blob: EncryptionBlob | null } | undefined { +function sessionEncFor(network: Network, identityId: string): { key: CryptoKey; blobs: readonly EncryptionBlob[] } | undefined { // Not `unlockedSecret()`: that one auto-locks an expired session, which a read must not do. return unlockedFor(network, identityId)?.sessionEnc } /** - * Whether an encryption key is stored for (network, identity), and its key id (public: it is - * on the identity). Readable while locked; using it needs the vault unlocked. + * The key ids (public: they are on the identity) of every encryption key stored for (network, + * identity), highest first; empty when none. Readable while locked; using one needs the vault + * unlocked. */ -export async function storedEncryptionKeyId(network: Network, identityId: string): Promise { +export async function storedEncryptionKeyIds(network: Network, identityId: string): Promise { const session = sessionEncFor(network, identityId) - if (session !== undefined) return session.blob?.keyId ?? null + if (session !== undefined) return encryptionEntries(session.blobs).map((b) => b.keyId) // Unlocked for this identity by a tab-only key: a vault blob it cannot open does not count. // (A resumed signing-only session has no blob keys either, but the blob is its own: it counts, // and using it asks for an interactive unlock.) const u = unlockedFor(network, identityId) - if (u !== null && u.blobKeys === null && u.scope === 'full') return null - const blob = await idbGet('vault', encryptionBlobKey(network, identityId)) - return blob?.keyId ?? null + if (u !== null && u.blobKeys === null && u.scope === 'full') return [] + return encryptionEntries(await idbGet('vault', encryptionBlobKey(network, identityId))).map((b) => b.keyId) +} + +/** The highest key id among {@link storedEncryptionKeyIds}, or null when none is stored. */ +export async function storedEncryptionKeyId(network: Network, identityId: string): Promise { + return (await storedEncryptionKeyIds(network, identityId))[0] ?? null } /** * Seal the identity's encryption private key (32 bytes, key `keyId` on the identity) beside the - * unlocked vault record, replacing any earlier one. A tab-only session holds it for the session - * only. The caller has verified it against the identity and wipes `secret` afterwards. + * unlocked vault record, ADDED to the keys already there (a key of the same id is resealed; no + * other is ever replaced). A tab-only session holds it for the session only. The caller has + * verified it against the identity and wipes `secret` afterwards. */ export async function storeEncryptionKey(network: Network, identityId: string, keyId: number, secret: Uint8Array): Promise { assertDedicatedOrigin() @@ -1516,30 +1568,45 @@ export async function storeEncryptionKey(network: Network, identityId: string, k // A resumed signing-only tab has no blob keys either, but its vault does: seal there after an // interactive unlock, never into this tab's memory (it would be lost on reload). if (unlocked.scope === 'signing') throw new VaultLockedError('unlock this tab first: your encryption key is stored with the rest of the vault') + const add = (current: StoredEncryption | undefined, sealed: EncryptionBlob): EncryptionBlob[] => [...encryptionEntries(current).filter((b) => b.keyId !== keyId), sealed] if (unlocked.blobKeys === null) { // A tab-only session: sealed under a random key that lives as long as the session. - const key = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']) - unlocked.sessionEnc = { key, blob: await sealEncryptionBlob(key, network, identityId, keyId, secret) } + const held = unlocked.sessionEnc + const key = held?.key ?? (await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])) + const sealed = await sealEncryptionBlob(key, network, identityId, keyId, secret) + unlocked.sessionEnc = { key, blobs: add(held?.blobs, sealed) } } else { - await idbPut('vault', encryptionBlobKey(network, identityId), await sealEncryptionBlob(unlocked.blobKeys.encryption, network, identityId, keyId, secret)) + const sealed = await sealEncryptionBlob(unlocked.blobKeys.encryption, network, identityId, keyId, secret) + const at = encryptionBlobKey(network, identityId) + // Read and written in one transaction: a key another tab adds meanwhile is kept. + await idbUpdate('vault', at, (current) => [[at, add(current, sealed)]]) } notifyEncryptionKeyChange() } -/** Delete the stored encryption key (it can be imported again from the identity file). */ +/** Delete every stored encryption key (each can be imported again from the identity file). */ export async function removeEncryptionKey(network: Network, identityId: string): Promise { const session = sessionEncFor(network, identityId) - if (session !== undefined && unlocked !== null) unlocked.sessionEnc = { key: session.key, blob: null } + if (session !== undefined && unlocked !== null) unlocked.sessionEnc = { key: session.key, blobs: [] } await idbDelete('vault', encryptionBlobKey(network, identityId)) notifyEncryptionKeyChange() } +/** This browser does not hold encryption key `keyId` of the identity. */ +export class EncryptionKeyNotHeldError extends Error { + constructor(readonly keyId: number) { + super(`this browser does not hold encryption key ${keyId}`) + this.name = 'EncryptionKeyNotHeldError' + } +} + /** - * Run `use` with the unlocked encryption private key (a fresh copy, wiped afterwards). Module - * internal: callers get the {@link EncryptionOps} of `lib/auth/encryption-key.ts`, which pass the - * key only to the SDK. Throws {@link VaultLockedError} when locked or when no key is stored. + * Run `use` with an unlocked encryption private key (a fresh copy, wiped afterwards): key `keyId` + * ({@link EncryptionKeyNotHeldError} when this browser does not hold it), else the highest held. + * Module internal: callers get the {@link EncryptionOps} of `lib/auth/encryption-key.ts`, which + * pass the key only to the SDK. Throws {@link VaultLockedError} when locked or when none is stored. */ -export async function withEncryptionKey(network: Network, identityId: string, use: (keyId: number, secret: Uint8Array) => Promise): Promise { +export async function withEncryptionKey(network: Network, identityId: string, use: (keyId: number, secret: Uint8Array) => Promise, keyId?: number): Promise { const src = await encryptionSource(network, identityId) if (src === null) { const scope = unlockScope(network, identityId) @@ -1547,14 +1614,38 @@ export async function withEncryptionKey(network: Network, identityId: string, scope === null ? 'unlock this browser to read private repos' : scope === 'signing' ? 'unlock to use your encryption key in this tab' : 'no encryption key is stored in this browser', ) } - const secret = await openEncryptionBlob(src.key, network, identityId, src.blob) + const blob = keyId === undefined ? src.blobs[0] : src.blobs.find((b) => b.keyId === keyId) + if (blob === undefined) throw new EncryptionKeyNotHeldError(keyId ?? -1) + const secret = await openEncryptionBlob(src.key, network, identityId, blob) try { - return await use(src.blob.keyId, secret) + return await use(blob.keyId, secret) } finally { secret.fill(0) } } +/** + * Run `use` with every held encryption private key of (network, identity), highest key id first + * (fresh copies, all wiped afterwards): for a reader that cannot tell from a document which of its + * keys it was sealed to. An entry that does not open is left out. Module internal, as + * {@link withEncryptionKey}; throws {@link VaultLockedError} when locked or none is stored. + */ +export async function withEncryptionKeys(network: Network, identityId: string, use: (keys: readonly { readonly keyId: number; readonly secret: Uint8Array }[]) => Promise): Promise { + const src = await encryptionSource(network, identityId) + if (src === null) { + const scope = unlockScope(network, identityId) + throw new VaultLockedError( + scope === null ? 'unlock this browser to read private repos' : scope === 'signing' ? 'unlock to use your encryption key in this tab' : 'no encryption key is stored in this browser', + ) + } + const keys = await readEncryptionBlobs(network, identityId) + try { + return await use(keys) + } finally { + for (const k of keys) k.secret.fill(0) + } +} + /** * Lock (sign-out, Lock, forget, revoke, a key found disabled on chain): forget the unlocked * secret here, delete the kept session, and lock every other tab. The stored record stays. 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..13da17c83 --- /dev/null +++ b/forge-web/lib/auth/wallet-encryption.test.ts @@ -0,0 +1,420 @@ +/** + * 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, idbGet, idbPut, resetMemoryStores } from '../idb' +import { AuthController } from './controller' +import { ENCRYPTION_KEY_ELSEWHERE, ENCRYPTION_KEY_OTHER_APPROVAL, adoptWalletEncryptionKey, encryptionKeyState, encryptionOps, type EncryptionOps, type UnwrapInput } from './encryption-key' +import { WrapError } from '../private' +import type { WalletKey } from './key-registration' +import { holdForSession, lockVault, releaseUnlocked, storeEncryptionKey, storeInVault, storedEncryptionKeyId, storedEncryptionKeyIds, 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 }, +})) +// A wrap opens only with the private key it was sealed to (`opensWith`, when the test says). +vi.mock('../private', async (orig) => { + const real = await orig() + return { + ...real, + unwrapKey: async (_facade: unknown, p: { readerPrivateKey: { hex: string }; repoId: Uint8Array; document: Record }) => { + const want = p.document['opensWith'] + if (typeof want === 'string' && want !== p.readerPrivateKey.hex) throw new real.WrapError('wrapUnreadable') + return { 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, contract = FORGE.core): FakeKey { + return { + keyId, + wif, + purposeNumber: 0, + securityLevelNumber: 2, + keyTypeNumber: 2, + data: '', + contractBounds: { toJSON: () => ({ $type: 'singleContract', id: contract }) }, + 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[] + const sdk = { + identities: { + fetch: async () => ({ 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 + // 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 stores it again 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: kept, and the notice says where the newer one is", 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) + // Wraps made to key 6 still open here; new ones go to key 7. + expect(await storedEncryptionKeyIds(NET, ID)).toEqual([6]) + }, 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)] + 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 outcome = await adoptWalletEncryptionKey(lagging, NET, ID, FORGE.core, [mine], { attempts: 5, intervalMs: 5 }) + expect(outcome).toEqual({ stored: [6], missing: null }) + expect(reads).toBe(3) + expect(bytesToHex(mine)).toBe(bytesToHex(WALLET_ENC)) + // Without retries (a returning login), one read decides. + reads = 0 + const behindOnly = { ...lagging, identities: { ...(lagging as unknown as { identities: object }).identities, fetch: async () => ({ balance: 1n, publicKeys: (++reads, behind) }) } } as unknown as EvoSDK + expect(await adoptWalletEncryptionKey(behindOnly, NET, ID, FORGE.core, [mine])).toEqual({ stored: [], missing: null }) + 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) + + /** The wallet's first approval for forge-collab: another auth key (7), and another encryption key (8). */ + const COLLAB_WIF = encodeWif(new Uint8Array(32).fill(7), NET) + const COLLAB_ENC = encryptionKeyFromLogin(new Uint8Array(32).fill(0x22), ID) + const collabGrant: WalletKey = { keyId: 7, wif: COLLAB_WIF, scope: { core: false, collab: true, community: false, unbounded: false }, limits: null } + async function twoApprovals(): Promise { + const c = make() + await login(c, true) + keys = [...keys, authKey(7, COLLAB_WIF, FORGE.collab), encKey(8, COLLAB_ENC)] + await c.addWalletGrant(ID, collabGrant, FORGE.collab, { encryptionKeys: [new Uint8Array(COLLAB_ENC)], justRegistered: true }) + return c + } + /** A repo's wrap to key `keyId` of ours, which opens only with `secret`. */ + const wrapTo = (keyId: number | null, secret: Uint8Array): UnwrapInput => ({ + document: { ...(keyId === null ? {} : { recipientKeyId: keyId, senderKeyId: 4 }), opensWith: bytesToHex(secret) }, + counterpartyKey: {} as never, + repoId: new Uint8Array(32).fill(keyId ?? 0), + epoch: 0, + }) + const readerOf = async (ops: EncryptionOps, w: UnwrapInput): Promise => ((await ops.unwrap(w)) as unknown as { reader: string }).reader + + it('two approvals: the vault holds both keys, and a repo wrapped to either opens', async () => { + const c = await twoApprovals() + expect(c.getState().notice ?? null).toBeNull() + expect(await storedEncryptionKeyIds(NET, ID)).toEqual([8, 6]) + const ops = (await encryptionOps(sdk, NET, ID, FORGE.collab))! + // Writers send from the newest; readers pick the key the wrap names. + expect(ops.keyId).toBe(8) + expect(ops.keyIds).toEqual([8, 6]) + expect(await readerOf(ops, wrapTo(6, WALLET_ENC))).toBe(bytesToHex(WALLET_ENC)) + expect(await readerOf(ops, wrapTo(8, COLLAB_ENC))).toBe(bytesToHex(COLLAB_ENC)) + // A wrap naming no key id: each held key is tried in turn. + expect(await readerOf(ops, wrapTo(null, WALLET_ENC))).toBe(bytesToHex(WALLET_ENC)) + // A wrap to a key this browser does not hold does not open. + await expect(ops.unwrap(wrapTo(3, WALLET_ENC))).rejects.toBeInstanceOf(WrapError) + // Both stay held across a reload: one unlock opens the set. + releaseUnlocked() + gestures = 0 + const tab = make() + await tab.unlock(ID, 'passkey') + expect(gestures).toBe(1) + const again = (await encryptionOps(sdk, NET, ID, FORGE.collab))! + expect(await readerOf(again, wrapTo(6, WALLET_ENC))).toBe(bytesToHex(WALLET_ENC)) + expect(await readerOf(again, wrapTo(8, COLLAB_ENC))).toBe(bytesToHex(COLLAB_ENC)) + }, 30_000) + + it('an imported key is added too, never replacing one already held', async () => { + const c = await twoApprovals() + keys = [...keys, encKey(9, DG_ENC)] + await storeEncryptionKey(NET, ID, 9, new Uint8Array(DG_ENC)) + expect(await storedEncryptionKeyIds(NET, ID)).toEqual([9, 8, 6]) + // A returning login stores its key again: still one entry per key id. + await login(c) + expect(await storedEncryptionKeyIds(NET, ID)).toEqual([9, 8, 6]) + }, 30_000) + + it('a vault written with a single key entry reads as a set of one, and grows from it', async () => { + const c = make() + await login(c, true) + // What the vault held before key sets: the one sealed entry itself, not a list. + const at = (await idbEntries('vault')).map(([k]) => String(k)).find((k) => k.startsWith('vault-enc:'))! + const list = (await idbGet('vault', at))! + expect(list).toHaveLength(1) + await idbPut('vault', at, list[0]) + expect(await storedEncryptionKeyIds(NET, ID)).toEqual([6]) + expect(await withEncryptionKey(NET, ID, async (k, s) => [k, bytesToHex(s)])).toEqual([6, bytesToHex(WALLET_ENC)]) + keys = [...keys, authKey(7, COLLAB_WIF, FORGE.collab), encKey(8, COLLAB_ENC)] + await c.addWalletGrant(ID, collabGrant, FORGE.collab, { encryptionKeys: [new Uint8Array(COLLAB_ENC)] }) + expect(await storedEncryptionKeyIds(NET, ID)).toEqual([8, 6]) + const ops = (await encryptionOps(sdk, NET, ID, FORGE.collab))! + expect(await readerOf(ops, wrapTo(6, WALLET_ENC))).toBe(bytesToHex(WALLET_ENC)) + }, 30_000) + + it('a login whose key another approval superseded: no notice at sign-in (the repo that needs it says so)', async () => { + await twoApprovals() + resetMemoryStores() + lockVault() + const other = make() + await login(other) + expect(other.getState().notice ?? null).toBeNull() + expect(await storedEncryptionKeyIds(NET, ID)).toEqual([6]) + expect(ENCRYPTION_KEY_OTHER_APPROVAL).toMatch(/another approval in your wallet/) + }, 30_000) + + it('a tab holding a tab-only key cannot open the stored keys: their drop is reported, by their stored ids (L2)', async () => { + const OLD = new Uint8Array(32).fill(0x45) + keys = [encKey(3, 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, 3, new Uint8Array(OLD)) + // This tab now holds a pasted key for the identity: it sees no stored encryption key. + lockVault() + holdForSession(NET, { identityId: ID, keyId: 9, wif: encodeWif(new Uint8Array(32).fill(9), NET) }) + expect(await storedEncryptionKeyIds(NET, ID)).toEqual([]) + const c = make() + await login(c) + expect(c.getState().notice).toMatch(/not carried over/) + expect(await storedEncryptionKeyIds(NET, ID)).toEqual([6]) + }, 30_000) + + it('a different key the vault could not carry over is still reported as 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 storedEncryptionKeyIds(NET, ID)).toEqual([6]) + }, 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..0f4b40977 100644 --- a/forge-web/lib/auth/wallet-login.live.test.ts +++ b/forge-web/lib/auth/wallet-login.live.test.ts @@ -10,12 +10,17 @@ * * 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. * - * 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 +34,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, storedEncryptionKeyIds, 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') @@ -42,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 }) @@ -54,32 +64,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! @@ -88,24 +115,39 @@ 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, unbounded: false }) - const after = await controller.addWalletGrant(first.identityId, grant.key, forge.collab) - expect(after.grants).toEqual({ core: true, collab: true }) - 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) + lockVault() + resetMemoryStores() + const returning = new AuthController(async () => sdk, network) + 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 }) + const heldBefore = await storedEncryptionKeyIds(network, first.identityId) + const after = await returning.addWalletGrant(first.identityId, grant.key, forge.community, { encryptionKeys: grant.encryptionKeys, justRegistered: grant.registered }) + grant.wipe() + expect(after.grants).toEqual({ core: true, collab: false, community: true }) + // That first approval registered another encryption key: the vault keeps both (D27). + expect(await storedEncryptionKeyIds(network, first.identityId)).toHaveLength(heldBefore.length + 1) + await expectEncryptionKeyKept(first.identityId) + 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, @@ -132,14 +174,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 () => { diff --git a/forge-web/lib/repo/private-members.ts b/forge-web/lib/repo/private-members.ts index c5a373768..5e0490bf0 100644 --- a/forge-web/lib/repo/private-members.ts +++ b/forge-web/lib/repo/private-members.ts @@ -20,7 +20,7 @@ import type { EvoSDK, IdentityPublicKey } from '@dashevo/evo-sdk' import { base58Encode, decodeIdentifier } from '../auth/base58' import type { EncKeyLike, EncryptionOps } from '../auth/encryption-key' -import { fetchIdentityKeys, usableEncryptionKey } from '../auth/encryption-key' +import { fetchIdentityKeys, heldKeysText, usableEncryptionKey } from '../auth/encryption-key' import type { Network } from '../constants' import { EpochKeys, @@ -133,12 +133,16 @@ export function planRotation( self: string, exclude: readonly string[], coreId: string, - /** The id of the encryption key this browser holds: only a self-wrap to it can be resumed. */ - heldKeyId: number, + /** + * The ids of the encryption keys this browser holds (one id: that key alone): only a self-wrap + * to one of them can be resumed, and the rotator's newest usable key must be among them. + */ + held: number | readonly number[], /** The epoch the rotation chains from: the current one, or the one a maintainer's removal keeps. */ from: number | null = session.resolution.currentEpoch, ): RotationPlan { const r = session.resolution + const heldIds = typeof held === 'number' ? [held] : held const n = from if (n === null) throw new PrivateMembersError('this repo has no key epoch yet') // The current key must be readable to chain from (a burned current epoch still chains). @@ -159,7 +163,7 @@ export function planRotation( const epoch = n + 1 if (epoch > 0xffff_ffff) throw new PrivateMembersError('no key epoch number is left') const resume = pendingSelfWrap(session, self, epoch) - if (resume !== null && resume.row.recipientKeyId !== heldKeyId) { + if (resume !== null && !heldIds.includes(resume.row.recipientKeyId)) { throw notHeldKey(epoch, resume.row.recipientKeyId) } const mine = ownWraps(session, selfId, epoch) @@ -176,21 +180,22 @@ export function planRotation( } // §5.2: the new key goes to each member's newest usable key, the rotator's own included. If // this browser holds an older one, the rotator would lose the epoch it creates: refused. - if (id === self && key.keyId !== heldKeyId) throw staleHeldKey(heldKeyId, key.keyId) + if (id === self && !heldIds.includes(key.keyId)) throw staleHeldKey(heldIds, key.keyId) recipients.push({ identity: id, keyId: key.keyId, done: wrappedBySelf.has(id) }) } const burn = mustBurn(exclude.length > 0, resume !== null, mine, recipients, remaining) return { from: n, epoch, resume, burn, recipients, unreachable, excluded: [...excluded] } } -/** This browser holds encryption key `held`, but the identity's newest usable key is `current`. */ -function staleHeldKey(held: number, current: number): PrivateMembersError { +/** This browser holds encryption keys `held`, but not the identity's newest usable key `current`. */ +function staleHeldKey(held: readonly number[], current: number): PrivateMembersError { return new PrivateMembersError( - `this browser holds encryption key ${held}, but your identity's current key is ${current}: the new repo key would go to key ${current}, which you couldn't read here. Import key ${current} (Settings → Private repos), or rotate from the CLI with it.`, + `this browser holds ${heldKeysText(held)}, but your identity's current key is ${current}: the new repo key would go to key ${current}, which you couldn't read here. Import key ${current} (Settings → Private repos), or rotate from the CLI with it.`, 'E306', ) } + /** A pending self-wrap of `epoch` to a key of ours this browser does not hold: it cannot be resumed here. */ function notHeldKey(epoch: number, keyId: number): PrivateMembersError { return new PrivateMembersError( @@ -329,12 +334,15 @@ function keyOf(session: PrivateSession, identity: string, keyId: number): Identi return k as unknown as IdentityPublicKey } -/** This identity's stored encryption key, as the sender of a wrap: it must still be usable. */ +/** + * This identity's writer key: the newest usable ENCRYPTION key on chain among those this browser + * holds (a held key disabled since is never it). It sends every wrap, and gets the self-wraps. + */ function senderKey(session: PrivateSession, c: PrivateWriteContext): IdentityPublicKey { const mine = session.memberKeys.get(c.auth.identityId) ?? [] - const k = mine.find((x) => x.keyId === c.ops.keyId) as (EncKeyLike & IdentityPublicKey) | undefined - if (k === undefined || usableEncryptionKey([k], c.repo.forge.core) === null) { - throw new PrivateMembersError('the encryption key in this browser is no longer enabled on your identity; import your current one', 'E306') + const k = usableEncryptionKey(mine.filter((x) => c.ops.keyIds.includes(x.keyId)), c.repo.forge.core) as (EncKeyLike & IdentityPublicKey) | null + if (k === null) { + throw new PrivateMembersError('no encryption key in this browser is still enabled on your identity; import your current one', 'E306') } return k } @@ -518,7 +526,7 @@ async function readOwnWrap( ) const doc = documents[0] const w = doc === undefined ? null : parseWrapDoc(doc) - if (w === null || w.senderKeyId !== c.ops.keyId) return null + if (w === null || !c.ops.keyIds.includes(w.senderKeyId)) return null const recipient = (session.memberKeys.get(identity) ?? (await fetchIdentityKeys(c.sdk, identity)) ?? []).find((k) => k.keyId === w.row.recipientKeyId) if (recipient === undefined) return null try { @@ -669,7 +677,7 @@ async function rotateWith( minFrom?: number, drop: readonly { readonly identity: string; readonly role?: Role }[] = [], ): Promise<{ epoch: number; commit: Uint8Array } | { lost: number }> { - const plan = planRotation(session, c.auth.identityId, exclude, c.repo.forge.core, c.ops.keyId) + const plan = planRotation(session, c.auth.identityId, exclude, c.repo.forge.core, c.ops.keyIds) // The read must be at least as new as the removal it follows: a current epoch below the one // before the removal means its re-anchor is not visible here yet, and chaining from it would // skip that epoch. @@ -805,9 +813,9 @@ export async function createEpochZero(c: PrivateWriteContext, defaultBranch: str // encryption key (§5.2), which must be the one this browser holds, or the repo would be // created unreadable to its own owner. const pending = pendingSelfWrap(session, c.auth.identityId, 0) - if (pending !== null && pending.row.recipientKeyId !== c.ops.keyId) throw notHeldKey(0, pending.row.recipientKeyId) - if (pending === null && selfKey.keyId !== c.ops.keyId) { - throw new PrivateMembersError(`your identity's current encryption key is key ${selfKey.keyId}, but this browser holds key ${c.ops.keyId}; add key ${selfKey.keyId} here (Settings → Private repos)`, 'E306') + if (pending !== null && !c.ops.keyIds.includes(pending.row.recipientKeyId)) throw notHeldKey(0, pending.row.recipientKeyId) + if (pending === null && !c.ops.keyIds.includes(selfKey.keyId)) { + throw new PrivateMembersError(`your identity's current encryption key is key ${selfKey.keyId}, but this browser holds ${heldKeysText(c.ops.keyIds)}; add key ${selfKey.keyId} here (Settings → Private repos)`, 'E306') } const k0 = await ownEpochKey(c, session, { identity: c.auth.identityId, keyId: pending?.row.recipientKeyId ?? selfKey.keyId }, 0, intent) try { @@ -848,7 +856,7 @@ async function ownEpochKey( if (outcome.kind === 'not-a-member') throw new PrivateMembersError('you are not a maintainer of this repo any more; ask the owner to add you again, or rotate from another maintainer', 'E310') const standing = await readOwnWrap(c, session, epoch, self.identity) if (standing === null) throw unusableWrap({ kind: 'unreadable' }, self.identity, epoch) - if (standing.recipientKeyId !== c.ops.keyId) { + if (!c.ops.keyIds.includes(standing.recipientKeyId)) { standing.raw.fill(0) throw notHeldKey(epoch, standing.recipientKeyId) } @@ -1051,7 +1059,7 @@ export async function removePrivateMember( // The rotation after the delete is planned now (its own checks: the rotator's key among them), // so a removal it would refuse is refused before the membership goes. if (kept !== null && s.resolution.keys.has(kept)) { - planRotation(s, c.auth.identityId, effect === 'rotate-exclude' ? [memberId] : [], c.repo.forge.core, c.ops.keyId, kept) + planRotation(s, c.auth.identityId, effect === 'rotate-exclude' ? [memberId] : [], c.repo.forge.core, c.ops.keyIds, kept) } // Another staying maintainer's config that would come before this browser's re-anchor, and // is not the same anchor, is known now: refuse before paying for anything. @@ -1336,7 +1344,7 @@ async function keepCurrentKey(c: PrivateWriteContext, session: PrivateSession, l } const kn = await rawEpochKey(session, c, n) try { - requireSame(await postWrap(c, session, kn.keys, kn.raw, c.auth.identityId, c.ops.keyId, `${intent}:keep`), c.auth.identityId, n) + requireSame(await postWrap(c, session, kn.keys, kn.raw, c.auth.identityId, senderKey(session, c).keyId, `${intent}:keep`), c.auth.identityId, n) } finally { kn.raw.fill(0) } @@ -1469,8 +1477,8 @@ async function wrapMissing( } /** The cost of a repair: a rotation (members + 1) when needed, plus one wrap per unwrapped member. */ -export function repairCost(session: PrivateSession, plan: RepairPlan, self: string, coreId: string, heldKeyId: number): CostPreview { +export function repairCost(session: PrivateSession, plan: RepairPlan, self: string, coreId: string, held: number | readonly number[]): CostPreview { const wraps = plan.wrap.map(() => previewCreate('repoKey')) if (plan.rotate.length === 0 && !plan.burned) return sumPreviews(wraps) - return rotationCost(planRotation(session, self, plan.rotate, coreId, heldKeyId)) + return rotationCost(planRotation(session, self, plan.rotate, coreId, held)) } diff --git a/forge-web/lib/repo/private-rotation.test.ts b/forge-web/lib/repo/private-rotation.test.ts index 764d3f12e..71286a14b 100644 --- a/forge-web/lib/repo/private-rotation.test.ts +++ b/forge-web/lib/repo/private-rotation.test.ts @@ -190,6 +190,7 @@ const sdk = { /** Fake wrap ops: a wrap "encrypts" the raw key as itself; anyone in the test can open it. */ const ops: EncryptionOps = { keyId: 4, + keyIds: [4], unwrap: async (p) => (await ops.unwrapRaw(p)).keys, unwrapRaw: async (p) => { const bytes = p.document['wrapped'] diff --git a/forge-web/lib/repo/private-session.test.ts b/forge-web/lib/repo/private-session.test.ts index 2d7f54ed2..f23e101c3 100644 --- a/forge-web/lib/repo/private-session.test.ts +++ b/forge-web/lib/repo/private-session.test.ts @@ -275,6 +275,45 @@ describe('the private session', () => { }) }) +describe('a reader holding several encryption keys (DESIGN D27)', () => { + /** BOB's wraps: epoch 0 to his older key 4, epoch 1 (after a rotation) to his newer key 9. */ + async function twoKeyWorld(): Promise { + const w = await world() + await rotate(w) + w.wraps = w.wraps.filter((d) => !(d['memberId'] === b58(BOB) && d['epoch'] === 1)) + w.wraps.push(wrapDoc(ALICE, BOB, 1, 99, 9)) + return w + } + /** BOB's keys: the wallet's auth key 8 (HASH160) and its encryption key 9, beside key 4. */ + const bobKeys: EncKeyLike[] = [...encKeys(4), { keyId: 8, purposeNumber: 0, keyTypeNumber: 2, data: '' }, ...encKeys(9)] + const load = (w: World, held: number[]) => + loadPrivateSession({ + repo: REPO_REF, + network: 'devnet', + reader: b58(BOB), + source: { ...source(w), identityKeys: async (id) => (id === b58(BOB) ? bobKeys : encKeys()) }, + unwrapper: { ...unwrapper(w), keyId: Math.max(...held), keyIds: held }, + }) + + it('opens the wraps to the older key and to the newer one', async () => { + const w = await twoKeyWorld() + const both = await load(w, [9, 4]) + expect([...both.resolution.keys.keys()].sort()).toEqual([0, 1]) + expect(both.missingKey ?? null).toBeNull() + // Holding only the older key: epoch 0 opens, epoch 1 (wrapped to key 9) does not. (Only the + // newer key would open both: epoch 1's anchor carries epoch 0's key.) + const older = await load(w, [4]) + expect([...older.resolution.keys.keys()]).toEqual([0]) + }) + + it('holding none of the keys its wraps went to: names the newest, and whether a wallet approval registered it', async () => { + const w = await twoKeyWorld() + const none = await load(w, [7]) + expect(none.resolution.keys.size).toBe(0) + expect(none.missingKey).toEqual({ keyId: 9, otherApproval: true }) + }) +}) + describe('config rows', () => { it('a config without enc states no key and is no row, as in forge-core (§5.3)', () => { const doc = { @@ -471,6 +510,20 @@ describe('rotation and repair planning', () => { expect(planRotation(s, b58(ALICE), [b58(CAROL)], FORGE.core, 4).burn).toBe(true) }) + it('holding several keys: the rotator plans with its newest usable one among them; a held key since disabled is never it', async () => { + const w = await world() + const s = await sessionFor(w, ALICE) + // ALICE's usable key on chain is 4; this browser also holds 9 (a key disabled since, say). + const plan = planRotation(s, b58(ALICE), [b58(CAROL)], FORGE.core, [9, 4]) + expect(plan.recipients.find((r) => r.identity === b58(ALICE))?.keyId).toBe(4) + expect(() => planRotation(s, b58(ALICE), [b58(CAROL)], FORGE.core, [9])).toThrow(/holds encryption key 9, but your identity's current key is 4/) + expect(() => planRotation(s, b58(ALICE), [b58(CAROL)], FORGE.core, [7, 9])).toThrow(/holds encryption keys 7 and 9/) + // A pending self-wrap to any held key resumes. + w.wraps.push(wrapDoc(ALICE, ALICE, 1, 50, 3)) + const s2 = await sessionFor(w, ALICE) + expect(planRotation(s2, b58(ALICE), [], FORGE.core, [4, 3]).resume?.row.recipientKeyId).toBe(3) + }) + it('a pending n + 1 to a key this browser does not hold is refused, not skipped', async () => { const w = await world() w.members = w.members.filter((m) => m.identity !== b58(CAROL)) diff --git a/forge-web/lib/repo/private-session.ts b/forge-web/lib/repo/private-session.ts index 756745de7..ab7636811 100644 --- a/forge-web/lib/repo/private-session.ts +++ b/forge-web/lib/repo/private-session.ts @@ -15,7 +15,7 @@ import type { EvoSDK, IdentityPublicKey } from '@dashevo/evo-sdk' import { base58Encode, decodeIdentifier } from '../auth/base58' import type { EncKeyLike, EncryptionOps } from '../auth/encryption-key' -import { fetchIdentityKeys, isUsableEncryptionKey } from '../auth/encryption-key' +import { fetchIdentityKeys, isUsableEncryptionKey, walletRegistered } from '../auth/encryption-key' import { onEncryptionKeyChange } from '../auth/vault' import type { Network } from '../constants' import { @@ -102,6 +102,12 @@ export interface PrivateSession { readonly memberKeys: ReadonlyMap /** Pack manifests (`$id`) found uploaded under an old key (§8.2), shown to maintainers. */ readonly suspectManifests: Set + /** + * The reader holds encryption keys, but none of the keys its wraps here went to: the newest + * wrap's key id, and whether a wallet approval registered that key (DESIGN D27: each first + * approval for another contract registers one). Absent when a held key opens a wrap here. + */ + readonly missingKey?: { readonly keyId: number; readonly otherApproval: boolean } | null /** Whether the session is closed (vault locked, key changed). */ readonly closed: boolean /** End this session now (its keys and caches are dropped; its gate admits nothing). */ @@ -123,8 +129,10 @@ export interface SessionSource { /** The reader's side: decrypt one of its wraps (the vault's {@link EncryptionOps} in production). */ export interface SessionUnwrapper { - /** The id of the encryption key the reader holds. */ + /** The id of the encryption key the reader holds (its newest, when it holds several). */ readonly keyId: number + /** Every key id the reader holds (default: {@link keyId} alone); a wrap to any of them is opened. */ + readonly keyIds?: readonly number[] unwrap(p: { document: PlainDocument; counterpartyKey: EncKeyLike; repoId: Uint8Array; epoch: number }): Promise } @@ -137,6 +145,7 @@ export function isMaintainer(session: PrivateSession, identity: string | null): export function sessionUnwrapper(ops: EncryptionOps): SessionUnwrapper { return { keyId: ops.keyId, + keyIds: ops.keyIds, unwrap: (p) => ops.unwrap({ document: p.document, counterpartyKey: p.counterpartyKey as unknown as IdentityPublicKey, repoId: p.repoId, epoch: p.epoch }), } @@ -293,6 +302,9 @@ export async function loadPrivateSession(input: { const keyOf = (identity: string, keyId: number): EncKeyLike | undefined => memberKeys.get(identity)?.find((k) => k.keyId === keyId) const parsed = wrapDocs.map(parseWrapDoc).filter((w): w is NonNullable => w !== null) + const held = unwrapper === null ? [] : (unwrapper.keyIds ?? [unwrapper.keyId]) + /** The reader's own wraps from current maintainers (§5.4 checks 1–2). */ + const ownWrap = (w: (typeof parsed)[number]): boolean => bytesEqual(w.row.memberId, readerId) && maintainers.has(w.row.owner) const wraps: WrapDoc[] = await Promise.all( parsed.map(async (w) => { const memberB58 = base58Encode(w.row.memberId) @@ -301,7 +313,7 @@ export async function loadPrivateSession(input: { let keys: EpochKeys | undefined // Only the reader's own wraps from current maintainers are opened (§5.4 checks 1–2); the // anchor check (5) is resolveEpochs'. - if (unwrapper !== null && bytesEqual(w.row.memberId, readerId) && maintainers.has(w.row.owner) && w.row.recipientKeyId === unwrapper.keyId) { + if (unwrapper !== null && ownWrap(w) && held.includes(w.row.recipientKeyId)) { const sender = keyOf(base58Encode(w.row.owner), w.senderKeyId) if (sender !== undefined) { // Only a wrap that does not open is skipped (§5.4 check 4); a locked vault or an SDK @@ -316,6 +328,14 @@ export async function loadPrivateSession(input: { }), ) + // Wraps to this reader, none to a key its browser holds: say which key they need. + const own = parsed.filter(ownWrap) + let missingKey: PrivateSession['missingKey'] = null + if (unwrapper !== null && own.length > 0 && !own.some((w) => held.includes(w.row.recipientKeyId))) { + const newest = own.reduce((a, b) => (b.row.epoch > a.row.epoch ? b : a)).row.recipientKeyId + missingKey = { keyId: newest, otherApproval: walletRegistered(memberKeys.get(reader) ?? [], newest) } + } + const configRows = configDocs.map(parseConfigRow).filter((c): c is ConfigRow => c !== null) const resolution = await resolveEpochs({ repoId, @@ -372,6 +392,7 @@ export async function loadPrivateSession(input: { configHistory, anchors, unanchoredDocs, + missingKey, memberKeys, suspectManifests: new Set(), configRows, diff --git a/forge-web/lib/repo/private-writes.test.ts b/forge-web/lib/repo/private-writes.test.ts index 607e46e57..93288e7e8 100644 --- a/forge-web/lib/repo/private-writes.test.ts +++ b/forge-web/lib/repo/private-writes.test.ts @@ -75,6 +75,7 @@ const encKey = (keyId = 4): EncKeyLike => ({ keyId, purposeNumber: 1, keyTypeNum let identityKeys: EncKeyLike[] = [encKey()] const ops: EncryptionOps = { keyId: 4, + keyIds: [4], unwrap: async (p) => (await ops.unwrapRaw(p)).keys, unwrapRaw: async (p) => { const bytes = p.document['wrapped'] @@ -430,6 +431,31 @@ describe('private create, correctness review', () => { expect(chain['repo']).toBeUndefined() }) + it('holding a newer key since disabled on chain: creates with the newest usable held key, sending and self-wrapping from it (L1)', async () => { + identityKeys = [encKey(4), { ...encKey(6), disabledAt: 1n }] + const sent: { sender: number; recipient: number }[] = [] + const both: EncryptionOps = { + ...ops, + keyId: 6, + keyIds: [6, 4], + wrap: async (p) => { + sent.push({ sender: p.senderKey.keyId, recipient: p.recipientKey.keyId }) + return { wrapped: new Uint8Array(p.raw), recipientKeyId: p.recipientKey.keyId, senderKeyId: p.senderKey.keyId } + }, + } + await createRepo(sdk, auth, FORGE, { name: 'two-keys', visibility: 'private' }, undefined, { ops: both, epochZero: createEpochZero }) + expect(sent).toEqual([{ sender: 4, recipient: 4 }]) + expect(chain['repoKey']?.[0]?.['recipientKeyId']).toBe(4) + }) + + it('refuses when the identity’s usable key is none of the held ones, naming them all', async () => { + identityKeys = [encKey(4), encKey(8)] + const both: EncryptionOps = { ...ops, keyId: 6, keyIds: [6, 4] } + await expect(createRepo(sdk, auth, FORGE, { name: 'stale2', visibility: 'private' }, undefined, { ops: both, epochZero: createEpochZero })).rejects.toThrow( + /key 8, but this browser holds encryption keys 4 and 6/, + ) + }) + it('refuses a private fork', () => { return expect(createRepo(sdk, auth, FORGE, { name: 'pf', visibility: 'private', forkOf: b58(REPO) }, undefined, { ops, epochZero: createEpochZero })).rejects.toThrow(/fork/) }) diff --git a/forge-web/lib/repo/writes.ts b/forge-web/lib/repo/writes.ts index bbbafd29d..4bfe33fdf 100644 --- a/forge-web/lib/repo/writes.ts +++ b/forge-web/lib/repo/writes.ts @@ -29,7 +29,7 @@ import { base58Encode, decodeIdentifier } from '../auth/base58' import { idbDelete, idbEntries, idbGet, idbPut } from '../idb' import { isGitRefName, type EventKind } from '../rules' import { denseNumber, isAuthorKind, namesDenseRule, normalizeRepoName as normalizeV2RepoName, type ClosedAs, type Role, type StateAction, type Visibility } from '../rules/v2' -import { fetchIdentityKeys, usableEncryptionKey, type EncryptionOps } from '../auth/encryption-key' +import { fetchIdentityKeys, heldKeysText, usableEncryptionKey, type EncryptionOps } from '../auth/encryption-key' import { ConsensusRefusal, DUPLICATE_UNIQUE_CODE, @@ -1420,9 +1420,9 @@ export async function createRepo( if (visibility === 'private' && !resumed && privateCreate !== undefined) { const current = usableEncryptionKey((await fetchIdentityKeys(sdk, ownerId)) ?? [], forge.core) if (current === null) throw new Error('cannot create a private repository: your identity has no encryption key') - if (current.keyId !== privateCreate.ops.keyId) { + if (!privateCreate.ops.keyIds.includes(current.keyId)) { throw new Error( - `cannot create a private repository: your identity's current encryption key is key ${current.keyId}, but this browser holds key ${privateCreate.ops.keyId}; add key ${current.keyId} here (Settings → Private repos)`, + `cannot create a private repository: your identity's current encryption key is key ${current.keyId}, but this browser holds ${heldKeysText(privateCreate.ops.keyIds)}; add key ${current.keyId} here (Settings → Private repos)`, ) } }