Skip to content
Merged
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
62 changes: 62 additions & 0 deletions apps/mobile/app/qa/account-actions.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import * as Application from 'expo-application';
import { Redirect, Stack, useLocalSearchParams } from 'expo-router';
import { useMemo, useState, useSyncExternalStore } from 'react';
import { ScrollView, View } from 'react-native';
import {
createAccountActionFixture,
type AccountFixtureScenario,
} from '../../src/host/account-action-fixture';
import { AccountHosts } from '../../src/ui/account-hosts';
import { Button } from '../../src/ui/primitives/button';
import { Text } from '../../src/ui/primitives/text';
import { space } from '../../src/ui/design/tokens';
import { t } from '../../src/ui/strings';

export default function AccountActionsFixtureRoute() {
if (!__DEV__ || !Application.applicationId?.endsWith('.dev')) return <Redirect href="/" />;
return <AccountActionsFixture />;
}

function AccountActionsFixture() {
const params = useLocalSearchParams<{ scenario?: string }>();
const scenarios: AccountFixtureScenario[] = [
'success',
'delete-partial',
'local-write',
'session-write',
'expired-retry',
'completion-write',
];
const scenario = scenarios.find((value) => value === params.scenario) ?? 'success';
const [reset, setReset] = useState(0);
const fixture = useMemo(() => createAccountActionFixture(scenario), [scenario, reset]);
const snapshot = useSyncExternalStore(
fixture.subscribe,
fixture.getSnapshot,
fixture.getSnapshot,
);
return (
<View style={{ flex: 1 }}>
<Stack.Screen options={{ title: t.accountFixture.title }} />
<AccountHosts
key={scenario}
account={fixture.account}
busy={false}
saved={fixture.saved()}
results={{}}
onPair={async () => {}}
/>
<ScrollView style={{ flex: 1 }} contentContainerStyle={{ padding: space.x4 }}>
<Text>{t.accountFixture.notice}</Text>
<Button
testID="account-fixture-reset"
label={t.accountFixture.reset}
onPress={() => setReset((value) => value + 1)}
/>
<Text testID="account-fixture-result" selectable>
{snapshot}
</Text>
</ScrollView>
</View>
);
}
162 changes: 162 additions & 0 deletions apps/mobile/src/host/account-action-fixture.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
import { createConnectAccount } from './connect-account';
import { removeAccountConnections } from './account-connections';
import type { AccountOwner } from './account-owner';
import { parseSavedHosts, type SavedHost, type SavedHosts } from './hosts';

export type AccountFixtureScenario =
| 'success'
| 'delete-partial'
| 'local-write'
| 'session-write'
| 'expired-retry'
| 'completion-write';

const response = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });

