Skip to content
Open
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
1 change: 1 addition & 0 deletions browser/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ This changelog covers all five packages, as they are (for now) updated as a whol

## UNRELEASED

- Fix: a guest's work (started with Get started, no account) comes along when they sign up for an account afterwards. The account's new identity replaced the guest without handing its drives over, so the Welcome drive and everything in it disappeared after sign-up.
- Internal: one `isPlainObject` in @tomic/lib replaces 5 local type guards.
- Internal: one `isLoopbackHost` in @tomic/lib replaces 12 inline localhost checks.
- Removed the dead mobile-Tauri frontend code: Android back-button handling, the native QR scanner ("Scan a QR code" button) and the `@tauri-apps/plugin-barcode-scanner` dependency. The mobile app is the Flutter app; Tauri is desktop only. Pairing codes are still pasted or typed.
Expand Down
173 changes: 173 additions & 0 deletions browser/data-browser/src/components/NewIdentitySection.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
// @vitest-environment jsdom
// @wc-ignore-file
import React from 'react';
import { act, cleanup, fireEvent, render } from '@testing-library/react';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';

const m = vi.hoisted(() => ({
order: [] as string[],
prepare: vi.fn(),
applyBrought: vi.fn(),
guest: { subject: 'did:ad:agent:guest', privateDrive: 'did:ad:guesthome' },
current: undefined as { subject: string } | undefined,
}));

const store = {
getAgent: () => m.current,
setAgent: (agent: { subject: string } | undefined) => {
m.order.push(`setAgent:${agent?.subject}`);
m.current = agent;
},
getServerUrl: () => 'https://app.example',
registerLocalOnlyDrive: vi.fn(),
uploadFiles: vi.fn(),
createDrive: vi.fn(async () => ({ subject: 'did:ad:newdrive' })),
};

vi.mock('@tomic/react', () => {
class Agent {
constructor(
public provider: unknown,
public subject: string,
) {}
static generateKeyPair = async () => ({
privateKey: 'priv',
publicKey: 'pub',
});
static buildSecret = () => 'secret';
static fromSecret = async () => new Agent({}, 'did:ad:agent:new');
privateDriveSubject = async () => 'did:ad:newhome';
}

return {
Agent,
JSCryptoProvider: class {
constructor(public key: string) {}
getPublicKey = async () => 'pub';
},
agentSubject: () => 'did:ad:agent:new',
dataBrowser: { properties: { icon: 'icon' } },
useStore: () => store,
};
});
vi.mock('../helpers/AppSettings', () => ({
useSettings: () => ({ setAgent: vi.fn(), setDrive: vi.fn() }),
}));
vi.mock('../hooks/useNavigateWithTransition', () => ({
useNavigateWithTransition: () => vi.fn(),
}));
vi.mock('../helpers/managed/cloudSync', () => ({
getManagedPortalUrl: () => undefined,
}));
vi.mock('../helpers/originNode', () => ({ isOriginWithoutNode: () => false }));
vi.mock('../helpers/tauri', () => ({ isRunningInTauri: () => false }));
vi.mock('../helpers/privateDrive', () => ({
fetchPrivateDriveSubject: vi.fn(),
}));
vi.mock('../helpers/agentStorage', () => ({ saveAgentToIDB: vi.fn() }));
vi.mock('../helpers/startLocalIdentity', () => ({
saveAgentResource: vi.fn(async () => ({ set: vi.fn(), save: vi.fn() })),
}));
vi.mock('../helpers/driveData', () => ({ reopenRestoredDrive: vi.fn() }));
vi.mock('../helpers/navigation', () => ({
constructOpenURL: (s: string) => s,
}));
vi.mock('../helpers/managed', () => ({ PRODUCT_NAME: 'Atomic' }));
vi.mock('../helpers/managed/recovery', () => ({
isPasskeySupported: async () => false,
PrfUnsupportedError: class extends Error {},
}));
vi.mock('../helpers/bringAlong', () => ({
prepareIdentitySwitch: m.prepare,
applyBroughtAlong: m.applyBrought,
}));
vi.mock('./ProfileForm', () => ({
ProfileForm: ({ onSave }: { onSave: (v: { name: string }) => void }) => (
<button data-testid='save-profile' onClick={() => onSave({ name: 'Ann' })}>
save
</button>
),
}));
vi.mock('./Button', () => ({ Button: (p: object) => <button {...p} /> }));
vi.mock('./Row', () => ({
Column: ({ children }: { children: React.ReactNode }) => (
<div>{children}</div>
),
Row: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}));
vi.mock('./CodeBlock', () => ({ CodeBlock: () => <div /> }));
vi.mock('./SecretCodeBlock', () => ({ SecretCodeBlock: () => <div /> }));
vi.mock('./forms/InputStyles', () => ({
InputStyled: 'input',
InputWrapper: 'div',
}));
vi.mock('./forms/Field', () => ({ default: () => <div /> }));
vi.mock('react-hot-toast', () => ({ default: { error: vi.fn() } }));

import { NewIdentitySection } from './NewIdentitySection';

beforeEach(() => {
vi.clearAllMocks();
m.order.length = 0;
m.current = m.guest;
m.prepare.mockImplementation(async () => {
m.order.push('prepare');

return 'brought';
});
m.applyBrought.mockResolvedValue(true);
});
afterEach(cleanup);

async function createAccount() {
const view = render(
<NewIdentitySection
autoStart
onDone={vi.fn()}
stepIndicatorPortal={null}
defaultProfileName='ann'
/>,
);
await act(async () => {});
await act(async () => {
fireEvent.click(view.getByTestId('save-profile'));
});
await act(async () => {});
}

