diff --git a/apps/mobile/app/qa/account-actions.tsx b/apps/mobile/app/qa/account-actions.tsx
new file mode 100644
index 0000000000..dad11f42a5
--- /dev/null
+++ b/apps/mobile/app/qa/account-actions.tsx
@@ -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 ;
+ return ;
+}
+
+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 (
+
+
+ {}}
+ />
+
+ {t.accountFixture.notice}
+
+
+ );
+}
diff --git a/apps/mobile/src/host/account-action-fixture.ts b/apps/mobile/src/host/account-action-fixture.ts
new file mode 100644
index 0000000000..435a5534d3
--- /dev/null
+++ b/apps/mobile/src/host/account-action-fixture.ts
@@ -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,
+ };
+}
diff --git a/apps/mobile/src/host/account-connections.ts b/apps/mobile/src/host/account-connections.ts
new file mode 100644
index 0000000000..eeeb325a30
--- /dev/null
+++ b/apps/mobile/src/host/account-connections.ts
@@ -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;
+ adopt(next: SavedHosts): void;
+ clearLocal(host: SavedHost): Promise;
+}): Promise {
+ 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);
+}
diff --git a/apps/mobile/src/host/account-owner.ts b/apps/mobile/src/host/account-owner.ts
new file mode 100644
index 0000000000..819291e3ae
--- /dev/null
+++ b/apps/mobile/src/host/account-owner.ts
@@ -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;
+ 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
+ );
+}
diff --git a/apps/mobile/src/host/connect-account.ts b/apps/mobile/src/host/connect-account.ts
index 64a0a69ecb..b014992633 100644
--- a/apps/mobile/src/host/connect-account.ts
+++ b/apps/mobile/src/host/connect-account.ts
@@ -1,3 +1,4 @@
+import type { AccountOwner } from './account-owner';
import { checkRoute, isConnectRoute } from './route';
import type { PairingPayload } from './pairing';
@@ -22,7 +23,12 @@ export type ConnectRefusal =
| 'sign-in-required'
| 'account-not-allowed'
| 'host-offline'
- | 'relay-unavailable';
+ | 'relay-unavailable'
+ | 'account-changed'
+ | 'account-identity-required'
+ | 'account-action-pending'
+ | 'account-cleanup-failed'
+ | 'account-deletion-uncertain';
export interface ConnectHost {
id: string;
@@ -37,6 +43,9 @@ interface Session {
clientId: string;
refreshToken: string;
email?: string;
+ subject?: string;
+ sessionId?: string;
+ action?: 'signOut' | 'delete-pending' | 'delete-complete' | 'delete-local';
}
class Refused extends Error {
@@ -58,6 +67,14 @@ function parseSession(text: string | null): Session | undefined {
return {
clientId: value['clientId'],
refreshToken: value['refreshToken'],
+ ...(typeof value['subject'] === 'string' ? { subject: value['subject'] } : {}),
+ ...(typeof value['sessionId'] === 'string' ? { sessionId: value['sessionId'] } : {}),
+ ...(value['action'] === 'signOut' ||
+ value['action'] === 'delete-pending' ||
+ value['action'] === 'delete-complete' ||
+ value['action'] === 'delete-local'
+ ? { action: value['action'] }
+ : {}),
...(typeof value['email'] === 'string' ? { email: value['email'] } : {}),
};
} catch {
@@ -69,10 +86,12 @@ export function createConnectAccount(options: {
runtime: ConnectRuntime;
redirectUri: string;
relay?: string;
+ removeConnections?: (owner: AccountOwner) => Promise;
}) {
const { runtime } = options;
const relay = (options.relay ?? CONNECT_RELAY).replace(/\/+$/u, '');
let queue: Promise = Promise.resolve();
+ let observedDeletion: string | undefined;
const serial = (work: () => Promise): Promise => {
const next = queue.then(work, work);
@@ -130,9 +149,38 @@ export function createConnectAccount(options: {
}
};
- const access = async (): Promise => {
+ const owner = (session: Session): AccountOwner | undefined =>
+ session.subject === undefined
+ ? undefined
+ : {
+ issuer: 'https://api.workos.com',
+ relay,
+ clientId: session.clientId,
+ subject: session.subject,
+ };
+ const key = async (session: Session) =>
+ session.sessionId ??
+ runtime.challenge(JSON.stringify([session.clientId, session.refreshToken]));
+ const current = async (expected: string): Promise => {
+ const session = parseSession(await runtime.read());
+ if (!session || (await key(session)) !== expected) throw new Refused('account-changed');
+ return session;
+ };
+ const finish = async (session: Session) => {
+ try {
+ const account = owner(session);
+ if (account) await options.removeConnections?.(account);
+ await save(undefined);
+ observedDeletion = undefined;
+ } catch {
+ throw new Refused('account-cleanup-failed');
+ }
+ };
+
+ const access = async (deleting = false): Promise => {
const session = parseSession(await runtime.read().catch(() => null));
if (session === undefined) throw new Refused('sign-in-required');
+ if (session.action && !deleting) throw new Refused('account-action-pending');
const reply = await call(
TOKEN_ENDPOINT,
form({
@@ -145,17 +193,54 @@ export function createConnectAccount(options: {
const rotated = reply.body['refresh_token'];
if (typeof token !== 'string') {
if (reply.status >= 400 && reply.status < 500) {
- await save(undefined);
+ if (!session.action) await save(undefined);
throw new Refused('sign-in-required');
}
throw new Refused('relay-unavailable');
}
- if (typeof rotated === 'string' && rotated !== session.refreshToken)
- await save({ ...session, refreshToken: rotated });
+ const subject = record(reply.body['user'])['id'];
+ if (session.subject && typeof subject === 'string' && subject !== session.subject)
+ throw new Refused('account-changed');
+ if (
+ (typeof rotated === 'string' && rotated !== session.refreshToken) ||
+ (!session.subject && typeof subject === 'string') ||
+ !session.sessionId
+ )
+ await save({
+ ...session,
+ sessionId: await key(session),
+ ...(typeof rotated === 'string' ? { refreshToken: rotated } : {}),
+ ...(typeof subject === 'string' ? { subject } : {}),
+ });
return token;
};
return {
+ async actionKey(): Promise {
+ const session = parseSession(await runtime.read());
+ return session ? key(session) : null;
+ },
+ async pendingDeletion(): Promise {
+ const action = parseSession(await runtime.read())?.action;
+ return (
+ action === 'delete-pending' || action === 'delete-complete' || action === 'delete-local'
+ );
+ },
+ finishLocalCleanup: (expected: string) =>
+ settle(async () => {
+ const session = await current(expected);
+ if (!session.action || session.action === 'signOut')
+ throw new Refused('account-action-pending');
+ await save({ ...session, action: 'delete-local' });
+ await finish(session);
+ }),
+ async savePairing(expected: string, savePairing: () => Promise): Promise {
+ return serial(async () => {
+ const session = await current(expected);
+ if (session.action) throw new Refused('account-action-pending');
+ await savePairing();
+ });
+ },
async email(): Promise {
const session = parseSession(await runtime.read().catch(() => null));
return session === undefined ? null : session.email;
@@ -163,6 +248,7 @@ export function createConnectAccount(options: {
signIn: () =>
settle(async () => {
+ if (parseSession(await runtime.read())?.action) throw new Refused('account-action-pending');
const config = await call(`${relay}/v1/config`);
const clientId = config.body['clientId'];
if (
@@ -210,7 +296,15 @@ export function createConnectAccount(options: {
if (reply.status !== 200 || typeof refreshToken !== 'string')
throw new Refused('sign-in-failed');
const email = record(reply.body['user'])['email'];
- await save({ clientId, refreshToken, ...(typeof email === 'string' ? { email } : {}) });
+ const subject = record(reply.body['user'])['id'];
+ if (typeof subject !== 'string' || !subject) throw new Refused('sign-in-failed');
+ await save({
+ clientId,
+ refreshToken,
+ subject,
+ sessionId: runtime.random(),
+ ...(typeof email === 'string' ? { email } : {}),
+ });
return typeof email === 'string' ? email : undefined;
}),
@@ -236,53 +330,118 @@ export function createConnectAccount(options: {
}),
offer: (hostId: string, deviceName: string) =>
- settle(async (): Promise => {
- const verifier = runtime.random();
- const verifierHash = await runtime.challenge(verifier);
- const body = await relayCall(
- `/v1/hosts/${encodeURIComponent(hostId)}/offer`,
- await access(),
- { verifierHash, name: deviceName.slice(0, 64) },
- );
- const host = record(body['host']);
- const encryption = record(body['encryption']);
- const enrollment = record(body['enrollment']);
- const route =
- typeof body['hostname'] === 'string'
- ? checkRoute(`https://${body['hostname']}`)
- : undefined;
- if (
- encryption['protocol'] !== 'connect-noise-xk-v1' ||
- typeof encryption['publicKey'] !== 'string' ||
- !/^[0-9a-f]{64}$/u.test(encryption['publicKey']) ||
- typeof enrollment['body'] !== 'string' ||
- typeof enrollment['signature'] !== 'string' ||
- typeof body['expiresAt'] !== 'string' ||
- route?.ok !== true ||
- !isConnectRoute(route.origin) ||
- new URL(route.origin).hostname !== body['hostname'] ||
- typeof host['id'] !== 'string' ||
- typeof host['name'] !== 'string'
- )
- throw new Refused('relay-unavailable');
- return {
- host: { id: host['id'], name: host['name'] },
- offer: '',
- encryption: { protocol: 'connect-noise-xk-v1', publicKey: encryption['publicKey'] },
- enrollment: { body: enrollment['body'], signature: enrollment['signature'] },
- routes: [route.origin],
- expiresAt: body['expiresAt'],
- verifier,
- };
- }),
+ settle(
+ async (): Promise => {
+ const token = await access();
+ const session = parseSession(await runtime.read());
+ const accountOwner = session && owner(session);
+ if (!session || !accountOwner) throw new Refused('account-identity-required');
+ const sessionKey = await key(session);
+ const verifier = runtime.random();
+ const verifierHash = await runtime.challenge(verifier);
+ const body = await relayCall(`/v1/hosts/${encodeURIComponent(hostId)}/offer`, token, {
+ verifierHash,
+ name: deviceName.slice(0, 64),
+ });
+ const host = record(body['host']);
+ const encryption = record(body['encryption']);
+ const enrollment = record(body['enrollment']);
+ const route =
+ typeof body['hostname'] === 'string'
+ ? checkRoute(`https://${body['hostname']}`)
+ : undefined;
+ if (
+ encryption['protocol'] !== 'connect-noise-xk-v1' ||
+ typeof encryption['publicKey'] !== 'string' ||
+ !/^[0-9a-f]{64}$/u.test(encryption['publicKey']) ||
+ typeof enrollment['body'] !== 'string' ||
+ typeof enrollment['signature'] !== 'string' ||
+ typeof body['expiresAt'] !== 'string' ||
+ route?.ok !== true ||
+ !isConnectRoute(route.origin) ||
+ new URL(route.origin).hostname !== body['hostname'] ||
+ typeof host['id'] !== 'string' ||
+ typeof host['name'] !== 'string'
+ )
+ throw new Refused('relay-unavailable');
+ return {
+ accountOwner,
+ sessionKey,
+ host: { id: host['id'], name: host['name'] },
+ offer: '',
+ encryption: { protocol: 'connect-noise-xk-v1', publicKey: encryption['publicKey'] },
+ enrollment: { body: enrollment['body'], signature: enrollment['signature'] },
+ routes: [route.origin],
+ expiresAt: body['expiresAt'],
+ verifier,
+ };
+ },
+ ),
- deleteAccount: () =>
+ deleteAccount: (expected: string) =>
settle(async () => {
- await relayCall('/v1/account', await access(), undefined, 'DELETE');
- await save(undefined);
+ let session = await current(expected);
+ if (session.action === 'signOut' || session.action === 'delete-local')
+ throw new Refused('account-action-pending');
+ if (observedDeletion === expected) {
+ session = { ...session, action: 'delete-complete' };
+ try {
+ await save(session);
+ } catch {
+ throw new Refused('account-cleanup-failed');
+ }
+ }
+ if (session.action !== 'delete-complete') {
+ let token: string;
+ try {
+ token = await access(true);
+ } catch (error) {
+ if (session.action === 'delete-pending')
+ throw new Refused('account-deletion-uncertain');
+ throw error;
+ }
+ session = parseSession(await runtime.read())!;
+ await save({ ...session, action: 'delete-pending' });
+ let reply: Awaited>;
+ try {
+ reply = await call(`${relay}/v1/account`, {
+ method: 'DELETE',
+ headers: { authorization: `Bearer ${token}` },
+ });
+ } catch {
+ throw new Refused('account-deletion-uncertain');
+ }
+ if (reply.status !== 200 || reply.body['deleted'] !== true) {
+ const rejected =
+ reply.status === 401 ||
+ reply.status === 403 ||
+ (reply.status === 503 &&
+ record(reply.body['error'])['code'] === 'account-deletion-unavailable');
+ if (rejected && session.action !== 'delete-pending') {
+ await save(session);
+ throw new Refused(reply.status === 401 ? 'sign-in-required' : 'relay-unavailable');
+ }
+ throw new Refused('account-deletion-uncertain');
+ }
+ observedDeletion = await key(session);
+ session = { ...session, action: 'delete-complete' };
+ try {
+ await save(session);
+ } catch {
+ throw new Refused('account-cleanup-failed');
+ }
+ }
+ await finish(session);
}),
- signOut: () => serial(() => save(undefined)),
+ signOut: (expected: string) =>
+ settle(async () => {
+ const session = await current(expected);
+ if (session.action && session.action !== 'signOut')
+ throw new Refused('account-action-pending');
+ await save({ ...session, action: 'signOut' });
+ await finish(session);
+ }),
};
}
diff --git a/apps/mobile/src/host/conversation-filter.ts b/apps/mobile/src/host/conversation-filter.ts
index 9cf6e0231d..56682eeb17 100644
--- a/apps/mobile/src/host/conversation-filter.ts
+++ b/apps/mobile/src/host/conversation-filter.ts
@@ -28,6 +28,17 @@ export function createConversationFilter(storage: {
} catch {}
publish();
},
+ async clearPersisted(expected: string) {
+ await ready;
+ const stored = await storage.read();
+ if (stored === expected || value === expected) {
+ const next = value === expected ? 'all' : value;
+ storage.write(next);
+ touched = true;
+ value = next;
+ publish();
+ }
+ },
subscribe(listener: () => void) {
listeners.add(listener);
return () => {
diff --git a/apps/mobile/src/host/host-session.ts b/apps/mobile/src/host/host-session.ts
index 546e4a54a1..1e74346169 100644
--- a/apps/mobile/src/host/host-session.ts
+++ b/apps/mobile/src/host/host-session.ts
@@ -1,3 +1,5 @@
+import type { AccountOwner } from './account-owner';
+import { removeAccountConnections } from './account-connections';
import { sourceDrafts } from './native-source-drafts';
import { useCallback, useMemo, useSyncExternalStore } from 'react';
import { useFocusEffect } from 'expo-router';
@@ -134,13 +136,13 @@ async function commit(next: SavedHosts, trigger: ConnectionTrigger = 'switch'):
adopt(next, trigger);
}
-void loadSavedHosts().then(
- (hosts) => {
- adopt(hosts);
- void pushSession.sync(hosts.hosts);
- },
- () => adopt({ hosts: [] }),
-);
+let hostsLoaded = false;
+const restoreHosts = (hosts: SavedHosts) => {
+ adopt(hosts);
+ hostsLoaded = true;
+ void pushSession.sync(hosts.hosts);
+};
+const hostsReady = loadSavedHosts().then(restoreHosts, () => adopt({ hosts: [] }));
AppState.addEventListener('change', (next) => {
mobileTelemetry.foreground(next === 'active', state.hosts.length);
@@ -153,6 +155,17 @@ AppState.addEventListener('change', (next) => {
if (state.client?.getSnapshot().connection.status === 'connected') void state.inbox?.refresh();
});
+let mutation: Promise = Promise.resolve();
+function serialize(work: () => Promise): Promise {
+ const next = mutation.then(async () => {
+ await hostsReady;
+ if (!hostsLoaded) restoreHosts(await loadSavedHosts());
+ return work();
+ });
+ mutation = next.catch(() => undefined);
+ return next;
+}
+
export const hostSession = {
subscribe(listener: () => void): () => void {
listeners.add(listener);
@@ -160,46 +173,77 @@ export const hostSession = {
},
getState: (): HostSessionState => state,
async pair(host: SavedHost): Promise {
- await commit(withHost(stored, host), 'pair');
- void pushSession.enable(stored.hosts);
+ return serialize(async () => {
+ await commit(withHost(stored, host), 'pair');
+ void pushSession.enable(stored.hosts);
+ });
},
async switchTo(hostId: string): Promise {
- if (stored.current === hostId) return true;
- const next = selectHost(stored, hostId);
- if (next === undefined) return false;
- await commit(next);
- return true;
+ return serialize(async () => {
+ if (stored.current === hostId) return true;
+ const next = selectHost(stored, hostId);
+ if (next === undefined) return false;
+ await commit(next);
+ return true;
+ });
+ },
+ async removeAccount(owner: AccountOwner): Promise {
+ return serialize(async () => {
+ await sourceDrafts.ready;
+ await removeAccountConnections({
+ owner,
+ state: stored,
+ persist: saveHosts,
+ adopt,
+ clearLocal: async (host) => {
+ await sourceDrafts.removePersistedWhere((key) => {
+ try {
+ const parts = JSON.parse(key);
+ return parts[0] === 'computer' && parts[1] === host.hostId;
+ } catch {
+ return false;
+ }
+ });
+ clearHostConversationCache(host.hostId);
+ await forgetRecentChats(host.hostId);
+ await conversationFilter.clearPersisted(computerEnvironmentKey(host.hostId));
+ await pushSession.forget(host).catch(() => undefined);
+ },
+ });
+ });
},
async unpair(
hostId?: string,
): Promise<{ current: boolean; revoked: Promise } | undefined> {
- const host =
- hostId === undefined ? state.saved : stored.hosts.find((entry) => entry.hostId === hostId);
- if (host === null || host === undefined) return undefined;
- const current = host.hostId === state.saved?.hostId;
- await sourceDrafts.ready;
- sourceDrafts.removeWhere((key) => {
+ return serialize(async () => {
+ const host =
+ hostId === undefined ? state.saved : stored.hosts.find((entry) => entry.hostId === hostId);
+ if (host === null || host === undefined) return undefined;
+ const current = host.hostId === state.saved?.hostId;
+ await sourceDrafts.ready;
+ sourceDrafts.removeWhere((key) => {
+ try {
+ const parts = JSON.parse(key);
+ return parts[0] === 'computer' && parts[1] === host.hostId;
+ } catch {
+ return false;
+ }
+ });
+ await commit(withoutHost(stored, host.hostId));
try {
- const parts = JSON.parse(key);
- return parts[0] === 'computer' && parts[1] === host.hostId;
- } catch {
- return false;
- }
- });
- await commit(withoutHost(stored, host.hostId));
- try {
- clearHostConversationCache(host.hostId);
- } catch {}
- void forgetRecentChats(host.hostId);
- void conversationFilter.ready.then(() => {
- if (conversationFilter.getSnapshot() === computerEnvironmentKey(host.hostId))
- conversationFilter.set('all');
+ clearHostConversationCache(host.hostId);
+ } catch {}
+ void forgetRecentChats(host.hostId).catch(() => undefined);
+ void conversationFilter.ready.then(() => {
+ if (conversationFilter.getSnapshot() === computerEnvironmentKey(host.hostId))
+ conversationFilter.set('all');
+ });
+ const revoked = pushSession
+ .forget(host)
+ .then(() => revokePairing({ host, carrier: nativeCarrier() }))
+ .then((result) => result === 'revoked');
+ return { current, revoked };
});
- const revoked = pushSession
- .forget(host)
- .then(() => revokePairing({ host, carrier: nativeCarrier() }))
- .then((result) => result === 'revoked');
- return { current, revoked };
},
};
diff --git a/apps/mobile/src/host/hosts.ts b/apps/mobile/src/host/hosts.ts
index f6d02cc3c4..cd52583999 100644
--- a/apps/mobile/src/host/hosts.ts
+++ b/apps/mobile/src/host/hosts.ts
@@ -1,3 +1,5 @@
+import { parseAccountOwner, type AccountOwner } from './account-owner';
+
export interface HostEncryption {
protocol: 'connect-noise-xk-v1';
hostKey: string;
@@ -5,6 +7,7 @@ export interface HostEncryption {
}
export interface SavedHost {
+ accountOwner?: AccountOwner;
encryption?: HostEncryption;
hostId: string;
hostName: string;
@@ -16,6 +19,7 @@ export interface SavedHost {
export interface SavedHosts {
hosts: SavedHost[];
current?: string;
+ pendingAccountRemoval?: SavedHost[];
}
function record(value: unknown): Record {
@@ -31,6 +35,9 @@ export function parseSavedHost(input: unknown): SavedHost | undefined {
typeof value['deviceId'] === 'string' &&
typeof value['credential'] === 'string'
? {
+ ...(parseAccountOwner(value['accountOwner']) === undefined
+ ? {}
+ : { accountOwner: parseAccountOwner(value['accountOwner'])! }),
...(parseEncryption(value['encryption']) === undefined
? {}
: { encryption: parseEncryption(value['encryption'])! }),
@@ -60,15 +67,26 @@ export function parseSavedHosts(
const hosts = Array.isArray(value['hosts'])
? value['hosts'].flatMap((entry) => parseSavedHost(entry) ?? [])
: [];
- if (hosts.length === 0) {
+ if (
+ hosts.length === 0 &&
+ !Array.isArray(value['hosts']) &&
+ !Array.isArray(value['pendingAccountRemoval'])
+ ) {
const legacy = parseSavedHost(parse(single));
return legacy === undefined ? { hosts: [] } : { hosts: [legacy], current: legacy.hostId };
}
const current =
typeof value['current'] === 'string' && hosts.some((host) => host.hostId === value['current'])
? value['current']
- : hosts[0]!.hostId;
- return { hosts, current };
+ : hosts[0]?.hostId;
+ const pendingAccountRemoval = Array.isArray(value['pendingAccountRemoval'])
+ ? value['pendingAccountRemoval'].flatMap((entry) => parseSavedHost(entry) ?? [])
+ : [];
+ return {
+ hosts,
+ ...(current === undefined ? {} : { current }),
+ ...(pendingAccountRemoval.length ? { pendingAccountRemoval } : {}),
+ };
}
export function currentHost(state: SavedHosts): SavedHost | undefined {
@@ -76,11 +94,14 @@ export function currentHost(state: SavedHosts): SavedHost | undefined {
}
export function withHost(state: SavedHosts, host: SavedHost): SavedHosts {
+ if (state.pendingAccountRemoval?.some((entry) => entry.hostId === host.hostId))
+ throw new Error('account-cleanup-pending');
const previous = state.hosts.find((entry) => entry.hostId === host.hostId);
if (previous?.encryption && previous.encryption.hostKey !== host.encryption?.hostKey)
throw new Error('host-key-mismatch');
return {
+ ...state,
hosts: [...state.hosts.filter((entry) => entry.hostId !== host.hostId), host],
current: host.hostId,
};
@@ -92,12 +113,13 @@ export function withoutHost(state: SavedHosts, hostId: string): SavedHosts {
state.current !== hostId && hosts.some((host) => host.hostId === state.current)
? state.current
: hosts[0]?.hostId;
- return current === undefined ? { hosts } : { hosts, current };
+ const { current: _previous, ...rest } = state;
+ return { ...rest, hosts, ...(current === undefined ? {} : { current }) };
}
export function selectHost(state: SavedHosts, hostId: string): SavedHosts | undefined {
return state.hosts.some((host) => host.hostId === hostId)
- ? { hosts: state.hosts, current: hostId }
+ ? { ...state, current: hostId }
: undefined;
}
diff --git a/apps/mobile/src/host/native-connect-account.ts b/apps/mobile/src/host/native-connect-account.ts
index 05700ab90c..650b93fc99 100644
--- a/apps/mobile/src/host/native-connect-account.ts
+++ b/apps/mobile/src/host/native-connect-account.ts
@@ -5,6 +5,7 @@ import * as WebBrowser from 'expo-web-browser';
import { fetch } from 'expo/fetch';
import { MOBILE_REDIRECT_URI } from '../cloud/instance-contract';
+import { hostSession } from './host-session';
import { createConnectAccount } from './connect-account';
const KEY = 'botharness.connect-account.v1';
@@ -12,6 +13,7 @@ const base64url = (value: string) =>
value.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
export const connectAccount = createConnectAccount({
+ removeConnections: (owner) => hostSession.removeAccount(owner),
redirectUri: Application.applicationId
? `${Application.applicationId}:/oauth2redirect`
: MOBILE_REDIRECT_URI,
diff --git a/apps/mobile/src/host/native-source-drafts.ts b/apps/mobile/src/host/native-source-drafts.ts
index 0647f3d04c..e70652c803 100644
--- a/apps/mobile/src/host/native-source-drafts.ts
+++ b/apps/mobile/src/host/native-source-drafts.ts
@@ -7,10 +7,12 @@ export const sourceDrafts = createSourceDrafts({
const f = file();
return f.exists ? JSON.parse(await f.text()) : {};
},
- write(value) {
+ write(value, required) {
try {
file().writeSync(JSON.stringify(value));
- } catch {}
+ } catch (error) {
+ if (required) throw error;
+ }
},
});
export function useSourceDraft(key: string) {
diff --git a/apps/mobile/src/host/saved-host.ts b/apps/mobile/src/host/saved-host.ts
index 6974dc7e99..1392d3aee8 100644
--- a/apps/mobile/src/host/saved-host.ts
+++ b/apps/mobile/src/host/saved-host.ts
@@ -18,10 +18,8 @@ export async function loadSavedHosts(): Promise {
}
export async function saveHosts(state: SavedHosts): Promise {
- if (state.hosts.length === 0) await SecureStore.deleteItemAsync(KEY);
- else
- await SecureStore.setItemAsync(KEY, JSON.stringify(state), {
- keychainAccessible: SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
- });
+ await SecureStore.setItemAsync(KEY, JSON.stringify(state), {
+ keychainAccessible: SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
+ });
await SecureStore.deleteItemAsync(SINGLE_KEY).catch(() => undefined);
}
diff --git a/apps/mobile/src/host/source-drafts.ts b/apps/mobile/src/host/source-drafts.ts
index 935bcae716..327345749e 100644
--- a/apps/mobile/src/host/source-drafts.ts
+++ b/apps/mobile/src/host/source-drafts.ts
@@ -1,6 +1,6 @@
export interface DraftStorage {
read(): Promise;
- write(value: Record): void;
+ write(value: Record, required?: boolean): void;
}
export function createSourceDrafts(storage: DraftStorage) {
let values: Record = {};
@@ -43,6 +43,21 @@ export function createSourceDrafts(storage: DraftStorage) {
publish();
}
},
+ async removePersistedWhere(match: (key: string) => boolean) {
+ await ready;
+ const raw = await storage.read();
+ const next: Record = {};
+ if (raw && typeof raw === 'object' && !Array.isArray(raw))
+ for (const [key, value] of Object.entries(raw))
+ if (!changed.has(key) && typeof value === 'string') next[key] = value;
+ Object.assign(next, values);
+ const removed = Object.keys(next).filter(match);
+ for (const key of removed) delete next[key];
+ storage.write(next, true);
+ values = next;
+ for (const key of removed) changed.add(key);
+ publish();
+ },
subscribe(listener: () => void) {
listeners.add(listener);
return () => {
diff --git a/apps/mobile/src/telemetry/schema.ts b/apps/mobile/src/telemetry/schema.ts
index f6c80d9157..ce23f495f8 100644
--- a/apps/mobile/src/telemetry/schema.ts
+++ b/apps/mobile/src/telemetry/schema.ts
@@ -23,6 +23,11 @@ export type PairingReason =
| 'account-not-allowed'
| 'host-offline'
| 'relay-unavailable'
+ | 'account-changed'
+ | 'account-identity-required'
+ | 'account-action-pending'
+ | 'account-cleanup-failed'
+ | 'account-deletion-uncertain'
| 'unknown';
export type DurationBucket = 'under1s' | '1-5s' | '5-15s' | '15-60s' | '60plus';
export type ActivationStep = 'host_ready' | 'message_accepted' | 'bot_message_observed';
@@ -136,6 +141,11 @@ const fields: Record b
'account-not-allowed',
'host-offline',
'relay-unavailable',
+ 'account-changed',
+ 'account-identity-required',
+ 'account-action-pending',
+ 'account-cleanup-failed',
+ 'account-deletion-uncertain',
'unknown',
),
duration_bucket: duration,
diff --git a/apps/mobile/src/ui/account-hosts.tsx b/apps/mobile/src/ui/account-hosts.tsx
index dc058303f4..ea0193f981 100644
--- a/apps/mobile/src/ui/account-hosts.tsx
+++ b/apps/mobile/src/ui/account-hosts.tsx
@@ -8,7 +8,17 @@ import { AccountPanel, type AccountPairResult } from './primitives/account-panel
import { t } from './strings';
export function AccountHosts(props: {
- account: Pick;
+ account: Pick<
+ ConnectAccount,
+ | 'email'
+ | 'signIn'
+ | 'hosts'
+ | 'signOut'
+ | 'deleteAccount'
+ | 'actionKey'
+ | 'pendingDeletion'
+ | 'finishLocalCleanup'
+ >;
busy: boolean;
saved: readonly SavedHost[];
results: Readonly>;
@@ -19,9 +29,13 @@ export function AccountHosts(props: {
const [hosts, setHosts] = useState();
const [loading, setLoading] = useState(false);
const [error, setError] = useState();
+ const [pendingDeletion, setPendingDeletion] = useState(false);
const [selected, setSelected] = useState([]);
const generation = useRef(0);
const working = useRef(false);
+ const actionKey = useRef(null);
+ const locked = useRef(false);
+ locked.current = props.busy || loading;
const load = async (ticket: number): Promise => {
setLoading(true);
@@ -43,6 +57,8 @@ export function AccountHosts(props: {
useFocusEffect(
useCallback(() => {
const ticket = ++generation.current;
+ actionKey.current = null;
+ setPendingDeletion(false);
setEmail(false);
setLoading(false);
setError(undefined);
@@ -51,9 +67,17 @@ export function AccountHosts(props: {
void account
.email()
.then(async (current) => {
+ if (ticket !== generation.current) return;
+ actionKey.current = await account.actionKey();
+ if (ticket !== generation.current) return;
+ setPendingDeletion(await account.pendingDeletion());
if (ticket !== generation.current) return;
setEmail(current);
if (current !== null) await load(ticket);
+ if (ticket === generation.current) {
+ const key = await account.actionKey();
+ if (ticket === generation.current) actionKey.current = key;
+ }
})
.catch(() => {
if (ticket === generation.current) {
@@ -68,30 +92,27 @@ export function AccountHosts(props: {
}, [account]),
);
- const run = async (action: 'signIn' | 'signOut' | 'deleteAccount' | 'refresh') => {
- if (working.current || props.busy || loading) return;
+ const run = async (
+ action: 'signIn' | 'signOut' | 'deleteAccount' | 'finishLocalCleanup' | 'refresh',
+ confirmedKey?: string,
+ ) => {
+ if (working.current || locked.current) return;
working.current = true;
const ticket = ++generation.current;
setLoading(true);
setError(undefined);
try {
if (action === 'refresh') await load(ticket);
- else if (action === 'signOut') {
- await account.signOut();
- if (ticket === generation.current) {
- setEmail(null);
- setHosts(undefined);
- setSelected([]);
- }
- } else {
- const result = await account[action]();
+ else {
+ const result =
+ action === 'signIn' ? await account.signIn() : await account[action](confirmedKey ?? '');
if (ticket !== generation.current) return;
if (!result.ok) {
setError(t.pairRefused[result.code]);
- return;
+ return t.pairRefused[result.code];
}
setSelected([]);
- if (action === 'deleteAccount') {
+ if (action === 'deleteAccount' || action === 'signOut' || action === 'finishLocalCleanup') {
setEmail(null);
setHosts(undefined);
} else {
@@ -101,11 +122,45 @@ export function AccountHosts(props: {
}
} catch {
if (ticket === generation.current) setError(t.pairRefused['relay-unavailable']);
+ return t.pairRefused['relay-unavailable'];
} finally {
+ try {
+ if (ticket === generation.current) {
+ const key = await account.actionKey();
+ const pending = await account.pendingDeletion();
+ if (ticket === generation.current) {
+ actionKey.current = key;
+ setPendingDeletion(pending);
+ }
+ }
+ } catch {
+ if (ticket === generation.current) actionKey.current = null;
+ }
working.current = false;
if (ticket === generation.current) setLoading(false);
}
};
+ const confirm = (action: 'signOut' | 'deleteAccount' | 'finishLocalCleanup') => {
+ if (working.current || locked.current || !actionKey.current) return;
+ let ticket = generation.current;
+ const confirmedKey = actionKey.current;
+ let used = false;
+ const copy =
+ action === 'finishLocalCleanup'
+ ? [t.pairAccount.cleanupTitle, t.pairAccount.cleanupMessage, t.pairAccount.cleanupConfirm]
+ : action === 'signOut'
+ ? [t.pairAccount.signOutTitle, t.pairAccount.signOutMessage, t.pairAccount.signOut]
+ : [t.pairAccount.deleteTitle, t.pairAccount.deleteMessage, t.pairAccount.deleteConfirm];
+ confirmDestructive(copy[0]!, copy[1]!, copy[2]!, async () => {
+ if (used || ticket !== generation.current || locked.current || working.current) return;
+ const failure = await run(action, confirmedKey);
+ if (failure) {
+ if (generation.current === ticket + 1) ticket = generation.current;
+ throw new Error(failure);
+ }
+ used = true;
+ });
+ };
const added = (host: ConnectHost) =>
accountHostAdded(host, props.saved) ||
props.results[host.id] === 'already-paired' ||
@@ -115,6 +170,7 @@ export function AccountHosts(props: {
return (
void run('refresh')}
onSignIn={() => void run('signIn')}
- onSignOut={() => void run('signOut')}
- onDelete={() =>
- confirmDestructive(
- t.pairAccount.deleteTitle,
- t.pairAccount.deleteMessage,
- t.pairAccount.deleteConfirm,
- () => run('deleteAccount'),
- )
- }
+ onSignOut={() => confirm(pendingDeletion ? 'finishLocalCleanup' : 'signOut')}
+ onDelete={() => confirm('deleteAccount')}
/>
);
}
diff --git a/apps/mobile/src/ui/primitives/account-panel.ios.tsx b/apps/mobile/src/ui/primitives/account-panel.ios.tsx
index d97ae34f79..f899c7ed97 100644
--- a/apps/mobile/src/ui/primitives/account-panel.ios.tsx
+++ b/apps/mobile/src/ui/primitives/account-panel.ios.tsx
@@ -37,7 +37,7 @@ export function AccountPanel(props: AccountPanelProps) {
) : props.email !== false ? (
<>