export function createAccountActionFixture(scenario: AccountFixtureScenario = 'success') {
const owner: AccountOwner = {
issuer: 'https://api.workos.com',
relay: 'https://fixture.invalid',
clientId: 'client_fixture',
subject: 'user_fixture',
};
const host = (hostId: string, accountOwner?: AccountOwner): SavedHost => ({
hostId,
hostName: hostId,
routes: [`https://${hostId}.fixture.invalid`],
deviceId: 'fixture-device',
credential: 'fixture-only',
...(accountOwner ? { accountOwner } : {}),
});
let state: SavedHosts = {
hosts: [
host('owned', owner),
host('manual'),
host('legacy'),
host('other', { ...owner, subject: 'user_other' }),
],
current: 'owned',
};
let persisted = JSON.stringify(state);
let session: string | null = JSON.stringify({
clientId: owner.clientId,
subject: owner.subject,
sessionId: 'fixture-session',
refreshToken: 'fixture-refresh',
email: 'fixture@example.invalid',
});
let failed = false;
let remoteDeleted = false;
let sequence = 0;
const counters = {
accountWrites: 0,
pairingWrites: 0,
deletes: 0,
refreshes: 0,
disconnects: 0,
cleared: [] as string[],
};
const listeners = new Set<() => void>();
let snapshot = '';
const publish = () => {
snapshot = JSON.stringify({
...counters,
signedIn: session !== null,
saved: state.hosts.map((host) => host.hostId),
current: state.current ?? null,
pending: state.pendingAccountRemoval?.map((host) => host.hostId) ?? [],
remoteDeleted,
});
for (const listener of listeners) listener();
};
const account = createConnectAccount({
relay: owner.relay,
redirectUri: 'fixture:/callback',
runtime: {
read: async () => session,
write: async (value) => {
counters.accountWrites++;
if (
scenario === 'completion-write' &&
value &&
JSON.parse(value).action === 'delete-complete' &&
!failed
) {
failed = true;
publish();
throw new Error('fixture completion write');
}
if (scenario === 'session-write' && value === null && !failed) {
failed = true;
publish();
throw new Error('fixture write');
}
session = value;
publish();
},
random: () => `fixture-${++sequence}`,
challenge: async (value) => value,
authorize: async () => null,
now: () => 0,
request: async (url, init) => {
if (url === 'https://api.workos.com/user_management/authenticate') {
counters.refreshes++;
publish();
if ((scenario === 'expired-retry' || scenario === 'completion-write') && failed)
return response({}, 400);
return response({ access_token: 'fixture-access', user: { id: owner.subject } });
}
if (url === `${owner.relay}/v1/hosts`) return response({ hosts: [] });
if (url === `${owner.relay}/v1/account` && init?.method === 'DELETE') {
counters.deletes++;
remoteDeleted = true;
if ((scenario === 'delete-partial' || scenario === 'expired-retry') && !failed) {
failed = true;
publish();
return response({}, 502);
}
publish();
return response({ deleted: true });
}
throw new Error('fixture rejects every other request');
},
},
removeConnections: (accountOwner) =>
removeAccountConnections({
owner: accountOwner,
state: parseSavedHosts(persisted),
persist: async (next) => {
counters.pairingWrites++;
if (scenario === 'local-write' && !failed) {
failed = true;
publish();
throw new Error('fixture pairing write');
}
persisted = JSON.stringify(next);
publish();
},
adopt: (next) => {
if (state.current === 'owned' && next.current !== 'owned') counters.disconnects++;
state = next;
publish();
},
clearLocal: async (host) => {
counters.cleared.push(host.hostId);
publish();
},
}),
});
publish();
return {
account,
subscribe: (listener: () => void) => {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
getSnapshot: () => snapshot,
saved: () => state.hosts,
};
}
29 changes: 29 additions & 0 deletions apps/mobile/src/host/account-connections.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { sameAccount, type AccountOwner } from './account-owner';
import { withoutHost, type SavedHost, type SavedHosts } from './hosts';

export async function removeAccountConnections(options: {
owner: AccountOwner;
state: SavedHosts;
persist(next: SavedHosts): Promise<void>;
adopt(next: SavedHosts): void;
clearLocal(host: SavedHost): Promise<void>;
}): Promise<void> {
const removed = options.state.hosts.filter((host) =>
sameAccount(host.accountOwner, options.owner),
);
const pending = [...(options.state.pendingAccountRemoval ?? []), ...removed];
const owned = pending.filter((host) => sameAccount(host.accountOwner, options.owner));
if (!owned.length) return;
const next = {
...removed.reduce((state, host) => withoutHost(state, host.hostId), options.state),
pendingAccountRemoval: pending,
};
await options.persist(next);
options.adopt(next);
for (const host of owned) await options.clearLocal(host);
const { pendingAccountRemoval: _pending, ...rest } = next;
const remaining = pending.filter((host) => !sameAccount(host.accountOwner, options.owner));
const complete = { ...rest, ...(remaining.length ? { pendingAccountRemoval: remaining } : {}) };
await options.persist(complete);
options.adopt(complete);
}
34 changes: 34 additions & 0 deletions apps/mobile/src/host/account-owner.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
export interface AccountOwner {
issuer: 'https://api.workos.com';
relay: string;
clientId: string;
subject: string;
}

export function parseAccountOwner(input: unknown): AccountOwner | undefined {
if (typeof input !== 'object' || input === null) return undefined;
const value = input as Record<string, unknown>;
if (
value['issuer'] !== 'https://api.workos.com' ||
typeof value['relay'] !== 'string' ||
typeof value['clientId'] !== 'string' ||
typeof value['subject'] !== 'string' ||
!value['subject']
)
return undefined;
return {
issuer: value['issuer'],
relay: value['relay'],
clientId: value['clientId'],
subject: value['subject'],
};
}

export function sameAccount(a: AccountOwner | undefined, b: AccountOwner): boolean {
return (
a?.issuer === b.issuer &&
a.relay === b.relay &&
a.clientId === b.clientId &&
a.subject === b.subject
);
}
Loading
Loading