diff --git a/browser/CHANGELOG.md b/browser/CHANGELOG.md index 7325938fd2..5d961f8b52 100644 --- a/browser/CHANGELOG.md +++ b/browser/CHANGELOG.md @@ -4,6 +4,24 @@ This changelog covers all five packages, as they are (for now) updated as a whol ## UNRELEASED +- Signing in to a hosted account can now be enough to open your identity on a + new device (#277). When the account service offers assisted recovery + (`assisted_recovery` in `GET /api/auth/providers`), a new account's backup is + wrapped by the account alone, so onboarding asks for no passkey and shows no + recovery code, and the sign-in and restore steps unlock it by themselves + after a recent sign-in. Existing backups get the extra wrapper the next time + a passkey or recovery code opens them. The sign-in and restore steps now + offer the same account options as the portal's sign-in page (Google when + configured, passkey, email link), from one shared `AccountSignIn` component + in `@tomic/service-ui`. Builds that know no account service (the FOSS + release, self-hosted nodes) show none of it and make no requests for it. + Account recovery has a "Let Atomic help me recover" switch: off removes the + assisted wrapper, so only a passkey or recovery code opens the identity. A + wrapper records which service key made it (`kdf_params.key_id`); after the + service rotates its key, the next unlock re-wraps with the new one. Accounts + may now have an `acct_` id apart from their address: backups and bindings + keep using the id, and the app shows `address` from `GET /api/me`. + - Pasting an agent secret that opens a different agent than the signed-in account no longer signs that account out on its own. The app now says which account is signed in, shows both agents, and lets the user stay signed in or diff --git a/browser/data-browser/src/components/AccountRecoveryCard.tsx b/browser/data-browser/src/components/AccountRecoveryCard.tsx index ce9d606780..fd659b7a29 100644 --- a/browser/data-browser/src/components/AccountRecoveryCard.tsx +++ b/browser/data-browser/src/components/AccountRecoveryCard.tsx @@ -3,13 +3,20 @@ import { styled } from 'styled-components'; import { FaKey } from 'react-icons/fa6'; import { Agent, useStore, isAtomicIdentifier } from '@tomic/react'; import { Button } from './Button'; +import { Checkbox, CheckboxLabel } from './forms/Checkbox'; import { hasPasskeyApi } from '../helpers/passkeySupport'; import { Column, Row } from './Row'; import { CodeBlock } from './CodeBlock'; import { SecretCodeBlock } from './SecretCodeBlock'; import { ErrorLook } from './ErrorLook'; import { InputStyled, InputWrapper } from './forms/InputStyles'; -import { getManagedAccount, PRODUCT_NAME } from '../helpers/managed'; +import { + accountAddress, + getManagedAccount, + isAssistedRecoveryAvailable, + PRODUCT_NAME, + setAssistedRecovery, +} from '../helpers/managed'; import { useSettings } from '../helpers/AppSettings'; import { fetchManagedInfo } from '../helpers/managedServer'; import { getManagedPortalUrl } from '../helpers/managed/cloudSync'; @@ -100,23 +107,29 @@ export function AccountRecoveryCard({ const [hasSession, setHasSession] = useState(null); const [accountEmail, setAccountEmail] = useState(null); const [portalUrl, setPortalUrl] = useState(null); + /** Assisted recovery: offered here at all, and whether it is on. */ + const [assistedOffered, setAssistedOffered] = useState(false); + const [assistedOn, setAssistedOn] = useState(true); useEffect(() => { let cancelled = false; void (async () => { - const [session, info] = await Promise.all([ + const [session, info, assisted] = await Promise.all([ getManagedAccount().catch(() => null), fetchManagedInfo(baseURL).catch(() => null), + isAssistedRecoveryAvailable().catch(() => false), ]); if (cancelled) return; setHasSession(!!session); + setAssistedOffered(!!session && assisted); + setAssistedOn(!session?.assisted_recovery_off); // Kept for the passkey's label, which is what the user will see in their // password manager a year from now when they have forgotten what this // credential was for. - setAccountEmail(session?.email ?? null); + setAccountEmail(session ? accountAddress(session) : null); // Resolve the portal the same way every other surface does, rather than // reading `info.portalUrl` straight off the connected node. // @@ -411,7 +424,9 @@ export function AccountRecoveryCard({ if (!agentSubject || backup.phase !== 'ready') return; - if (!envelopeWrapperKinds(backup.secret).hasPasskey && !codeInput.trim()) { + const kinds = envelopeWrapperKinds(backup.secret); + + if (!kinds.hasPasskey && !kinds.hasAccount && !codeInput.trim()) { setAddingAccountPasskey(true); setNeedsCode(true); setError(undefined); @@ -544,9 +559,46 @@ export function AccountRecoveryCard({ ); } - const { hasPasskey, hasCode } = envelopeWrapperKinds(backup.secret); + const { hasPasskey, hasCode, hasAccount } = envelopeWrapperKinds( + backup.secret, + ); const deviceOnly = backup.onServer === false; + async function handleAssistedChange(enabled: boolean) { + if (backup.phase !== 'ready') return; + + const current = backup; + setLoading(true); + setError(undefined); + + const failed = await setAssistedRecovery(enabled).then( + () => null, + (err: unknown) => (err instanceof Error ? err.message : String(err)), + ); + setLoading(false); + + if (failed) { + setError(failed); + + return; + } + + setAssistedOn(enabled); + + // Off removes the wrapper on the server; show the backup without it. + if (!enabled) { + setBackup({ + ...current, + secret: { + ...current.secret, + wrappers: current.secret.wrappers.filter( + w => w.wrapper_type !== 'atomic-assisted', + ), + }, + }); + } + } + return ( {error && {error}} @@ -555,12 +607,40 @@ export function AccountRecoveryCard({ into a space and the sentence read "your passkey ." */} You can get back in with:{' '} {`${ - [hasPasskey && 'your passkey', hasCode && 'your recovery code'] + [ + hasAccount && `signing in to your ${PRODUCT_NAME} account`, + hasPasskey && 'your passkey', + hasCode && 'your recovery code', + ] .filter(Boolean) .join(' or ') || 'your recovery password' }${deviceOnly ? ', on this device' : ''}.`} + {assistedOffered && + !deviceOnly && + (hasPasskey || hasCode || hasAccount) ? ( + + + void handleAssistedChange(enabled)} + disabled={loading || (assistedOn && !hasPasskey && !hasCode)} + data-test='assisted-recovery-switch' + /> + Let {PRODUCT_NAME} help me recover + + + {assistedOn + ? `Signing in to your ${PRODUCT_NAME} account is enough to open your identity on a new device. ${PRODUCT_NAME} holds a key for that. Turn it off to rely only on your passkey or recovery code.` + : `Only your passkey or recovery code opens your identity. ${PRODUCT_NAME} cannot.`} + {assistedOn && !hasPasskey && !hasCode + ? ' Add a passkey or recovery code first.' + : null} + + + ) : null} + {/* The gap worth naming: everything above still works here, and none of it survives this browser. Said plainly because the Sync page reads the server copy, so a card that stayed quiet about which copy it diff --git a/browser/data-browser/src/components/AgentProfileHeader.tsx b/browser/data-browser/src/components/AgentProfileHeader.tsx index a1b493cfa6..309027cade 100644 --- a/browser/data-browser/src/components/AgentProfileHeader.tsx +++ b/browser/data-browser/src/components/AgentProfileHeader.tsx @@ -14,6 +14,7 @@ import { useUpload } from '../hooks/useUpload'; import { useSettings } from '../helpers/AppSettings'; import { fetchManagedInfo } from '../helpers/managedServer'; import { + accountAddress, getManagedAccount, PRODUCT_NAME, safePortalUrl, @@ -165,10 +166,10 @@ export function AgentProfileHeader({ subject }: { subject: string }) { href={portalUrl ? `${portalUrl}/dashboard` : undefined} target='_blank' rel='noopener noreferrer' - title={`Manage ${account.email} on ${PRODUCT_NAME}`} + title={`Manage ${accountAddress(account)} on ${PRODUCT_NAME}`} data-test='account-email' > - {account.email} + {accountAddress(account)} ) : null} diff --git a/browser/data-browser/src/components/NewIdentitySection.tsx b/browser/data-browser/src/components/NewIdentitySection.tsx index 8c9798de03..96c16b5d8f 100644 --- a/browser/data-browser/src/components/NewIdentitySection.tsx +++ b/browser/data-browser/src/components/NewIdentitySection.tsx @@ -76,6 +76,11 @@ interface NewIdentitySectionProps { * Resolves with the plaintext code to show the user once. The fallback for * devices without passkey support, or when the user asks for it. */ onBackupWithCode?: (secret: string) => Promise; + /** Back the secret up under the signed-in account alone (assisted + * recovery). Resolves true when that worked, which ends onboarding with + * nothing to register or save; false moves on to the passkey and code + * step. */ + onBackupWithAccount?: (secret: string) => Promise; } interface IdentityData { @@ -105,6 +110,7 @@ export function NewIdentitySection({ offerRecoveryBackup = false, onBackupWithPasskey, onBackupWithCode, + onBackupWithAccount, }: NewIdentitySectionProps) { const store = useStore(); const { setAgent, setDrive } = useSettings(); @@ -255,6 +261,19 @@ export function NewIdentitySection({ await onAfterCreate(resource.subject); } + // Signing in is enough to get back in: nothing for the person to + // register or write down, and the secret is still revealable from + // Settings, so skip straight to the workspace. + if ( + offerRecoveryBackup && + onBackupWithAccount && + (await onBackupWithAccount(finalSecret)) + ) { + await finishWithoutSecretStep(resource.subject); + + return; + } + setStep( offerRecoveryBackup && (onBackupWithPasskey || onBackupWithCode) ? 'recovery-backup' @@ -298,13 +317,15 @@ export function NewIdentitySection({ * be a second thing to store. With no backup, the reveal + verify steps * stay — it really is the only copy. */ - async function finishWithoutSecretStep() { - if (identity?.driveSubject) { - setDrive(identity.driveSubject); + async function finishWithoutSecretStep( + driveSubject = identity?.driveSubject, + ) { + if (driveSubject) { + setDrive(driveSubject); // An earlier lookup can have cached "not found" before creation. // Read the now-persisted drive and profile before opening the workspace. - await reopenRestoredDrive(store, identity.driveSubject); - if (navigateToDrive) navigate(constructOpenURL(identity.driveSubject)); + await reopenRestoredDrive(store, driveSubject); + if (navigateToDrive) navigate(constructOpenURL(driveSubject)); } onDone(); @@ -474,7 +495,7 @@ export function NewIdentitySection({ setUseCodeFallback(true); }} onGenerate={handleGenerateRecoveryCode} - onContinue={finishWithoutSecretStep} + onContinue={() => finishWithoutSecretStep()} onSkip={() => { setError(undefined); setStep('secret'); diff --git a/browser/data-browser/src/components/Share/ShareDialog.tsx b/browser/data-browser/src/components/Share/ShareDialog.tsx index 423c265758..ed974478ee 100644 --- a/browser/data-browser/src/components/Share/ShareDialog.tsx +++ b/browser/data-browser/src/components/Share/ShareDialog.tsx @@ -31,7 +31,10 @@ import { profileReviewedBefore, rememberProfileReviewed } from '../InviteForm'; import { useIsPrivateDrive } from '@hooks/useIsPrivateDrive'; import { useInheritedRights } from '../../routes/Share/useInheritedRights'; import { getManagedPortalUrl } from '../../helpers/managed/cloudSync'; -import { getManagedAccount } from '../../helpers/managed/session'; +import { + accountAddress, + getManagedAccount, +} from '../../helpers/managed/session'; import { sendShareInvites } from '../../helpers/managed/shareInvites'; import { EmailInviteInput, isEmailAddress } from './EmailInviteInput'; import { PeopleWithAccess, effectiveRole } from './PeopleWithAccess'; @@ -459,7 +462,10 @@ function useCurrentAgentDetail( if (!isSaas) return; let cancelled = false; getManagedAccount() - .then(account => !cancelled && setEmail(account?.email)) + .then( + account => + !cancelled && setEmail(account ? accountAddress(account) : undefined), + ) .catch(() => { /* The name alone is fine. */ }); diff --git a/browser/data-browser/src/helpers/managed/accountPasskey.ts b/browser/data-browser/src/helpers/managed/accountPasskey.ts index 2ea010cbbc..cede8b07ad 100644 --- a/browser/data-browser/src/helpers/managed/accountPasskey.ts +++ b/browser/data-browser/src/helpers/managed/accountPasskey.ts @@ -124,3 +124,54 @@ export async function accountPasskey( existing, }; } + +/** + * Sign in to the account with a passkey, from the app: the same ceremony as + * the portal's "Sign in with passkey", which the account service accepts + * from the app's origin too. Ends with the shared session cookie set. + * Resolves false when the person dismissed the prompt. + */ +export async function signInWithAccountPasskey(email = ''): Promise { + const start = await managedFetch('/passkeys/login/start', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ email: email.trim() }), + }); + if (!start.ok) throw new Error('Could not start passkey sign-in.'); + const { publicKey } = await start.json(); + + let credential: PublicKeyCredential | null; + + try { + credential = (await navigator.credentials.get({ + publicKey: { + ...publicKey, + challenge: decode(publicKey.challenge), + allowCredentials: (publicKey.allowCredentials ?? []).map( + (c: { id: string; type: string }) => ({ ...c, id: decode(c.id) }), + ), + }, + } as CredentialRequestOptions)) as PublicKeyCredential | null; + } catch (error) { + if (error instanceof DOMException && error.name === 'NotAllowedError') { + return false; + } + + throw error; + } + + if (!credential) return false; + const finish = await managedFetch('/passkeys/login/finish', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(authenticationResponse(credential)), + }); + + if (!finish.ok) { + throw new Error( + 'That passkey is not linked to an account. Use Google or an email link instead.', + ); + } + + return true; +} diff --git a/browser/data-browser/src/helpers/managed/accountProviders.ts b/browser/data-browser/src/helpers/managed/accountProviders.ts new file mode 100644 index 0000000000..0c980b5b4a --- /dev/null +++ b/browser/data-browser/src/helpers/managed/accountProviders.ts @@ -0,0 +1,72 @@ +import { hasManagedApi, managedFetch } from './api'; + +export type AccountProviders = { + /** "Continue with Google" is configured on the account service. */ + google: boolean; + /** Signing in to the account is enough to unlock the identity. */ + assisted_recovery: boolean; +}; + +const NONE: AccountProviders = { google: false, assisted_recovery: false }; +let pending: Promise | null = null; + +/** + * What the account service offers, read once per page. A build that knows no + * account service (the FOSS release, a self-hosted node) asks nobody and gets + * nothing, so it never depends on atomic.place. + */ +export function getAccountProviders(): Promise { + if (!hasManagedApi()) return Promise.resolve(NONE); + pending ??= managedFetch('/auth/providers') + .then(res => (res.ok ? res.json() : NONE)) + .then((body: Partial) => ({ + google: body?.google === true, + assisted_recovery: body?.assisted_recovery === true, + })) + .catch(() => { + // Not cached: a network blip must not switch these off for the rest of + // the page's life. + pending = null; + + return NONE; + }); + + return pending; +} + +/** + * Where "Continue with Google" starts, on the account service, returning to + * `returnTo` (this page) once signed in. + */ +export function googleSignInUrl(portalUrl: string, returnTo: string): string { + const start = new URL('/api/auth/google/start', portalUrl); + start.searchParams.set('next', returnTo); + + return start.toString(); +} + +/** + * Email a sign-in link, the same one the portal sends. The link opens on the + * portal; this page notices the session through the shared cookie. Returns + * the link itself where the service hands it out (local development). + */ +export async function sendAccountEmailLink( + email: string, +): Promise { + const res = await managedFetch('/signup', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ email: email.trim() }), + }); + const body = await res.json().catch(() => null); + + if (!res.ok) { + throw new Error( + typeof body?.error === 'string' + ? body.error + : 'Could not send the sign-in link. Try again.', + ); + } + + return typeof body?.magic_link === 'string' ? body.magic_link : null; +} diff --git a/browser/data-browser/src/helpers/managed/recovery-assisted.test.ts b/browser/data-browser/src/helpers/managed/recovery-assisted.test.ts new file mode 100644 index 0000000000..31f03ab80d --- /dev/null +++ b/browser/data-browser/src/helpers/managed/recovery-assisted.test.ts @@ -0,0 +1,179 @@ +// @wc-ignore-file +import { beforeEach, expect, it, vi } from 'vitest'; +import { + buildEnvelopeWithAssisted, + decryptEnvelopeWithAssisted, + FreshSignInRequiredError, + hasAssistedWrapper, + type RecoverySecret, +} from './recovery'; +import { getManagedAccount } from './session'; +import { managedFetch, getManagedApiBase } from './api'; + +vi.mock('./session', () => ({ getManagedAccount: vi.fn() })); +vi.mock('./api', () => ({ + managedFetch: vi.fn(), + getManagedApiBase: vi.fn(), + hasManagedApi: vi.fn(() => true), +})); + +const AGENT = 'atomic:agent:9Hc-J_2n4jIpXqzTZMDSnNFOFB1fWqCsGSk3Wdyy9Bs'; + +/** A stand-in for the account service: a key per (agent, salt), like the real + * HMAC, and a switch for a sign-in that is too old to unlock with. */ +function fakeService({ fresh }: { fresh: boolean }) { + const keys = new Map(); + const keyIds = new Map(); + const seenSalts: string[] = []; + const service = { currentKey: 'key-1', appended: [] as unknown[] }; + + vi.mocked(managedFetch).mockImplementation(async (path, init) => { + if (path === '/auth/providers') { + return Response.json({ google: true, assisted_recovery: true }); + } + + if (path === '/recovery-secret/assisted-key') { + const { agent_subject, salt } = JSON.parse(String(init?.body)); + const unlocking = seenSalts.includes(salt); + + if (unlocking && !fresh) { + return Response.json( + { error: 'Sign in again', error_code: 'fresh_sign_in_required' }, + { status: 403 }, + ); + } + + seenSalts.push(salt); + const id = `${agent_subject}|${salt}`; + + if (!keys.has(id)) { + const bytes = crypto.getRandomValues(new Uint8Array(32)); + keys.set(id, btoa(String.fromCharCode(...bytes))); + keyIds.set(id, service.currentKey); + } + + return Response.json({ + key: keys.get(id), + key_id: keyIds.get(id), + rotate: keyIds.get(id) !== service.currentKey, + }); + } + + if (path === '/recovery-secret/wrappers') { + const body = JSON.parse(String(init?.body)); + service.appended.push(body.wrapper); + + return Response.json({ ...body, owner_email: 'person@example.com' }); + } + + return new Response(null, { status: 404 }); + }); + + return service; +} + +function stored( + request: Awaited>, +) { + return { + ...request, + owner_email: 'person@example.com', + kdf_algorithm: '', + kdf_params: {}, + salt: '', + wrappers: request.wrappers!.map(w => ({ ...w, created_at: 0 })), + created_at: 0, + updated_at: 0, + } as RecoverySecret; +} + +beforeEach(() => { + vi.mocked(getManagedAccount).mockResolvedValue({ + email: 'person@example.com', + }); + vi.mocked(getManagedApiBase).mockReturnValue('https://portal.example/api'); + vi.mocked(managedFetch).mockReset(); +}); + +it('a backup made for the account opens with the account alone', async () => { + fakeService({ fresh: true }); + const request = await buildEnvelopeWithAssisted({ + secret: 'the-agent-secret', + agentSubject: AGENT, + }); + + expect(request.wrappers).toHaveLength(1); + expect(request.wrappers![0].wrapper_type).toBe('atomic-assisted'); + // The DEK and the secret never go to the service. + const sent = vi + .mocked(managedFetch) + .mock.calls.map(([, init]) => String(init?.body ?? '')) + .join('\n'); + expect(sent).not.toContain('the-agent-secret'); + + const backup = stored(request); + expect(hasAssistedWrapper(backup)).toBe(true); + expect(await decryptEnvelopeWithAssisted(backup)).toBe('the-agent-secret'); +}); + +it('an old sign-in is told to sign in again', async () => { + fakeService({ fresh: false }); + const backup = stored( + await buildEnvelopeWithAssisted({ secret: 's', agentSubject: AGENT }), + ); + + await expect(decryptEnvelopeWithAssisted(backup)).rejects.toBeInstanceOf( + FreshSignInRequiredError, + ); +}); + +it('a build without an account service asks nobody', async () => { + const { hasManagedApi } = await import('./api'); + const { getAccountProviders } = await import('./accountProviders'); + vi.mocked(hasManagedApi).mockReturnValueOnce(false); + vi.mocked(managedFetch).mockClear(); + + expect(await getAccountProviders()).toEqual({ + google: false, + assisted_recovery: false, + }); + expect(managedFetch).not.toHaveBeenCalled(); +}); + +it('a wrapper from a rotated key is re-wrapped with the current one', async () => { + const service = fakeService({ fresh: true }); + const request = await buildEnvelopeWithAssisted({ + secret: 'the-agent-secret', + agentSubject: AGENT, + }); + expect(request.wrappers![0].kdf_params).toEqual({ key_id: 'key-1' }); + + service.currentKey = 'key-2'; + expect(await decryptEnvelopeWithAssisted(stored(request))).toBe( + 'the-agent-secret', + ); + + await vi.waitFor(() => expect(service.appended).toHaveLength(1)); + const [rewrapped] = service.appended as { + kdf_params: unknown; + salt: string; + }[]; + expect(rewrapped.kdf_params).toEqual({ key_id: 'key-2' }); + expect(rewrapped.salt).not.toBe(request.wrappers![0].salt); +}); + +it('an account that turned assisted recovery off gets no new wrapper', async () => { + const service = fakeService({ fresh: true }); + const request = await buildEnvelopeWithAssisted({ + secret: 's', + agentSubject: AGENT, + }); + vi.mocked(getManagedAccount).mockResolvedValue({ + email: 'person@example.com', + assisted_recovery_off: true, + }); + service.currentKey = 'key-2'; + await decryptEnvelopeWithAssisted(stored(request)); + await new Promise(resolve => setTimeout(resolve, 20)); + expect(service.appended).toHaveLength(0); +}); diff --git a/browser/data-browser/src/helpers/managed/recovery.ts b/browser/data-browser/src/helpers/managed/recovery.ts index 394c8ac272..df24a678be 100644 --- a/browser/data-browser/src/helpers/managed/recovery.ts +++ b/browser/data-browser/src/helpers/managed/recovery.ts @@ -6,9 +6,10 @@ import { wasmBinaryUrl, wasmJsUrl } from '../wasmUrls'; import { PRODUCT_NAME } from './product'; import { getManagedApiBase, managedFetch } from './api'; import { writeManagedAccountBinding } from './binding'; +import { getAccountProviders } from './accountProviders'; export type RecoveryWrapperInput = { - wrapper_type: 'webauthn-prf' | 'recovery-code'; + wrapper_type: 'webauthn-prf' | 'recovery-code' | 'atomic-assisted'; /** Empty for `webauthn-prf`: the authenticator's PRF output *is* the KEK. */ kdf_algorithm: string; kdf_params: Record; @@ -41,7 +42,10 @@ export type RecoverySecretInput = { }; export type RecoverySecret = { + /** The account key this backup is bound to. */ owner_email: string; + /** The address to show for that account, from newer control planes. */ + owner_address?: string; agent_subject: string; drive_subject?: string | null; encrypted_secret: string; @@ -795,6 +799,7 @@ export async function buildEnvelopeWithPasskeyAndCode({ }); const recoveryCode = generateRecoveryCode(); const codeWrapper = await wrapDekWithCode(sealed.dek, recoveryCode); + const assisted = await tryWrapDekWithAssisted(sealed.dek, agentSubject); return { recoveryCode, @@ -802,7 +807,7 @@ export async function buildEnvelopeWithPasskeyAndCode({ agentSubject, driveSubject, sealed, - wrappers: [passkeyWrapper, codeWrapper], + wrappers: [passkeyWrapper, codeWrapper, ...assisted], }), }; } @@ -824,6 +829,7 @@ export async function buildEnvelopeV2({ const sealed = await sealSecret(secret); const recoveryCode = generateRecoveryCode(); const wrapper = await wrapDekWithCode(sealed.dek, recoveryCode); + const assisted = await tryWrapDekWithAssisted(sealed.dek, agentSubject); return { recoveryCode, @@ -831,19 +837,287 @@ export async function buildEnvelopeV2({ agentSubject, driveSubject, sealed, - wrappers: [wrapper], + wrappers: [wrapper, ...assisted], }), }; } +// --- Assisted recovery: signing in to the account unlocks the identity --- +// +// The control plane holds a service key and hands a signed-in account the +// key-encryption key for one of its wrappers (see atomic-saas +// `src/assisted_recovery.rs`). Wrapping and unwrapping stay here, so the DEK +// and the secret never leave the browser. Unlocking needs a sign-in from the +// last half hour; an older session gets `FreshSignInRequiredError`. + +const ASSISTED_WRAPPER = 'atomic-assisted'; + +/** The account's sign-in is too old to unlock the identity; sign in again. */ +export class FreshSignInRequiredError extends Error { + constructor() { + super('Sign in again to unlock your account on this device.'); + this.name = /* @wc-ignore */ 'FreshSignInRequiredError'; + } +} + +/** Whether this deployment can unlock an identity for a signed-in account. */ +export async function isAssistedRecoveryAvailable(): Promise { + return (await getAccountProviders()).assisted_recovery; +} + +async function assistedKey( + agentSubject: string, + salt: string, + usage: KeyUsage[], +): Promise<{ key: CryptoKey; keyId?: string; rotate: boolean }> { + const response = await managedFetch('/recovery-secret/assisted-key', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ agent_subject: agentSubject, salt }), + }); + + if (!response.ok) { + const body = await response + .json() + .catch(() => null as { error_code?: string } | null); + + if (body?.error_code === 'fresh_sign_in_required') { + throw new FreshSignInRequiredError(); + } + + throw new Error( + `Could not reach your ${PRODUCT_NAME} account to unlock this backup.`, + ); + } + + const { key, key_id, rotate } = (await response.json()) as { + key: string; + key_id?: string; + rotate?: boolean; + }; + + return { + key: await crypto.subtle.importKey( + 'raw', + base64ToBytes(key), + 'AES-GCM', + false, + usage, + ), + keyId: key_id, + // The wrapper was made with a service key that has since been rotated. + rotate: rotate === true, + }; +} + +async function wrapDekWithAssisted( + dek: Uint8Array, + agentSubject: string, +): Promise { + const salt = bytesToBase64(randomBytes(SALT_BYTES)); + const { key, keyId } = await assistedKey(agentSubject, salt, ['encrypt']); + const wrapNonce = randomBytes(NONCE_BYTES); + const wrappedDek = await crypto.subtle.encrypt( + { name: 'AES-GCM', iv: wrapNonce }, + key, + dek, + ); + + return { + wrapper_type: ASSISTED_WRAPPER, + kdf_algorithm: 'hmac-sha256', + // Which service key made it, so it still opens after a rotation. + kdf_params: keyId ? { key_id: keyId } : {}, + salt, + wrapped_dek: bytesToBase64(new Uint8Array(wrappedDek)), + wrap_nonce: bytesToBase64(wrapNonce), + label: `${PRODUCT_NAME} account`, + }; +} + +/** The assisted wrapper when this deployment offers it, else nothing. Never + * throws: a backup without it still works with its passkey or code. */ +async function tryWrapDekWithAssisted( + dek: Uint8Array, + agentSubject: string, +): Promise { + try { + if (!(await isAssistedRecoveryAvailable())) return []; + + return [await wrapDekWithAssisted(dek, agentSubject)]; + } catch { + return []; + } +} + +export function hasAssistedWrapper(recovery: RecoverySecret): boolean { + return ( + recovery.format_version >= 2 && + recovery.wrappers.some(w => w.wrapper_type === ASSISTED_WRAPPER) + ); +} + +/** + * The backup for a signed-in account that nobody has to type or tap anything + * for: the DEK is wrapped only by the account's assisted key. Throws when the + * deployment does not offer assisted recovery, so the caller can fall back to + * a passkey or a recovery code. + */ +export async function buildEnvelopeWithAssisted({ + secret, + agentSubject, + driveSubject, +}: { + secret: string; + agentSubject: string; + driveSubject?: string | null; +}): Promise { + if (!(await isAssistedRecoveryAvailable())) { + throw new Error('Assisted recovery is not available here.'); + } + + const sealed = await sealSecret(secret); + const wrapper = await wrapDekWithAssisted(sealed.dek, agentSubject); + + return envelopeRequest({ + agentSubject, + driveSubject, + sealed, + wrappers: [wrapper], + }); +} + +/** Unlock with the account alone. Needs a recent sign-in. */ +export async function decryptEnvelopeWithAssisted( + recovery: RecoverySecret, +): Promise { + const wrapper = recovery.wrappers.find( + w => w.wrapper_type === ASSISTED_WRAPPER, + ); + + if (!wrapper) + throw new Error('This backup cannot be unlocked by signing in.'); + + const { key, rotate } = await assistedKey( + recovery.agent_subject, + wrapper.salt, + ['decrypt'], + ); + + return openWithDekKey( + recovery, + wrapper, + key, + 'Your account could not unlock this backup.', + // Re-wrap with the current service key; the new wrapper replaces this one. + rotate + ? dek => addAssistedWrapperInBackground(recovery, dek, true) + : undefined, + ); +} + +/** The DEK behind the assisted wrapper, for adding another way in. */ +async function assistedDek(recovery: RecoverySecret): Promise { + const wrapper = recovery.wrappers.find( + w => w.wrapper_type === ASSISTED_WRAPPER, + ); + + if (!wrapper) + throw new Error('This backup cannot be unlocked by signing in.'); + + const { key } = await assistedKey(recovery.agent_subject, wrapper.salt, [ + 'decrypt', + ]); + + try { + return await crypto.subtle.decrypt( + { name: 'AES-GCM', iv: base64ToBytes(wrapper.wrap_nonce) }, + key, + base64ToBytes(wrapper.wrapped_dek), + ); + } catch { + throw new Error('Your account could not unlock this backup.'); + } +} + +/** + * Turn assisted recovery on or off for the signed-in account. Off removes the + * assisted wrapper from the stored backup straight away; on lets the next + * unlock with a passkey or recovery code add it again. + */ +export async function setAssistedRecovery(enabled: boolean): Promise { + const response = await managedFetch('/recovery-secret/assisted', { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ enabled }), + }); + + if (!response.ok) { + throw new Error( + `Could not change this setting in your ${PRODUCT_NAME} account.`, + ); + } +} + +/** + * After a passkey or a recovery code opened a backup: add the assisted + * wrapper, so on the next device signing in is enough. In the background and + * best-effort; the unlock that just happened never waits on it. + */ +function addAssistedWrapperInBackground( + recovery: RecoverySecret, + dek: Uint8Array, + replace = false, +): void { + if ( + recovery.format_version !== 2 || + (hasAssistedWrapper(recovery) && !replace) + ) + return; + + void (async () => { + if (!(await isAssistedRecoveryAvailable())) return; + // The wrapper is appended to the signed-in account's backup, so only + // when that account is the one owning this backup. + const account = await getManagedAccount().catch(() => null); + + if ( + !account || + account.email !== recovery.owner_email || + account.assisted_recovery_off + ) + return; + + const wrapper = await wrapDekWithAssisted(dek, recovery.agent_subject); + const response = await managedFetch('/recovery-secret/wrappers', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + agent_subject: recovery.agent_subject, + encrypted_secret: recovery.encrypted_secret, + nonce: recovery.nonce, + wrapper, + }), + }); + + if (response.ok) + cacheRecoverySecret((await response.json()) as RecoverySecret); + })().catch(() => undefined); +} + /** Whether this backup can be unlocked by a passkey / by a typed code. */ export function envelopeWrapperKinds(recovery: RecoverySecret): { hasPasskey: boolean; hasCode: boolean; + /** Signing in to the account opens it (assisted recovery). */ + hasAccount: boolean; } { return { hasPasskey: recovery.wrappers.some(w => w.wrapper_type === 'webauthn-prf'), hasCode: recovery.wrappers.some(w => w.wrapper_type === 'recovery-code'), + hasAccount: recovery.wrappers.some( + w => w.wrapper_type === 'atomic-assisted', + ), }; } @@ -852,11 +1126,13 @@ async function openWithDekKey( wrapper: RecoveryWrapper, wrapKey: CryptoKey, wrongKeyMessage: string, + onDek?: (dek: Uint8Array) => void, ): Promise { let plaintext: ArrayBuffer; + let dek: ArrayBuffer; try { - const dek = await crypto.subtle.decrypt( + dek = await crypto.subtle.decrypt( { name: 'AES-GCM', iv: base64ToBytes(wrapper.wrap_nonce) }, wrapKey, base64ToBytes(wrapper.wrapped_dek), @@ -873,6 +1149,8 @@ async function openWithDekKey( throw new Error(wrongKeyMessage); } + onDek?.(new Uint8Array(dek)); + return new TextDecoder().decode(plaintext); } @@ -974,6 +1252,7 @@ export async function decryptEnvelopeWithPasskey( wrapper, key, 'That passkey could not unlock this backup.', + dek => addAssistedWrapperInBackground(recovery, dek), ); } @@ -1002,7 +1281,13 @@ export async function decryptEnvelopeV2( wrapper.kdf_params, ); - return openWithDekKey(recovery, wrapper, wrapKey, 'Wrong recovery code'); + return openWithDekKey( + recovery, + wrapper, + wrapKey, + 'Wrong recovery code', + dek => addAssistedWrapperInBackground(recovery, dek), + ); } /** @@ -1149,6 +1434,13 @@ export async function unifyAccountPasskey( 'Wrong recovery code. Use the recovery code saved for this account, not your agent secret.', ); } + } else if ( + hasAssistedWrapper(recovery) && + !recovery.wrappers.some(w => w.wrapper_type === 'webauthn-prf') + ) { + // Only the account opens this backup so far: a recent sign-in is enough + // to reach the DEK and add the passkey next to it. + dek = await assistedDek(recovery); } else { const { wrapper, key } = await unlockPasskeyWrapper(recovery); dek = await crypto.subtle.decrypt( @@ -1159,8 +1451,8 @@ export async function unifyAccountPasskey( } const { wrapper } = await wrapDekWithPasskey(new Uint8Array(dek), { - userName: recovery.owner_email, - userDisplayName: recovery.owner_email, + userName: recovery.owner_address ?? recovery.owner_email, + userDisplayName: recovery.owner_address ?? recovery.owner_email, createNew, }); if (!wrapper.kdf_params.account_passkey) diff --git a/browser/data-browser/src/helpers/managed/session.ts b/browser/data-browser/src/helpers/managed/session.ts index 4cb316baea..0638583746 100644 --- a/browser/data-browser/src/helpers/managed/session.ts +++ b/browser/data-browser/src/helpers/managed/session.ts @@ -7,10 +7,21 @@ import { PRODUCT_NAME } from './product'; import { hasManagedApi, managedFetch, setManagedDeviceToken } from './api'; export type ManagedAccount = { + /** The account key backups and bindings are stored under (`owner_email`). + * For older accounts it is their address; newer ones have an `acct_` id. */ email: string; + /** The address to show. Absent from control planes before account ids. */ + address?: string; + /** The person turned assisted recovery off in their settings. */ + assisted_recovery_off?: boolean; created_at?: number; }; +/** The address to show for an account. */ +export function accountAddress(account: ManagedAccount): string { + return account.address ?? account.email; +} + let sessionGeneration = 0; let pendingLogouts = 0; diff --git a/browser/data-browser/src/locales/de.po b/browser/data-browser/src/locales/de.po index 03b95ff94f..d58b2e0a76 100644 --- a/browser/data-browser/src/locales/de.po +++ b/browser/data-browser/src/locales/de.po @@ -3679,15 +3679,11 @@ msgstr "" msgid "Checking your {0} account…" msgstr "" -#. 0: PRODUCT_NAME -#: src/views/getting-started/GettingStartedFlow.tsx -msgid "To restore your account, sign in to your {0} account first, then come back here." -msgstr "" +#~ msgid "To restore your account, sign in to your {0} account first, then come back here." +#~ msgstr "" -#. 0: PRODUCT_NAME -#: src/views/getting-started/GettingStartedFlow.tsx -msgid "Sign in to your {0} account" -msgstr "" +#~ msgid "Sign in to your {0} account" +#~ msgstr "" #. 0: text #: src/chunks/TablePage/TableHeading.tsx @@ -5324,7 +5320,7 @@ msgstr "" msgid "Sign out & forget this device" msgstr "" -#. 0: account.email; 1: PRODUCT_NAME +#. 0: accountAddress(account); 1: PRODUCT_NAME #: src/components/AgentProfileHeader.tsx msgid "Manage {0} on {1}" msgstr "" @@ -6410,10 +6406,8 @@ msgstr "" msgid "Forgot it? Restore from {0}" msgstr "" -#. 0: PRODUCT_NAME -#: src/views/getting-started/GettingStartedFlow.tsx -msgid "Your backup is kept by your {0} account. Connect this device to it to restore." -msgstr "" +#~ msgid "Your backup is kept by your {0} account. Connect this device to it to restore." +#~ msgstr "" #. 0: action.label(ctx) #: src/actions/deriveTools.ts @@ -10889,8 +10883,10 @@ msgstr "" #~ msgid "Not set up. With an account on {0} we hold your key sealed, so an email gets you back in on a new device. Without one, losing every device loses this workspace." #~ msgstr "" -#~ msgid "This backup is sealed in this browser only. {0} is not holding a copy, so a new device could not get you back in." -#~ msgstr "" +#. 0: PRODUCT_NAME +#: src/components/AccountRecoveryCard.tsx +msgid "This backup is sealed in this browser only. {0} is not holding a copy, so a new device could not get you back in." +msgstr "" #~ msgid "You can get back in with:{0} {1}" #~ msgstr "" @@ -12398,6 +12394,52 @@ msgstr "" msgid "Search the drive for “{0}”" msgstr "" +#: src/helpers/managed/recovery.ts +msgid "Sign in again to unlock your account on this device." +msgstr "" + +#. 0: PRODUCT_NAME +#: src/helpers/managed/recovery.ts +msgid "{0} account" +msgstr "" + +#: src/helpers/managed/recovery.ts +msgid "Your account could not unlock this backup." +msgstr "" + +#. 0: restore.email +#: src/views/getting-started/GettingStartedFlow.tsx +msgid "Unlocking {0}…" +msgstr "" + +#: src/views/getting-started/GettingStartedFlow.tsx +msgid "Sign in again to open your account on this device." +msgstr "" + +#~ msgid "Continue with Google" +#~ msgstr "" + +#: src/views/getting-started/AccountSignInPanel.tsx +msgid "That sign-in expired. Pick an option to start again." +msgstr "" + +#: src/views/getting-started/AccountSignInPanel.tsx +msgid "Could not reach your account. Check your connection and try again." +msgstr "" + +#. 0: PRODUCT_NAME; 1: PRODUCT_NAME +#: src/components/AccountRecoveryCard.tsx +msgid "Signing in to your {0} account is enough to open your identity on a new device. {1} holds a key for that. Turn it off to rely only on your passkey or recovery code." +msgstr "" + +#~ msgid "Only your passkey or recovery code opens your identity. {0} cannot. It is added back the next time you unlock with one of them." +#~ msgstr "" + +#. 0: PRODUCT_NAME +#: src/components/AccountRecoveryCard.tsx +msgid "Only your passkey or recovery code opens your identity. {0} cannot." +msgstr "" + #. 0: conflict.email #: src/views/getting-started/GettingStartedFlow.tsx msgid "Signed out of {0}." diff --git a/browser/data-browser/src/locales/en.po b/browser/data-browser/src/locales/en.po index 66776c5f04..87a99713a0 100644 --- a/browser/data-browser/src/locales/en.po +++ b/browser/data-browser/src/locales/en.po @@ -3679,15 +3679,11 @@ msgstr "Enter your agent secret to unlock this drive on this device." msgid "Checking your {0} account…" msgstr "Checking your {0} account…" -#. 0: PRODUCT_NAME -#: src/views/getting-started/GettingStartedFlow.tsx -msgid "To restore your account, sign in to your {0} account first, then come back here." -msgstr "To restore your account, sign in to your {0} account first, then come back here." +#~ msgid "To restore your account, sign in to your {0} account first, then come back here." +#~ msgstr "To restore your account, sign in to your {0} account first, then come back here." -#. 0: PRODUCT_NAME -#: src/views/getting-started/GettingStartedFlow.tsx -msgid "Sign in to your {0} account" -msgstr "Sign in to your {0} account" +#~ msgid "Sign in to your {0} account" +#~ msgstr "Sign in to your {0} account" #. 0: text #: src/chunks/TablePage/TableHeading.tsx @@ -5335,7 +5331,7 @@ msgstr "Sign out and remove this device’s copy of your encrypted backup" msgid "Sign out & forget this device" msgstr "Sign out & forget this device" -#. 0: account.email; 1: PRODUCT_NAME +#. 0: accountAddress(account); 1: PRODUCT_NAME #: src/components/AgentProfileHeader.tsx msgid "Manage {0} on {1}" msgstr "Manage {0} on {1}" @@ -6421,10 +6417,8 @@ msgstr "Cloud Vault had nothing for this workspace:" msgid "Forgot it? Restore from {0}" msgstr "Forgot it? Restore from {0}" -#. 0: PRODUCT_NAME -#: src/views/getting-started/GettingStartedFlow.tsx -msgid "Your backup is kept by your {0} account. Connect this device to it to restore." -msgstr "Your backup is kept by your {0} account. Connect this device to it to restore." +#~ msgid "Your backup is kept by your {0} account. Connect this device to it to restore." +#~ msgstr "Your backup is kept by your {0} account. Connect this device to it to restore." #. 0: action.label(ctx) #: src/actions/deriveTools.ts @@ -10923,8 +10917,10 @@ msgstr "The selected model is not in the zero-retention list. Choose another mod #~ msgid "Not set up. With an account on {0} we hold your key sealed, so an email gets you back in on a new device. Without one, losing every device loses this workspace." #~ msgstr "Not set up. With an account on {0} we hold your key sealed, so an email gets you back in on a new device. Without one, losing every device loses this workspace." -#~ msgid "This backup is sealed in this browser only. {0} is not holding a copy, so a new device could not get you back in." -#~ msgstr "This backup is sealed in this browser only. {0} is not holding a copy, so a new device could not get you back in." +#. 0: PRODUCT_NAME +#: src/components/AccountRecoveryCard.tsx +msgid "This backup is sealed in this browser only. {0} is not holding a copy, so a new device could not get you back in." +msgstr "This backup is sealed in this browser only. {0} is not holding a copy, so a new device could not get you back in." #~ msgid "You can get back in with:{0} {1}" #~ msgstr "You can get back in with:{0} {1}" @@ -12444,6 +12440,52 @@ msgstr "No column matches" msgid "Search the drive for “{0}”" msgstr "Search the drive for “{0}”" +#: src/helpers/managed/recovery.ts +msgid "Sign in again to unlock your account on this device." +msgstr "Sign in again to unlock your account on this device." + +#. 0: PRODUCT_NAME +#: src/helpers/managed/recovery.ts +msgid "{0} account" +msgstr "{0} account" + +#: src/helpers/managed/recovery.ts +msgid "Your account could not unlock this backup." +msgstr "Your account could not unlock this backup." + +#. 0: restore.email +#: src/views/getting-started/GettingStartedFlow.tsx +msgid "Unlocking {0}…" +msgstr "Unlocking {0}…" + +#: src/views/getting-started/GettingStartedFlow.tsx +msgid "Sign in again to open your account on this device." +msgstr "Sign in again to open your account on this device." + +#~ msgid "Continue with Google" +#~ msgstr "Continue with Google" + +#: src/views/getting-started/AccountSignInPanel.tsx +msgid "That sign-in expired. Pick an option to start again." +msgstr "That sign-in expired. Pick an option to start again." + +#: src/views/getting-started/AccountSignInPanel.tsx +msgid "Could not reach your account. Check your connection and try again." +msgstr "Could not reach your account. Check your connection and try again." + +#. 0: PRODUCT_NAME; 1: PRODUCT_NAME +#: src/components/AccountRecoveryCard.tsx +msgid "Signing in to your {0} account is enough to open your identity on a new device. {1} holds a key for that. Turn it off to rely only on your passkey or recovery code." +msgstr "Signing in to your {0} account is enough to open your identity on a new device. {1} holds a key for that. Turn it off to rely only on your passkey or recovery code." + +#~ msgid "Only your passkey or recovery code opens your identity. {0} cannot. It is added back the next time you unlock with one of them." +#~ msgstr "Only your passkey or recovery code opens your identity. {0} cannot. It is added back the next time you unlock with one of them." + +#. 0: PRODUCT_NAME +#: src/components/AccountRecoveryCard.tsx +msgid "Only your passkey or recovery code opens your identity. {0} cannot." +msgstr "Only your passkey or recovery code opens your identity. {0} cannot." + #. 0: conflict.email #: src/views/getting-started/GettingStartedFlow.tsx msgid "Signed out of {0}." diff --git a/browser/data-browser/src/locales/es.po b/browser/data-browser/src/locales/es.po index d34b3b733c..fa84063046 100644 --- a/browser/data-browser/src/locales/es.po +++ b/browser/data-browser/src/locales/es.po @@ -3679,15 +3679,11 @@ msgstr "" msgid "Checking your {0} account…" msgstr "" -#. 0: PRODUCT_NAME -#: src/views/getting-started/GettingStartedFlow.tsx -msgid "To restore your account, sign in to your {0} account first, then come back here." -msgstr "" +#~ msgid "To restore your account, sign in to your {0} account first, then come back here." +#~ msgstr "" -#. 0: PRODUCT_NAME -#: src/views/getting-started/GettingStartedFlow.tsx -msgid "Sign in to your {0} account" -msgstr "" +#~ msgid "Sign in to your {0} account" +#~ msgstr "" #. 0: text #: src/chunks/TablePage/TableHeading.tsx @@ -5324,7 +5320,7 @@ msgstr "" msgid "Sign out & forget this device" msgstr "" -#. 0: account.email; 1: PRODUCT_NAME +#. 0: accountAddress(account); 1: PRODUCT_NAME #: src/components/AgentProfileHeader.tsx msgid "Manage {0} on {1}" msgstr "" @@ -6410,10 +6406,8 @@ msgstr "" msgid "Forgot it? Restore from {0}" msgstr "" -#. 0: PRODUCT_NAME -#: src/views/getting-started/GettingStartedFlow.tsx -msgid "Your backup is kept by your {0} account. Connect this device to it to restore." -msgstr "" +#~ msgid "Your backup is kept by your {0} account. Connect this device to it to restore." +#~ msgstr "" #. 0: action.label(ctx) #: src/actions/deriveTools.ts @@ -10889,8 +10883,10 @@ msgstr "" #~ msgid "Not set up. With an account on {0} we hold your key sealed, so an email gets you back in on a new device. Without one, losing every device loses this workspace." #~ msgstr "" -#~ msgid "This backup is sealed in this browser only. {0} is not holding a copy, so a new device could not get you back in." -#~ msgstr "" +#. 0: PRODUCT_NAME +#: src/components/AccountRecoveryCard.tsx +msgid "This backup is sealed in this browser only. {0} is not holding a copy, so a new device could not get you back in." +msgstr "" #~ msgid "You can get back in with:{0} {1}" #~ msgstr "" @@ -12398,6 +12394,52 @@ msgstr "" msgid "Search the drive for “{0}”" msgstr "" +#: src/helpers/managed/recovery.ts +msgid "Sign in again to unlock your account on this device." +msgstr "" + +#. 0: PRODUCT_NAME +#: src/helpers/managed/recovery.ts +msgid "{0} account" +msgstr "" + +#: src/helpers/managed/recovery.ts +msgid "Your account could not unlock this backup." +msgstr "" + +#. 0: restore.email +#: src/views/getting-started/GettingStartedFlow.tsx +msgid "Unlocking {0}…" +msgstr "" + +#: src/views/getting-started/GettingStartedFlow.tsx +msgid "Sign in again to open your account on this device." +msgstr "" + +#~ msgid "Continue with Google" +#~ msgstr "" + +#: src/views/getting-started/AccountSignInPanel.tsx +msgid "That sign-in expired. Pick an option to start again." +msgstr "" + +#: src/views/getting-started/AccountSignInPanel.tsx +msgid "Could not reach your account. Check your connection and try again." +msgstr "" + +#. 0: PRODUCT_NAME; 1: PRODUCT_NAME +#: src/components/AccountRecoveryCard.tsx +msgid "Signing in to your {0} account is enough to open your identity on a new device. {1} holds a key for that. Turn it off to rely only on your passkey or recovery code." +msgstr "" + +#~ msgid "Only your passkey or recovery code opens your identity. {0} cannot. It is added back the next time you unlock with one of them." +#~ msgstr "" + +#. 0: PRODUCT_NAME +#: src/components/AccountRecoveryCard.tsx +msgid "Only your passkey or recovery code opens your identity. {0} cannot." +msgstr "" + #. 0: conflict.email #: src/views/getting-started/GettingStartedFlow.tsx msgid "Signed out of {0}." diff --git a/browser/data-browser/src/locales/fr.po b/browser/data-browser/src/locales/fr.po index bb7ee5ee81..b900873f8c 100644 --- a/browser/data-browser/src/locales/fr.po +++ b/browser/data-browser/src/locales/fr.po @@ -3679,15 +3679,11 @@ msgstr "" msgid "Checking your {0} account…" msgstr "" -#. 0: PRODUCT_NAME -#: src/views/getting-started/GettingStartedFlow.tsx -msgid "To restore your account, sign in to your {0} account first, then come back here." -msgstr "" +#~ msgid "To restore your account, sign in to your {0} account first, then come back here." +#~ msgstr "" -#. 0: PRODUCT_NAME -#: src/views/getting-started/GettingStartedFlow.tsx -msgid "Sign in to your {0} account" -msgstr "" +#~ msgid "Sign in to your {0} account" +#~ msgstr "" #. 0: text #: src/chunks/TablePage/TableHeading.tsx @@ -5324,7 +5320,7 @@ msgstr "" msgid "Sign out & forget this device" msgstr "" -#. 0: account.email; 1: PRODUCT_NAME +#. 0: accountAddress(account); 1: PRODUCT_NAME #: src/components/AgentProfileHeader.tsx msgid "Manage {0} on {1}" msgstr "" @@ -6410,10 +6406,8 @@ msgstr "" msgid "Forgot it? Restore from {0}" msgstr "" -#. 0: PRODUCT_NAME -#: src/views/getting-started/GettingStartedFlow.tsx -msgid "Your backup is kept by your {0} account. Connect this device to it to restore." -msgstr "" +#~ msgid "Your backup is kept by your {0} account. Connect this device to it to restore." +#~ msgstr "" #. 0: action.label(ctx) #: src/actions/deriveTools.ts @@ -10889,8 +10883,10 @@ msgstr "" #~ msgid "Not set up. With an account on {0} we hold your key sealed, so an email gets you back in on a new device. Without one, losing every device loses this workspace." #~ msgstr "" -#~ msgid "This backup is sealed in this browser only. {0} is not holding a copy, so a new device could not get you back in." -#~ msgstr "" +#. 0: PRODUCT_NAME +#: src/components/AccountRecoveryCard.tsx +msgid "This backup is sealed in this browser only. {0} is not holding a copy, so a new device could not get you back in." +msgstr "" #~ msgid "You can get back in with:{0} {1}" #~ msgstr "" @@ -12398,6 +12394,52 @@ msgstr "" msgid "Search the drive for “{0}”" msgstr "" +#: src/helpers/managed/recovery.ts +msgid "Sign in again to unlock your account on this device." +msgstr "" + +#. 0: PRODUCT_NAME +#: src/helpers/managed/recovery.ts +msgid "{0} account" +msgstr "" + +#: src/helpers/managed/recovery.ts +msgid "Your account could not unlock this backup." +msgstr "" + +#. 0: restore.email +#: src/views/getting-started/GettingStartedFlow.tsx +msgid "Unlocking {0}…" +msgstr "" + +#: src/views/getting-started/GettingStartedFlow.tsx +msgid "Sign in again to open your account on this device." +msgstr "" + +#~ msgid "Continue with Google" +#~ msgstr "" + +#: src/views/getting-started/AccountSignInPanel.tsx +msgid "That sign-in expired. Pick an option to start again." +msgstr "" + +#: src/views/getting-started/AccountSignInPanel.tsx +msgid "Could not reach your account. Check your connection and try again." +msgstr "" + +#. 0: PRODUCT_NAME; 1: PRODUCT_NAME +#: src/components/AccountRecoveryCard.tsx +msgid "Signing in to your {0} account is enough to open your identity on a new device. {1} holds a key for that. Turn it off to rely only on your passkey or recovery code." +msgstr "" + +#~ msgid "Only your passkey or recovery code opens your identity. {0} cannot. It is added back the next time you unlock with one of them." +#~ msgstr "" + +#. 0: PRODUCT_NAME +#: src/components/AccountRecoveryCard.tsx +msgid "Only your passkey or recovery code opens your identity. {0} cannot." +msgstr "" + #. 0: conflict.email #: src/views/getting-started/GettingStartedFlow.tsx msgid "Signed out of {0}." diff --git a/browser/data-browser/src/views/getting-started/AccountSignInPanel.tsx b/browser/data-browser/src/views/getting-started/AccountSignInPanel.tsx new file mode 100644 index 0000000000..6224df3ca9 --- /dev/null +++ b/browser/data-browser/src/views/getting-started/AccountSignInPanel.tsx @@ -0,0 +1,297 @@ +import { useEffect, useRef, useState, type FormEvent } from 'react'; +import { styled, useTheme } from 'styled-components'; +import { AccountSignIn } from '@tomic/service-ui'; +import '@tomic/service-ui/styles.css'; +import { + getAccountProviders, + googleSignInUrl, + sendAccountEmailLink, +} from '../../helpers/managed/accountProviders'; +import { signInWithAccountPasskey } from '../../helpers/managed/accountPasskey'; +import { getManagedAccount } from '../../helpers/managed/session'; +import { hasPasskeyApi } from '../../helpers/passkeySupport'; +import { + approvalUrl, + awaitDeviceLink, + requestDeviceLink, + type LinkRequest, +} from '../../helpers/managed/deviceLink'; +import { openExternal } from '../../helpers/openExternal'; +import { CardError } from './chrome'; + +const EMAIL_POLL_MS = 2000; + +/** + * The account's ways in, the same component and the same options as the + * portal's sign-in page: Google, passkey, email link. `onSignedIn` runs once + * this browser holds an account session, however it got one. + */ +export function AccountSignInPanel({ + portalUrl, + disabled, + onSignedIn, +}: { + portalUrl: string; + disabled?: boolean; + onSignedIn: () => void; +}) { + const theme = useTheme(); + const [providers, setProviders] = useState({ + google: false, + assisted_recovery: false, + }); + const [email, setEmail] = useState(''); + const [busy, setBusy] = useState(false); + const [sending, setSending] = useState(false); + const [sentTo, setSentTo] = useState(null); + const [error, setError] = useState(null); + const signedIn = useRef(onSignedIn); + + useEffect(() => { + signedIn.current = onSignedIn; + }); + + useEffect(() => { + let live = true; + void getAccountProviders().then(p => live && setProviders(p)); + + return () => { + live = false; + }; + }, []); + + // The email link opens on the portal, in another tab or on the phone that + // got the mail. The shared cookie is how this page hears about it. + useEffect(() => { + if (!sentTo) return; + + const timer = window.setInterval(() => { + void getManagedAccount() + .catch(() => null) + .then(account => { + if (account) { + window.clearInterval(timer); + signedIn.current(); + } + }); + }, EMAIL_POLL_MS); + + return () => window.clearInterval(timer); + }, [sentTo]); + + async function handlePasskey() { + setBusy(true); + setError(null); + + const outcome = await signInWithAccountPasskey(email).catch( + (err: unknown) => (err instanceof Error ? err : new Error(String(err))), + ); + setBusy(false); + + if (outcome instanceof Error) setError(outcome.message); + else if (outcome) onSignedIn(); + } + + async function handleEmail(event: FormEvent) { + event.preventDefault(); + setSending(true); + setError(null); + + const outcome = await sendAccountEmailLink(email).catch((err: unknown) => + err instanceof Error ? err : new Error(String(err)), + ); + setSending(false); + + if (outcome instanceof Error) { + setError(outcome.message); + + return; + } + + // Local development hands the link out instead of mailing it, built on + // the requesting origin; the mailed one always opens on the portal. + if (outcome) { + const link = new URL(outcome); + window.open( + new URL(link.pathname + link.search, portalUrl).toString(), + '_blank', + 'noopener', + ); + } + + setSentTo(email.trim()); + } + + return ( + + void handlePasskey()} + passkeySupported={hasPasskeyApi()} + email={email} + onEmailChange={setEmail} + onSubmitEmail={e => void handleEmail(e)} + busy={busy || disabled} + sending={sending} + theme={theme.darkMode ? 'dark' : 'light'} + assistedRecovery={providers.assisted_recovery} + notice={ + error ? ( + {error} + ) : sentTo ? ( + + We sent a link to {sentTo}. Open it, then come back here: this + page continues by itself. + + ) : null + } + /> + + ); +} + +const Themed = styled.div` + --service-accent: ${p => p.theme.colors.main}; + --service-surface: ${p => p.theme.colors.bg}; + --service-on-accent: ${p => p.theme.colors.bg}; + --service-muted: ${p => p.theme.colors.textLight}; + --service-text: ${p => p.theme.colors.text}; + --service-border: ${p => p.theme.colors.bg2}; + --service-input-bg: ${p => p.theme.colors.bg}; + --service-radius: ${p => p.theme.radius}; +`; + +const Sent = styled.p` + margin: 0; + font-size: 0.9rem; + color: ${p => p.theme.colors.textLight}; +`; + +/** + * The same options for an app that cannot hold the account cookie (the + * desktop and Android apps, a self-hosted origin): each one opens the + * portal in the system browser, straight at that option, with a device-link + * code, and this screen continues once the code is approved there. Google + * refuses to sign in inside an app window anyway. + */ +export function AccountSignInViaBrowser({ + portalUrl, + disabled, + onSignedIn, +}: { + portalUrl: string; + disabled?: boolean; + onSignedIn: () => void; +}) { + const theme = useTheme(); + const [providers, setProviders] = useState({ + google: false, + assisted_recovery: false, + }); + const [email, setEmail] = useState(''); + const [request, setRequest] = useState(null); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const waiting = useRef(null); + const signedIn = useRef(onSignedIn); + + useEffect(() => { + signedIn.current = onSignedIn; + }); + + useEffect(() => { + let live = true; + void getAccountProviders().then(p => live && setProviders(p)); + + return () => { + live = false; + waiting.current?.abort(); + }; + }, []); + + function wait(issued: LinkRequest) { + if (waiting.current) return; + + const controller = new AbortController(); + waiting.current = controller; + + void awaitDeviceLink(portalUrl, issued, { signal: controller.signal }) + .catch(() => 'expired' as const) + .then(outcome => { + waiting.current = null; + setRequest(null); + + if (controller.signal.aborted) return; + + if (outcome === 'linked') signedIn.current(); + else setError('That sign-in expired. Pick an option to start again.'); + }); + } + + async function open(via: 'google' | 'passkey' | 'email') { + setBusy(true); + setError(null); + + const issued = + request ?? + (await requestDeviceLink(portalUrl).catch((err: unknown) => + err instanceof Error ? err : new Error(String(err)), + )); + setBusy(false); + + if (issued instanceof Error) { + setError( + issued instanceof TypeError + ? 'Could not reach your account. Check your connection and try again.' + : issued.message, + ); + + return; + } + + setRequest(issued); + const url = new URL(approvalUrl(portalUrl, issued.user_code)); + url.searchParams.set('via', via); + + if (via === 'email' && email.trim()) { + url.searchParams.set('email', email.trim()); + } + + await openExternal(url.toString()); + wait(issued); + } + + return ( + + void open('google') : undefined} + onPasskey={() => void open('passkey')} + email={email} + onEmailChange={setEmail} + onSubmitEmail={e => { + e.preventDefault(); + void open('email'); + }} + busy={busy || disabled} + theme={theme.darkMode ? 'dark' : 'light'} + assistedRecovery={providers.assisted_recovery} + notice={ + error ? ( + {error} + ) : request ? ( + + Finish in your browser, then approve the code{' '} + {request.user_code}. This screen continues by + itself. + + ) : null + } + /> + + ); +} diff --git a/browser/data-browser/src/views/getting-started/GettingStartedFlow.test.tsx b/browser/data-browser/src/views/getting-started/GettingStartedFlow.test.tsx index 2c57d7e72f..13c8a59e83 100644 --- a/browser/data-browser/src/views/getting-started/GettingStartedFlow.test.tsx +++ b/browser/data-browser/src/views/getting-started/GettingStartedFlow.test.tsx @@ -74,6 +74,8 @@ vi.mock('../../helpers/managed/deviceLink', () => ({ })); vi.mock('../../helpers/managed/session', () => ({ getManagedAccount: async () => state.account, + accountAddress: (account: { email: string; address?: string }) => + account.address ?? account.email, })); vi.mock('../../helpers/managedServer', () => ({ fetchManagedInfo: async () => null, diff --git a/browser/data-browser/src/views/getting-started/GettingStartedFlow.tsx b/browser/data-browser/src/views/getting-started/GettingStartedFlow.tsx index 80d5dc4a0d..eb2f8ee0fe 100644 --- a/browser/data-browser/src/views/getting-started/GettingStartedFlow.tsx +++ b/browser/data-browser/src/views/getting-started/GettingStartedFlow.tsx @@ -27,7 +27,10 @@ import { paths } from '../../routes/paths'; import { Button } from '../../components/Button'; import { Column } from '../../components/Row'; import { NewIdentitySection } from '../../components/NewIdentitySection'; -import { getManagedAccount } from '../../helpers/managed/session'; +import { + accountAddress, + getManagedAccount, +} from '../../helpers/managed/session'; import { getManagedPortalUrl } from '../../helpers/managed/cloudSync'; import { safePortalUrl } from '../../helpers/managed/api'; import { @@ -44,7 +47,11 @@ import { isRunningInTauri } from '../../helpers/tauri'; import { openExternal } from '../../helpers/openExternal'; import { buildEnvelopeV2, + buildEnvelopeWithAssisted, buildEnvelopeWithPasskeyAndCode, + decryptEnvelopeWithAssisted, + FreshSignInRequiredError, + hasAssistedWrapper, saveRecoverySecret, getRecoverySecret, getUnlockableRecoverySecret, @@ -59,11 +66,14 @@ import { type SecretAccountConflict, } from '../../helpers/managed/recovery'; import { CodeBlock } from '../../components/CodeBlock'; +import { + AccountSignInPanel, + AccountSignInViaBrowser, +} from './AccountSignInPanel'; import { InputStyled, InputWrapper } from '../../components/forms/InputStyles'; import { FaArrowLeft, FaKey } from 'react-icons/fa6'; import { Logo } from '../../components/Logo'; import { ConnectDeviceStep } from './ConnectDeviceStep'; -import { LinkProviderPanel } from '../../components/Vault/LinkProviderPanel'; import { canHoldProviderCookie, getRememberedProvider, @@ -266,7 +276,7 @@ export function GettingStartedFlow({ const account = await getManagedAccount(); if (!cancelled && account?.email) { - setManagedUsername(account.email.split('@')[0]); + setManagedUsername(accountAddress(account).split('@')[0]); } } catch { // Not signed in to the managed (or unreachable) — continue without a @@ -362,6 +372,74 @@ export function GettingStartedFlow({ return recoveryCode; } + /** + * The account's own ways in, above the passkey, code and secret: while the + * account is unlocking the identity by itself, say so; where there is no + * session, or it is too old to unlock with, offer the same sign-in options + * as the portal (the shared `AccountSignIn`), which end back here signed in. + */ + function accountSignIn() { + if (restore.phase === 'ready' && assistedUnlock === 'trying') { + return ( + Unlocking {restore.email}… + ); + } + + const offerSignIn = + !!knownPortalUrl && + (restore.phase === 'no-session' || + (restore.phase === 'ready' && assistedUnlock === 'needs-sign-in')); + + if (!offerSignIn || !knownPortalUrl) return null; + + const onSignedIn = () => setRestoreAttempt(n => n + 1); + + return ( + + {assistedUnlock === 'needs-sign-in' ? ( + + Sign in again to open your account on this device. + + ) : null} + {/* The same options either way; an app that cannot hold the + account cookie finishes each one in the system browser. */} + {canHoldProviderCookie(knownPortalUrl) ? ( + + ) : ( + + )} + + ); + } + + // The backup when the account service offers assisted recovery: wrapped by + // the account alone, so there is no passkey to register and no code to + // save, and signing in on any other device opens it. Resolves false when + // the service does not offer it, so the passkey and code step runs as + // before. + async function backupWithAccount(secret: string): Promise { + try { + const request = await buildEnvelopeWithAssisted({ + secret, + agentSubject: requireAgentSubject(), + driveSubject: newDriveSubject.current ?? null, + }); + await saveRecoverySecret(request); + + return true; + } catch { + return false; + } + } + // ─── Restore ("Forgot your secret?") ───────────────────────────────────── const [restore, setRestore] = useState({ phase: 'checking' }); const returnToPortal = @@ -416,6 +494,15 @@ export function GettingStartedFlow({ * step. A page reload would do the same and lose the user's place. */ const [restoreAttempt, setRestoreAttempt] = useState(0); + /** + * Opening the backup with the account alone (assisted recovery), which + * runs by itself as soon as a signed-in account's backup allows it. + * `needs-sign-in`: the sign-in is too old to unlock with, so the step + * offers signing in again next to the passkey and the code. + */ + const [assistedUnlock, setAssistedUnlock] = useState< + 'idle' | 'trying' | 'needs-sign-in' + >('idle'); useEffect(() => { if (step !== 'restore' && step !== 'signin') return; @@ -440,15 +527,38 @@ export function GettingStartedFlow({ setRestore({ phase: 'ready', secret, - email: account?.email ?? secret.owner_email, + email: account + ? accountAddress(account) + : (secret.owner_address ?? secret.owner_email), }); + if ( + account?.email === secret.owner_email && + hasAssistedWrapper(secret) + ) { + setAssistedUnlock('trying'); + + try { + const plaintext = await decryptEnvelopeWithAssisted(secret); + if (cancelled) return; + await handleSignInWithSecret(plaintext); + } catch (err) { + if (!cancelled) { + setAssistedUnlock( + err instanceof FreshSignInRequiredError + ? 'needs-sign-in' + : 'idle', + ); + } + } + } + return; } setRestore( account?.email - ? { phase: 'no-backup', email: account.email } + ? { phase: 'no-backup', email: accountAddress(account) } : { phase: 'no-session' }, ); } catch { @@ -1009,6 +1119,8 @@ export function GettingStartedFlow({ ) : null} + {accountSignIn()} + {/* Several accounts on this machine: ask which, rather than guessing and raising a prompt for the wrong one. */} {knownAccounts.length > 1 ? ( @@ -1026,7 +1138,7 @@ export function GettingStartedFlow({ onClick={() => unlockWithPasskey(account)} data-test='account-choice' > - {account.owner_email} + {account.owner_address ?? account.owner_email} ))} or sign in another way @@ -1117,9 +1229,7 @@ export function GettingStartedFlow({ step checks whether this account has a backup. */} {knownAccounts.length === 0 && knownPortalUrl && - (restore.phase === 'ready' || - (restore.phase === 'no-session' && - !canHoldProviderCookie(knownPortalUrl))) ? ( + restore.phase === 'ready' ? ( - )} - - ) - ) : restore.phase === 'no-backup' ? ( + ) : restore.phase === 'no-session' ? null : restore.phase === + 'no-backup' ? ( inviteToken ? ( // The portal sends an invitee here whenever it cannot rule // out an earlier identity. With nothing to restore, the @@ -1536,6 +1608,9 @@ export function GettingStartedFlow({ fromManaged ? backupWithPasskey : undefined } onBackupWithCode={fromManaged ? backupWithCode : undefined} + onBackupWithAccount={ + fromManaged ? backupWithAccount : undefined + } onAfterCreate={ fromManaged ? enableEncryptedBackup : undefined } diff --git a/browser/e2e/tests/native-account-restore.spec.ts b/browser/e2e/tests/native-account-restore.spec.ts index 9d27316056..87aa02aced 100644 --- a/browser/e2e/tests/native-account-restore.spec.ts +++ b/browser/e2e/tests/native-account-restore.spec.ts @@ -44,12 +44,10 @@ test('a fresh Mac install can start account recovery before it has an agent', as await page.goto(`${FRONTEND_URL}/app/welcome`); await page.getByRole('button', { name: 'Sign in', exact: true }).click(); await expect(page.getByLabel('Agent secret', { exact: true })).toBeVisible(); - await page.getByRole('button', { name: /^Forgot it\? Restore from/ }).click(); - - await expect( - page.getByRole('heading', { name: 'Restore account' }), - ).toBeVisible(); + // No agent and no session: the sign-in step itself offers the account's + // options, each finished in the system browser, so recovery starts here. + await expect(page.getByLabel('Email', { exact: true })).toBeVisible(); await expect( - page.getByRole('button', { name: 'Connect existing account' }), + page.getByRole('button', { name: 'Email me a link' }), ).toBeVisible(); }); diff --git a/browser/service-ui/README.md b/browser/service-ui/README.md index e99e8bbcb4..d890c3957f 100644 --- a/browser/service-ui/README.md +++ b/browser/service-ui/README.md @@ -14,3 +14,9 @@ Canonical copy lives here instead of separate product-name constants per app. Build before building either consumer: `pnpm --dir browser/service-ui build`. The workspace build does this in dependency order. The paired SaaS checkout uses a file dependency, like its existing `@tomic/lib` and `@tomic/edit-mode` dependencies. + +`AccountSignIn` is every way into an Atomic account (Google, passkey, email +link), used by the portal's sign-in page, its homepage signup panel and the +app's sign-in and restore steps, so no screen offers a different set. Hosts +pass the actions; `--service-on-accent`, `--service-border`, +`--service-input-bg` and `--service-radius` theme it further. diff --git a/browser/service-ui/src/AccountSignIn.tsx b/browser/service-ui/src/AccountSignIn.tsx new file mode 100644 index 0000000000..2369480657 --- /dev/null +++ b/browser/service-ui/src/AccountSignIn.tsx @@ -0,0 +1,301 @@ +import { useRef, type FormEvent, type ReactNode } from 'react'; + +/** + * Every way into an Atomic account, in one order, wherever someone signs in: + * the portal's sign-in page, the homepage signup panel and the app. Hosts + * pass the actions; this owns which options exist and how they look, so no + * screen can quietly drop one. + */ +export type AccountSignInCopy = { + google: string; + passkey: string; + passkeyUnavailable: string; + or: string; + emailLabel: string; + send: string; + sending: string; + info: AccountSignInInfoCopy; +}; + +/** "How safe is each option?": what each one trusts, and who can see what. */ +export type AccountSignInInfoCopy = { + open: string; + title: string; + close: string; + options: { name: string; text: string }[]; + unlockTitle: string; + /** When signing in alone opens the identity (assisted recovery). */ + unlockAssisted: string; + /** When the identity also needs a passkey or recovery code. */ + unlockSeparate: string; +}; + +export const ACCOUNT_SIGN_IN_COPY: Record<'en' | 'nl', AccountSignInCopy> = { + en: { + google: 'Google', + passkey: 'Sign in with passkey', + passkeyUnavailable: + 'This browser does not support passkeys. Use Google or an email link instead.', + or: 'or', + emailLabel: 'Email', + send: 'Email me a link', + sending: 'Sending', + info: { + open: 'How safe is each option?', + title: 'How safe is each option?', + close: 'Close', + options: [ + { + name: 'Passkey', + text: 'The safest. Your fingerprint, face or screen lock proves it is you. The key stays on your device or in your password manager, a fake website cannot use it, and nobody else is involved.', + }, + { + name: 'Google', + text: 'Google confirms your email address to us, and that address is all we receive. Google learns that you signed in to Atomic. Whoever controls your Google account can sign in.', + }, + { + name: 'Email link', + text: 'We send a link that works once, within 24 hours. Whoever can read your inbox can sign in. The email goes out through our mail provider, Postmark.', + }, + ], + unlockTitle: 'What signing in opens', + unlockAssisted: + 'Any of these is enough to open your Atomic identity on a new device. That works because Atomic keeps a key that, together with our database, can unlock your encrypted identity backup. Our service only hands it to your own account right after you sign in. So this is convenient, but not zero-knowledge: someone who got hold of both that key and our database could open your identity. You can turn this off under account recovery in the app, and rely only on your passkey or recovery code.', + unlockSeparate: + 'Signing in gives you your account: billing, hosted drives and your encrypted backup. Opening your Atomic identity on a new device also needs your passkey or recovery code, which Atomic cannot read.', + }, + }, + nl: { + google: 'Google', + passkey: 'Inloggen met passkey', + passkeyUnavailable: + 'Deze browser ondersteunt geen passkeys. Gebruik Google of een e-maillink.', + or: 'of', + emailLabel: 'E-mail', + send: 'Stuur me een link', + sending: 'Bezig met versturen', + info: { + open: 'Hoe veilig is elke optie?', + title: 'Hoe veilig is elke optie?', + close: 'Sluiten', + options: [ + { + name: 'Passkey', + text: 'Het veiligst. Je vingerafdruk, gezicht of schermvergrendeling bewijst dat jij het bent. De sleutel blijft op je apparaat of in je wachtwoordbeheerder, een nepwebsite kan hem niet gebruiken en er komt niemand anders aan te pas.', + }, + { + name: 'Google', + text: 'Google bevestigt je e-mailadres aan ons, en dat adres is alles wat we krijgen. Google ziet dat je bij Atomic inlogt. Wie je Google-account beheert, kan inloggen.', + }, + { + name: 'E-maillink', + text: 'We sturen een link die één keer werkt, binnen 24 uur. Wie je inbox kan lezen, kan inloggen. De e-mail gaat via onze mailprovider Postmark.', + }, + ], + unlockTitle: 'Wat inloggen opent', + unlockAssisted: + 'Elk van deze opties is genoeg om je Atomic-identiteit op een nieuw apparaat te openen. Dat kan omdat Atomic een sleutel bewaart die, samen met onze database, je versleutelde identiteitsback-up kan openen. Onze dienst geeft die alleen aan je eigen account, direct nadat je bent ingelogd. Dat is handig, maar niet zero-knowledge: wie zowel die sleutel als onze database in handen krijgt, kan je identiteit openen. Je kunt dit uitzetten bij accountherstel in de app. Dan werken alleen je passkey of herstelcode nog.', + unlockSeparate: + 'Inloggen geeft je je account: facturering, gehoste drives en je versleutelde back-up. Om je Atomic-identiteit op een nieuw apparaat te openen, heb je daarnaast je passkey of herstelcode nodig. Die kan Atomic niet lezen.', + }, + }, +}; + +export function AccountSignIn({ + googleHref, + onGoogle, + onPasskey, + passkeySupported = true, + email, + onEmailChange, + onSubmitEmail, + busy = false, + sending = false, + copy = ACCOUNT_SIGN_IN_COPY.en, + emailAutoComplete = 'username webauthn', + emailInputId = 'atomic-signin-email', + autoFocusEmail = false, + notice, + theme, + assistedRecovery = false, +}: { + /** Where the Google option goes; `null` when the account service has + * no Google client, which is the same answer on every screen. */ + googleHref: string | null; + /** Instead of `googleHref`, for a host that has to do something first + * (the desktop apps open Google in the system browser). */ + onGoogle?: () => void; + onPasskey: () => void; + passkeySupported?: boolean; + email: string; + onEmailChange: (email: string) => void; + onSubmitEmail: (event: FormEvent) => void; + /** Something is in flight: every option waits. */ + busy?: boolean; + /** The email link is on its way. */ + sending?: boolean; + copy?: AccountSignInCopy; + emailAutoComplete?: string; + emailInputId?: string; + autoFocusEmail?: boolean; + /** Errors and confirmations, under the options. */ + notice?: ReactNode; + /** The host's explicit theme; the system's when left out. */ + theme?: 'light' | 'dark'; + /** Signing in alone opens the identity; the info dialog says so. */ + assistedRecovery?: boolean; +}) { + const info = useRef(null); + + return ( +
+
+ + onEmailChange(e.target.value)} + autoComplete={emailAutoComplete} + autoFocus={autoFocusEmail} + required + data-test='email-sign-in' + /> + +
+ + {passkeySupported ? ( + + ) : ( +

{copy.passkeyUnavailable}

+ )} +
+ {googleHref ? ( + busy && e.preventDefault()} + data-test='google-sign-in' + > + + {copy.google} + + ) : onGoogle ? ( + + ) : null} +
+ {notice} + + { + // A press on the backdrop lands on the dialog itself. + if (e.target === e.currentTarget) e.currentTarget.close(); + }} + > +

{copy.info.title}

+
+ {copy.info.options.map(option => ( +
+
{option.name}
+
{option.text}
+
+ ))} +
+

{copy.info.unlockTitle}

+

+ {assistedRecovery + ? copy.info.unlockAssisted + : copy.info.unlockSeparate} +

+
+ +
+
+
+ ); +} + +// Google's "G", in its four brand colours, as their sign-in guidelines ask. +function GoogleMark() { + return ( + + ); +} + +// A key, in the text colour: the passkey sits beside Google as an equal. +function PasskeyMark() { + return ( + + ); +} diff --git a/browser/service-ui/src/index.tsx b/browser/service-ui/src/index.tsx index 87b3e7e2a0..2e953030f4 100644 --- a/browser/service-ui/src/index.tsx +++ b/browser/service-ui/src/index.tsx @@ -72,3 +72,9 @@ export function ServiceGroup({ }: HTMLAttributes) { return
; } + +export { + AccountSignIn, + ACCOUNT_SIGN_IN_COPY, + type AccountSignInCopy, +} from './AccountSignIn'; diff --git a/browser/service-ui/src/styles.css b/browser/service-ui/src/styles.css index 7fba47326f..a3c41ad342 100644 --- a/browser/service-ui/src/styles.css +++ b/browser/service-ui/src/styles.css @@ -62,3 +62,203 @@ opacity: 0.5; cursor: default; } + +/* AccountSignIn. Styled completely here, so the portal's global button and + input rules and the app's unstyled defaults end up looking the same. */ +.atomic-signin { + container: atomic-signin / inline-size; + display: grid; + gap: 12px; + text-align: left; +} +.atomic-signin-option, +.atomic-signin-submit, +.atomic-signin-email input { + box-sizing: border-box; + width: 100%; + margin: 0; + padding: 12px 16px; + border-radius: var(--service-radius, var(--radius, 8px)); + font: inherit; +} +.atomic-signin-option { + display: flex; + align-items: center; + justify-content: center; + gap: 10px; + border: 1px solid #747775; + background: #ffffff; + color: #1f1f1f; + font-weight: 600; + text-decoration: none; + box-shadow: none; + cursor: pointer; +} +.atomic-signin-option svg { + flex-shrink: 0; +} +.atomic-signin-option:hover { + background: #f2f2f2; +} +.atomic-signin-option:focus-visible, +.atomic-signin-submit:focus-visible { + outline: 2px solid var(--service-accent, var(--color-main, #204ce4)); + outline-offset: 2px; +} +.atomic-signin-option[aria-disabled='true'], +.atomic-signin-option:disabled, +.atomic-signin-submit:disabled { + opacity: 0.6; + pointer-events: none; +} +.atomic-signin-row { + display: flex; + flex-wrap: wrap; + gap: 8px; +} +.atomic-signin-row > * { + flex: 1 1 0; + min-width: 0; +} +.atomic-signin-row .atomic-signin-option { + padding-inline: 8px; + gap: 8px; +} +/* Three names side by side need about 330px; narrower, one per line. */ +@container atomic-signin (max-width: 330px) { + .atomic-signin-row { + flex-direction: column; + } +} +.atomic-signin-row:empty { + display: none; +} +.atomic-signin-or { + display: flex; + align-items: center; + gap: 12px; + margin: 0; + color: var(--service-muted, var(--color-text-light, #666)); + font-size: 14px; +} +.atomic-signin-or::before, +.atomic-signin-or::after { + content: ''; + flex: 1; + border-top: 1px solid + var(--service-border, var(--surface-border, rgba(0, 0, 0, 0.12))); +} +.atomic-signin-hint { + margin: 0; + color: var(--service-muted, var(--color-text-light, #666)); + font-size: 14px; +} +.atomic-signin-email { + display: grid; + gap: 8px; + margin: 0; +} +.atomic-signin-email label { + color: var(--service-muted, var(--color-text-light, #666)); + font-size: 13px; + font-weight: 700; +} +.atomic-signin-email input { + border: 1px solid var(--service-border, var(--color-bg-2, #ccc)); + background: var(--service-input-bg, var(--color-bg-1, #fff)); + color: var(--service-text, var(--color-text, #111)); +} +.atomic-signin-email input:focus { + outline: none; + border-color: var(--service-accent, var(--color-main, #204ce4)); +} +.atomic-signin-submit { + border: 1px solid transparent; + background: var(--service-accent, var(--color-main, #204ce4)); + color: var(--service-on-accent, #ffffff); + font-weight: 700; + cursor: pointer; +} +.atomic-signin-submit:hover { + filter: brightness(0.92); +} +/* Google's dark button, and the passkey's with it. An explicit host theme + overrides the system one, as on .atomic-product-background. */ +@media (prefers-color-scheme: dark) { + .atomic-signin:not([data-signin-theme='light']) .atomic-signin-option { + background: #131314; + border-color: #8e918f; + color: #e3e3e3; + } + .atomic-signin:not([data-signin-theme='light']) .atomic-signin-option:hover { + background: #1f1f20; + } +} +.atomic-signin[data-signin-theme='dark'] .atomic-signin-option { + background: #131314; + border-color: #8e918f; + color: #e3e3e3; +} +.atomic-signin[data-signin-theme='dark'] .atomic-signin-option:hover { + background: #1f1f20; +} + +.atomic-signin-info-open { + justify-self: center; + margin: 0; + padding: 4px; + border: 0; + background: none; + box-shadow: none; + color: var(--service-muted, var(--color-text-light, #666)); + font: inherit; + font-size: 14px; + font-weight: 400; + text-decoration: underline; + cursor: pointer; + transform: none; +} +.atomic-signin-info-open:hover { + background: none; + color: var(--service-text, var(--color-text, #111)); +} +.atomic-signin-info { + box-sizing: border-box; + width: min(34rem, calc(100vw - 32px)); + max-height: calc(100vh - 32px); + padding: 24px; + border: 1px solid var(--service-border, var(--surface-border, #ccc)); + border-radius: var(--service-radius, var(--radius, 8px)); + background: var(--service-surface, var(--color-bg, #fff)); + color: var(--service-text, var(--color-text, #111)); + text-align: left; + line-height: 1.5; +} +.atomic-signin-info::backdrop { + background: rgba(0, 0, 0, 0.45); +} +.atomic-signin .atomic-signin-info h2 { + margin: 0 0 16px; + font-size: 1.25em; +} +.atomic-signin .atomic-signin-info h3 { + margin: 20px 0 6px; + font-size: 1em; +} +.atomic-signin-info dl { + display: grid; + gap: 12px; + margin: 0; +} +.atomic-signin-info dt { + font-weight: 700; +} +.atomic-signin-info dd, +.atomic-signin-info p { + margin: 0; + color: var(--service-muted, var(--color-text-light, #555)); + font-size: 0.95em; +} +.atomic-signin-info form { + margin: 20px 0 0; +} diff --git a/planning/sync-onboarding-ux.md b/planning/sync-onboarding-ux.md index b41703226f..6b25bbf1fb 100644 --- a/planning/sync-onboarding-ux.md +++ b/planning/sync-onboarding-ux.md @@ -219,3 +219,12 @@ Rust inspection is available for a future matching confirmation step there. ### Account recovery after code sign-in The browser/Tauri Account recovery card offers recovery-code unlock independently of passkeys, including after a WebAuthn failure. A portal session plus the existing recovery code can add a passkey without replacing the code or older passkeys. Each passkey uses its own PRF salt. Flutter has no corresponding envelope-management card yet. + +### One set of account sign-in options + +Every screen that signs in to the account (the portal's sign-in page and its +homepage panel, the app's sign-in and restore steps) renders the same +`AccountSignIn` from `@tomic/service-ui`: Google, passkey, email link. The app +adds only what the portal cannot do, pasting an agent secret. Native builds that +cannot hold the account cookie link the device with a code instead. Flutter has +no account sign-in yet.