Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions browser/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
92 changes: 86 additions & 6 deletions browser/data-browser/src/components/AccountRecoveryCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -100,23 +107,29 @@ export function AccountRecoveryCard({
const [hasSession, setHasSession] = useState<boolean | null>(null);
const [accountEmail, setAccountEmail] = useState<string | null>(null);
const [portalUrl, setPortalUrl] = useState<string | null>(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.
//
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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 (
<Column gap='0.75rem'>
{error && <ErrorLook role='alert'>{error}</ErrorLook>}
Expand All @@ -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' : ''}.`}
</Protections>

{assistedOffered &&
!deviceOnly &&
(hasPasskey || hasCode || hasAccount) ? (
<Column gap='0.25rem'>
<CheckboxLabel>
<Checkbox
checked={assistedOn}
onChange={enabled => void handleAssistedChange(enabled)}
disabled={loading || (assistedOn && !hasPasskey && !hasCode)}
data-test='assisted-recovery-switch'
/>
Let {PRODUCT_NAME} help me recover
</CheckboxLabel>
<Hint>
{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}
</Hint>
</Column>
) : 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
Expand Down
5 changes: 3 additions & 2 deletions browser/data-browser/src/components/AgentProfileHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)}
<FaArrowUpRightFromSquare aria-hidden />
</AccountLink>
) : null}
Expand Down
33 changes: 27 additions & 6 deletions browser/data-browser/src/components/NewIdentitySection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>;
/** 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<boolean>;
}

interface IdentityData {
Expand Down Expand Up @@ -105,6 +110,7 @@ export function NewIdentitySection({
offerRecoveryBackup = false,
onBackupWithPasskey,
onBackupWithCode,
onBackupWithAccount,
}: NewIdentitySectionProps) {
const store = useStore();
const { setAgent, setDrive } = useSettings();
Expand Down Expand Up @@ -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'
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -474,7 +495,7 @@ export function NewIdentitySection({
setUseCodeFallback(true);
}}
onGenerate={handleGenerateRecoveryCode}
onContinue={finishWithoutSecretStep}
onContinue={() => finishWithoutSecretStep()}
onSkip={() => {
setError(undefined);
setStep('secret');
Expand Down
10 changes: 8 additions & 2 deletions browser/data-browser/src/components/Share/ShareDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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. */
});
Expand Down
51 changes: 51 additions & 0 deletions browser/data-browser/src/helpers/managed/accountPasskey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean> {
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;
}
Loading
Loading