it('hands the guest identity its drives over before the new agent replaces it', async () => {
await createAccount();

expect(m.prepare).toHaveBeenCalledTimes(1);
expect(m.prepare.mock.calls[0][1]).toBe('did:ad:agent:new');
// The guest must still be the active agent while it grants the new one.
expect(m.order.indexOf('prepare')).toBeLessThan(
m.order.indexOf('setAgent:did:ad:agent:new'),
);
});

it('lists the brought drives in the new home once it exists', async () => {
await createAccount();

expect(m.applyBrought).toHaveBeenCalledWith(
store,
'did:ad:agent:new',
'did:ad:newdrive',
);
});

it('does not apply anything when nothing was brought', async () => {
m.prepare.mockResolvedValue('left');
await createAccount();

expect(m.applyBrought).not.toHaveBeenCalled();
});

it('still creates the account when handing the guest work over fails', async () => {
m.prepare.mockRejectedValue(new Error('grant refused'));
await createAccount();

expect(m.order).toContain('setAgent:did:ad:agent:new');
expect(store.createDrive).toHaveBeenCalled();
expect(m.applyBrought).not.toHaveBeenCalled();
});
38 changes: 38 additions & 0 deletions browser/data-browser/src/components/NewIdentitySection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ import { isOriginWithoutNode } from '../helpers/originNode';
import { isRunningInTauri } from '../helpers/tauri';
import { useSettings } from '../helpers/AppSettings';
import { saveAgentToIDB } from '../helpers/agentStorage';
import {
applyBroughtAlong,
prepareIdentitySwitch,
} from '../helpers/bringAlong';
import { saveAgentResource } from '../helpers/startLocalIdentity';
import { reopenRestoredDrive } from '../helpers/driveData';
import { useNavigateWithTransition } from '../hooks/useNavigateWithTransition';
Expand Down Expand Up @@ -126,6 +130,8 @@ export function NewIdentitySection({
const [error, setError] = useState<string | undefined>();
const [identity, setIdentity] = useState<IdentityData | null>(null);
const creatingIdentity = useRef(false);
/** The identity this browser held (a guest) handed its drives to the new one. */
const broughtAlong = useRef(false);
/** True after the user copies the secret or saves the backup file. */
const [secretBackedUp, setSecretBackedUp] = useState(false);
/** Set once a backup resolves; shown once, then never again. */
Expand Down Expand Up @@ -164,6 +170,23 @@ export function NewIdentitySection({

const newAgent = new Agent(agentProvider, agentDID);

// A guest (Get started, no account) has no account of its own: its work
// comes along to the identity made here, before that one replaces it
// (the old key must still sign the grants). Same rule as signing in with
// a secret (`prepareIdentitySwitch`); an identity that is not a guest is
// only archived here, never handed over unasked.
// Never in the way of making the account: the guest's key is archived
// before anything is handed over, so a failed hand-over loses nothing
// and the reconcile gate can still bring the work along later.
try {
broughtAlong.current =
(await prepareIdentitySwitch(store, agentDID, async () => false)) ===
'brought';
} catch (e) {
broughtAlong.current = false;
console.warn('Bringing the guest work along failed', e);
}

store.setAgent(newAgent);

// With no node behind the app's origin (the hosted build on the free
Expand Down Expand Up @@ -288,6 +311,21 @@ export function NewIdentitySection({

setDrive(resource.subject);

if (broughtAlong.current) {
// Lists the guest's drives in the new home and imports its local-only
// ones. Never blocks onboarding: until it succeeds the record stays
// and the reconcile gate retries it.
try {
await applyBroughtAlong(
store,
identity.agentSubject,
resource.subject,
);
} catch (e) {
console.warn('Bringing the guest work along failed, will retry', e);
}
}

if (onAfterCreate) {
await onAfterCreate(resource.subject);
}
Expand Down
2 changes: 2 additions & 0 deletions planning/identity-bring-along.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ Not: agent, identity, drive rights, merge, it, here.
| Site first, app used before signing in | App settings: "Sign in" | B signs in, A's work comes along, result line |
| App first, then the site | Site: "Sign in with secret" (copied from the app) or hand-back | Plain sign-in; if the browser had a guest with work, the question |
| Two apps used apart | App 2 settings: "Sign in", with the secret or a code from app 1 | Same as row 2 |
| Guest first, then sign up on the portal | Web: Get started, edit, then portal sign-up by email; back at `/app/welcome?from_portal=true` | The new account is made in `NewIdentitySection`; the guest's drives are handed to it (`prepareIdentitySwitch`, no question) before it replaces the guest, and listed in the new home. The reconcile gate skips `/app/welcome`, so it never saw this switch |
| Signed in as B, sign in as B again | Nothing to do | No step |

The app needs a "Sign in" entry while signed in (today the login screen is
Expand All @@ -85,4 +86,5 @@ Sign out, and opens the same sign-in options as the login screen.
- [x] Bridge, `node.identity`, fake, Dart tests
- [x] App: sign in while signed in, result line, widget tests
- [x] Web: archive + question on secret sign-in, vitest, e2e (`bring-along.spec.ts`)
- [x] Web: guest's work comes along when the portal sign-up creates a new account (`NewIdentitySection.test.tsx`; a new identity is minted, the guest's agent is not adopted, because the account's key is its own secret/backup and the guest key stays archived on the device)
- [ ] Screenshots of every screen, app and web
Loading