Compare commits

..
4 Commits
13 changed files with 682 additions and 75 deletions
+1 -1
View File
@@ -1 +1 @@
0.1.34
0.1.36
+1
View File
@@ -20,6 +20,7 @@ module.exports = {
expo: {
name: 'Bulwark Mobile',
slug: 'bulwark-mobile',
scheme: 'bulwarkmobile',
version: VERSION,
orientation: 'portrait',
icon: './assets/icon.png',
+68 -2
View File
@@ -1,12 +1,12 @@
{
"name": "bulwark-mobile",
"version": "0.1.34",
"version": "0.1.36",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "bulwark-mobile",
"version": "0.1.34",
"version": "0.1.36",
"license": "AGPL-3.0-only",
"dependencies": {
"@react-native-async-storage/async-storage": "2.2.0",
@@ -17,6 +17,8 @@
"@react-navigation/native-stack": "^7.14.10",
"date-fns": "^4.1.0",
"expo": "~54.0.33",
"expo-auth-session": "~7.0.8",
"expo-crypto": "~15.0.7",
"expo-document-picker": "~14.0.8",
"expo-file-system": "~19.0.21",
"expo-image-picker": "~17.0.10",
@@ -25,6 +27,7 @@
"expo-secure-store": "~15.0.8",
"expo-sharing": "~14.0.8",
"expo-status-bar": "~3.0.9",
"expo-web-browser": "~15.0.8",
"lucide-react-native": "^1.7.0",
"react": "19.1.0",
"react-native": "0.81.5",
@@ -5203,6 +5206,33 @@
}
}
},
"node_modules/expo-auth-session": {
"version": "7.0.11",
"resolved": "https://registry.npmjs.org/expo-auth-session/-/expo-auth-session-7.0.11.tgz",
"integrity": "sha512-AhWtt/m9rb1Po77X/VBFbeE6UTgbm2vXP2iCblUSRsHCw2qD6lO0ulKUB8Xyxy9FtoI9yrNQ1iwCNgIIgo8VYQ==",
"license": "MIT",
"dependencies": {
"expo-application": "~7.0.8",
"expo-constants": "~18.0.13",
"expo-crypto": "~15.0.9",
"expo-linking": "~8.0.12",
"expo-web-browser": "~15.0.11",
"invariant": "^2.2.4"
},
"peerDependencies": {
"react": "*",
"react-native": "*"
}
},
"node_modules/expo-auth-session/node_modules/expo-application": {
"version": "7.0.8",
"resolved": "https://registry.npmjs.org/expo-application/-/expo-application-7.0.8.tgz",
"integrity": "sha512-qFGyxk7VJbrNOQWBbE09XUuGuvkOgFS9QfToaK2FdagM2aQ+x3CvGV2DuVgl/l4ZxPgIf3b/MNh9xHpwSwn74Q==",
"license": "MIT",
"peerDependencies": {
"expo": "*"
}
},
"node_modules/expo-constants": {
"version": "18.0.13",
"resolved": "https://registry.npmjs.org/expo-constants/-/expo-constants-18.0.13.tgz",
@@ -5217,6 +5247,18 @@
"react-native": "*"
}
},
"node_modules/expo-crypto": {
"version": "15.0.9",
"resolved": "https://registry.npmjs.org/expo-crypto/-/expo-crypto-15.0.9.tgz",
"integrity": "sha512-SNWKa2fXx7v9gkp1h/7nqXY5XN7qgNDn3yRc2aO0gWGbeMbvob/haMxxsPFe9f51aqH5NjNCqHf2kvLhvAd8KQ==",
"license": "MIT",
"dependencies": {
"base64-js": "^1.3.0"
},
"peerDependencies": {
"expo": "*"
}
},
"node_modules/expo-document-picker": {
"version": "14.0.8",
"resolved": "https://registry.npmjs.org/expo-document-picker/-/expo-document-picker-14.0.8.tgz",
@@ -5266,6 +5308,20 @@
"expo": "*"
}
},
"node_modules/expo-linking": {
"version": "8.0.12",
"resolved": "https://registry.npmjs.org/expo-linking/-/expo-linking-8.0.12.tgz",
"integrity": "sha512-FpXeIpFgZuxihwT9lBo86YD3y6LphBuAhN680MMxm/Y7fmsc57vimn2d3vFu68VI0+Z9w457t494mu2wvlgWTQ==",
"license": "MIT",
"dependencies": {
"expo-constants": "~18.0.13",
"invariant": "^2.2.4"
},
"peerDependencies": {
"react": "*",
"react-native": "*"
}
},
"node_modules/expo-localization": {
"version": "17.0.8",
"resolved": "https://registry.npmjs.org/expo-localization/-/expo-localization-17.0.8.tgz",
@@ -5418,6 +5474,16 @@
"react-native": "*"
}
},
"node_modules/expo-web-browser": {
"version": "15.0.11",
"resolved": "https://registry.npmjs.org/expo-web-browser/-/expo-web-browser-15.0.11.tgz",
"integrity": "sha512-r2LS4Ro6DgUPZkcaEfgt8mp9eJuoA93x11Jh7S6utFe0FEzvUNn2yFhxg8XVwESaaHGt2k5V8LuK36rsp0BeIw==",
"license": "MIT",
"peerDependencies": {
"expo": "*",
"react-native": "*"
}
},
"node_modules/expo/node_modules/@babel/code-frame": {
"version": "7.29.0",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz",
+4 -1
View File
@@ -1,6 +1,6 @@
{
"name": "bulwark-mobile",
"version": "0.1.34",
"version": "0.1.36",
"license": "AGPL-3.0-only",
"main": "index.ts",
"scripts": {
@@ -23,6 +23,8 @@
"@react-navigation/native-stack": "^7.14.10",
"date-fns": "^4.1.0",
"expo": "~54.0.33",
"expo-auth-session": "~7.0.8",
"expo-crypto": "~15.0.7",
"expo-document-picker": "~14.0.8",
"expo-file-system": "~19.0.21",
"expo-image-picker": "~17.0.10",
@@ -31,6 +33,7 @@
"expo-secure-store": "~15.0.8",
"expo-sharing": "~14.0.8",
"expo-status-bar": "~3.0.9",
"expo-web-browser": "~15.0.8",
"lucide-react-native": "^1.7.0",
"react": "19.1.0",
"react-native": "0.81.5",
+152 -12
View File
@@ -8,6 +8,11 @@ import type {
import { CAPABILITIES } from './types';
import { generateAccountId } from '../lib/account-utils';
import { secureFetch } from '../lib/client-cert';
import { refreshAccessToken, type OAuthTokens } from '../lib/oauth';
// Refresh OAuth access tokens this many ms before they actually expire so
// in-flight requests don't race the expiry window.
const TOKEN_REFRESH_LEEWAY_MS = 60_000;
const LEGACY_CREDENTIALS_KEY = 'jmap_credentials';
const CREDENTIALS_PREFIX = 'jmap_credentials__';
@@ -22,6 +27,12 @@ export interface StoredCredentials {
username: string;
password: string;
accessToken?: string;
// OAuth-only — present when credentials originate from the OAuth login
// flow rather than password auth.
refreshToken?: string;
expiresAt?: number;
tokenEndpoint?: string;
clientId?: string;
}
export class JMAPClient {
@@ -93,6 +104,115 @@ export class JMAPClient {
return this.session;
}
// OAuth login. Fetches the JMAP session to discover the authenticated
// username from the session.username field, persists credentials under that
// username's account id, and returns both the session and the resolved
// username so the auth-store can register the account.
async connectWithOAuth(
serverUrl: string,
tokens: OAuthTokens,
): Promise<{ session: JMAPSession; username: string; accountId: string }> {
const baseUrl = serverUrl.replace(/\/+$/, '');
this.credentials = {
serverUrl: baseUrl,
username: '',
password: '',
accessToken: tokens.accessToken,
refreshToken: tokens.refreshToken,
expiresAt: tokens.expiresAt,
tokenEndpoint: tokens.tokenEndpoint,
clientId: tokens.clientId,
};
this.session = this.rewriteSessionUrls(await this.fetchSession(baseUrl), baseUrl);
this._accountId = this.resolveAccountId(this.session);
// The JMAP session document carries the authenticated user's identifier
// — use it as the username so per-account storage keys are stable across
// restarts and OAuth re-logins.
const username = this.session.username || tokens.accessToken.slice(0, 8);
this.credentials.username = username;
const accountId = generateAccountId(username, baseUrl);
await SecureStore.setItemAsync(
credentialsKey(accountId),
JSON.stringify(this.credentials),
);
return { session: this.session, username, accountId };
}
// Replace the access token (and possibly refresh token) on the in-memory
// credentials and re-persist. Used both by the proactive expiry check and
// by the reactive 401-retry path.
private async persistRefreshedTokens(next: OAuthTokens): Promise<void> {
if (!this.credentials) return;
this.credentials = {
...this.credentials,
accessToken: next.accessToken,
refreshToken: next.refreshToken ?? this.credentials.refreshToken,
expiresAt: next.expiresAt,
tokenEndpoint: next.tokenEndpoint,
clientId: next.clientId,
};
const accountId = generateAccountId(
this.credentials.username,
this.credentials.serverUrl,
);
await SecureStore.setItemAsync(
credentialsKey(accountId),
JSON.stringify(this.credentials),
);
}
private hasRefreshableToken(): boolean {
return Boolean(this.credentials?.refreshToken && this.credentials.tokenEndpoint && this.credentials.clientId);
}
private currentOAuthTokens(): OAuthTokens | null {
if (!this.credentials?.accessToken || !this.credentials.tokenEndpoint || !this.credentials.clientId) {
return null;
}
return {
accessToken: this.credentials.accessToken,
refreshToken: this.credentials.refreshToken,
expiresAt: this.credentials.expiresAt,
tokenEndpoint: this.credentials.tokenEndpoint,
clientId: this.credentials.clientId,
};
}
// Refresh proactively when we're within the leeway window of expiry. Quiet
// no-op for password credentials or when the token is still fresh.
private async ensureFreshToken(): Promise<void> {
const tokens = this.currentOAuthTokens();
if (!tokens) return;
if (!this.hasRefreshableToken()) return;
if (tokens.expiresAt == null) return;
if (tokens.expiresAt - Date.now() > TOKEN_REFRESH_LEEWAY_MS) return;
try {
const next = await refreshAccessToken(tokens);
await this.persistRefreshedTokens(next);
} catch {
// Surface as AuthenticationError on the next 401; refresh may be
// temporarily failing (network) and that path already retries.
}
}
// Reactive refresh: called after a 401 to attempt a single retry with a
// freshly-minted access token. Returns true if a new token was obtained.
private async forceRefreshToken(): Promise<boolean> {
const tokens = this.currentOAuthTokens();
if (!tokens || !this.hasRefreshableToken()) return false;
try {
const next = await refreshAccessToken(tokens);
await this.persistRefreshedTokens(next);
return true;
} catch {
return false;
}
}
// Legacy single-slot restore - kept for backward-compat tests. New code
// should use loadAccount(accountId) driven by the account registry.
async restoreSession(): Promise<boolean> {
@@ -235,13 +355,23 @@ export class JMAPClient {
private async fetchSession(baseUrl: string): Promise<JMAPSession> {
const url = `${baseUrl}/.well-known/jmap`;
const response = await secureFetch(url, {
await this.ensureFreshToken();
let response = await secureFetch(url, {
headers: {
Authorization: this.authHeader,
Accept: 'application/json',
},
});
if (response.status === 401 && (await this.forceRefreshToken())) {
response = await secureFetch(url, {
headers: {
Authorization: this.authHeader,
Accept: 'application/json',
},
});
}
if (response.status === 401) {
throw new AuthenticationError('Invalid credentials');
}
@@ -280,14 +410,21 @@ export class JMAPClient {
methodCalls,
};
const response = await secureFetch(this.session.apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: this.authHeader,
},
body: JSON.stringify(body),
});
await this.ensureFreshToken();
const doFetch = () =>
secureFetch(this.session!.apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: this.authHeader,
},
body: JSON.stringify(body),
});
let response = await doFetch();
if (response.status === 401 && (await this.forceRefreshToken())) {
response = await doFetch();
}
if (response.status === 401) {
throw new AuthenticationError('Session expired');
@@ -335,9 +472,12 @@ export class JMAPClient {
async fetchBlobArrayBuffer(blobId: string, name?: string, type?: string): Promise<ArrayBuffer> {
const url = this.getBlobDownloadUrl(blobId, name, type);
const response = await secureFetch(url, {
headers: { Authorization: this.authHeader },
});
await this.ensureFreshToken();
const doFetch = () => secureFetch(url, { headers: { Authorization: this.authHeader } });
let response = await doFetch();
if (response.status === 401 && (await this.forceRefreshToken())) {
response = await doFetch();
}
if (response.status === 401) throw new AuthenticationError('Session expired');
if (!response.ok) throw new Error(`Failed to fetch blob: ${response.status}`);
return response.arrayBuffer();
+4
View File
@@ -9,6 +9,10 @@ export interface JMAPSession {
accounts: Record<string, JMAPAccountInfo>;
capabilities: Record<string, unknown>;
state: string;
// RFC 8620 §2 — authenticated user identifier. Optional because not all
// servers populate it; OAuth login uses it to derive the account label
// when there's no password username to fall back on.
username?: string;
}
export interface JMAPAccountInfo {
+157
View File
@@ -0,0 +1,157 @@
import * as AuthSession from 'expo-auth-session';
import * as WebBrowser from 'expo-web-browser';
import { secureFetch } from './client-cert';
// OAuth client ID registered (or accepted unregistered, when the server has
// requireClientRegistration=false like Stalwart 0.16) for the mobile app.
export const OAUTH_CLIENT_ID = 'bulwark-mobile';
// offline_access is required for Stalwart to return a refresh_token; without
// it the session dies as soon as the access token expires.
export const OAUTH_SCOPES = ['openid', 'email', 'profile', 'offline_access'];
export interface OAuthDiscovery {
authorization_endpoint: string;
token_endpoint: string;
revocation_endpoint?: string;
}
export interface OAuthTokens {
accessToken: string;
refreshToken?: string;
expiresAt?: number; // epoch ms
tokenEndpoint: string;
clientId: string;
}
export class OAuthError extends Error {}
export class OAuthCancelledError extends OAuthError {
constructor() {
super('OAuth cancelled');
}
}
export async function discoverOAuth(serverUrl: string): Promise<OAuthDiscovery> {
const baseUrl = serverUrl.replace(/\/+$/, '');
const urls = [
`${baseUrl}/.well-known/oauth-authorization-server`,
`${baseUrl}/.well-known/openid-configuration`,
];
const errors: string[] = [];
for (const url of urls) {
try {
const res = await secureFetch(url, { headers: { Accept: 'application/json' } });
if (!res.ok) {
errors.push(`${url} → HTTP ${res.status}`);
continue;
}
const data = await res.json();
if (data.authorization_endpoint && data.token_endpoint) {
return {
authorization_endpoint: data.authorization_endpoint,
token_endpoint: data.token_endpoint,
revocation_endpoint: data.revocation_endpoint,
};
}
errors.push(`${url} missing endpoints`);
} catch (err) {
errors.push(`${url}: ${err instanceof Error ? err.message : String(err)}`);
}
}
throw new OAuthError(`OAuth discovery failed: ${errors.join('; ')}`);
}
// Returns the redirect URI the browser will land on after the user signs in.
// For dev (Expo Go) this is the auth.expo.io proxy; for standalone/prebuild
// builds this is the app's custom scheme (bulwarkmobile://auth/callback).
function getRedirectUri(): string {
return AuthSession.makeRedirectUri({ scheme: 'bulwarkmobile', path: 'auth/callback' });
}
export async function runOAuthFlow(serverUrl: string): Promise<OAuthTokens> {
const discovery = await discoverOAuth(serverUrl);
const redirectUri = getRedirectUri();
const request = new AuthSession.AuthRequest({
clientId: OAUTH_CLIENT_ID,
scopes: OAUTH_SCOPES,
redirectUri,
responseType: AuthSession.ResponseType.Code,
usePKCE: true,
});
// promptAsync() opens the system browser tab and resolves when the OAuth
// server redirects back to the app via the custom scheme.
const result = await request.promptAsync({
authorizationEndpoint: discovery.authorization_endpoint,
});
if (result.type === 'cancel' || result.type === 'dismiss') {
throw new OAuthCancelledError();
}
if (result.type !== 'success') {
const msg =
result.type === 'error' && result.error
? result.error.description || result.error.message || result.type
: result.type;
throw new OAuthError(`Authorization failed: ${msg}`);
}
const code = result.params.code;
if (!code) throw new OAuthError('Authorization response missing code');
// Exchange the authorization code for tokens. Stalwart returns a JSON body
// with access_token, refresh_token, expires_in.
const tokenResult = await AuthSession.exchangeCodeAsync(
{
clientId: OAUTH_CLIENT_ID,
code,
redirectUri,
extraParams: request.codeVerifier ? { code_verifier: request.codeVerifier } : undefined,
},
{ tokenEndpoint: discovery.token_endpoint },
);
return {
accessToken: tokenResult.accessToken,
refreshToken: tokenResult.refreshToken,
expiresAt:
tokenResult.expiresIn != null
? Date.now() + tokenResult.expiresIn * 1000
: undefined,
tokenEndpoint: discovery.token_endpoint,
clientId: OAUTH_CLIENT_ID,
};
}
export async function refreshAccessToken(
tokens: OAuthTokens,
): Promise<OAuthTokens> {
if (!tokens.refreshToken) {
throw new OAuthError('No refresh token available');
}
const refreshed = await AuthSession.refreshAsync(
{ clientId: tokens.clientId, refreshToken: tokens.refreshToken },
{ tokenEndpoint: tokens.tokenEndpoint },
);
return {
accessToken: refreshed.accessToken,
// Rotated refresh tokens replace the previous one; some IdPs omit it and
// expect the client to reuse the original.
refreshToken: refreshed.refreshToken ?? tokens.refreshToken,
expiresAt:
refreshed.expiresIn != null
? Date.now() + refreshed.expiresIn * 1000
: undefined,
tokenEndpoint: tokens.tokenEndpoint,
clientId: tokens.clientId,
};
}
// Required to dismiss the in-app browser tab once the OAuth redirect fires.
// Safe to call once at module load; expo-web-browser exposes it via a method
// that no-ops on platforms where it isn't needed.
export function warmUpAuthBrowser(): void {
void WebBrowser.warmUpAsync().catch(() => undefined);
}
WebBrowser.maybeCompleteAuthSession();
+29 -2
View File
@@ -20,6 +20,7 @@ export default function LoginScreen({ onLogin, isAddMode, onCancel }: LoginScree
const c = useColors();
const styles = React.useMemo(() => makeStyles(c), [c]);
const login = useAuthStore((state) => state.login);
const loginOAuth = useAuthStore((state) => state.loginOAuth);
const isLoading = useAuthStore((state) => state.isLoading);
const error = useAuthStore((state) => state.error);
const clearError = useAuthStore((state) => state.clearError);
@@ -30,6 +31,7 @@ export default function LoginScreen({ onLogin, isAddMode, onCancel }: LoginScree
const [showPassword, setShowPassword] = React.useState(false);
const canSubmit = Boolean(serverUrl.trim() && email.trim() && password);
const canOAuth = Boolean(serverUrl.trim());
const handleLogin = async () => {
if (!canSubmit) {
@@ -44,6 +46,24 @@ export default function LoginScreen({ onLogin, isAddMode, onCancel }: LoginScree
}
};
const handleOAuth = async () => {
if (!canOAuth) return;
try {
const before = useAuthStore.getState().isAuthenticated;
await loginOAuth(serverUrl.trim(), { addAccount: isAddMode });
// loginOAuth swallows OAuthCancelledError silently — only fire the
// navigation hook when authentication actually completed.
const after = useAuthStore.getState().isAuthenticated;
if (after && !before) {
onLogin?.();
} else if (isAddMode && after) {
onLogin?.();
}
} catch {
// Store state already contains the user-facing error.
}
};
const updateField = React.useCallback(
(setter: React.Dispatch<React.SetStateAction<string>>) => (value: string) => {
if (useAuthStore.getState().error) {
@@ -151,8 +171,15 @@ export default function LoginScreen({ onLogin, isAddMode, onCancel }: LoginScree
{/* OAuth buttons */}
<View style={styles.oauthRow}>
<Button variant="outline" size="md" disabled>
SSO Provider
<Button
variant="outline"
size="md"
onPress={() => {
void handleOAuth();
}}
disabled={!canOAuth || isLoading}
>
Sign in with OAuth
</Button>
</View>
</View>
+21 -6
View File
@@ -28,14 +28,17 @@ vi.mock('../settings-store', () => ({
useSettingsStore: { getState: () => ({ archiveMode: 'single', emailsPerPage: 25 }) },
}));
// offline-cache-store is touched by selectMailbox (cache-seed fallback) and
// getEmailDetail (best-effort body refresh). Stub it as an empty cache so
// tests don't need to set up AsyncStorage.
// offline-cache-store is touched by selectMailbox (cache-seed fallback),
// getEmailDetail (best-effort body refresh), and setActiveAccount (account
// switch). Stub it as an empty cache so tests don't need to set up
// AsyncStorage.
vi.mock('../offline-cache-store', () => ({
useOfflineCacheStore: {
getState: () => ({
activeAccountId: null,
hydrated: true,
hydrate: vi.fn(),
setAccount: vi.fn(async () => undefined),
totalCount: () => 0,
getEmailsInMailbox: vi.fn(async () => []),
has: () => false,
@@ -45,19 +48,27 @@ vi.mock('../offline-cache-store', () => ({
},
}));
// email-store now early-returns from fetch actions when jmapClient.isConnected
// is false (cold-start guard). The tests exercise those actions, so present
// a connected stub.
// email-store now early-returns from fetch actions unless jmapClient is
// connected AND serving the same logical account the store has active
// (`generateAccountId(username, serverUrl) === activeAccountId`). The
// tests exercise those actions, so present a fully connected stub plus
// the matching username/serverUrl pair. beforeEach() syncs the store's
// activeAccountId to the id these credentials produce.
vi.mock('../../api/jmap-client', () => ({
jmapClient: {
isConnected: true,
accountId: 'acc-1',
username: 'test@example.com',
serverUrl: 'https://mail.example.com',
currentSession: { apiUrl: 'https://mail.example.com/jmap/' },
// refreshEmails / loadMoreEmails chunk by this value when fetching ids.
getMaxObjectsInGet: () => 500,
},
}));
import { generateAccountId } from '../../lib/account-utils';
const TEST_ACCOUNT_ID = generateAccountId('test@example.com', 'https://mail.example.com');
import * as emailApi from '../../api/email';
import { useEmailStore } from '../email-store';
@@ -74,6 +85,10 @@ const mockSearchEmails = emailApi.searchEmails as ReturnType<typeof vi.fn>;
beforeEach(() => {
vi.clearAllMocks();
useEmailStore.getState().reset();
// Wire the store's active account to the one the mocked jmapClient is
// serving, so the guard inside fetchMailboxes / refreshEmails / etc.
// doesn't short-circuit the tests.
useEmailStore.setState({ activeAccountId: TEST_ACCOUNT_ID });
});
describe('email-store', () => {
+47
View File
@@ -6,6 +6,7 @@ import { useEmailStore } from './email-store';
import { useContactsStore } from './contacts-store';
import { useCalendarStore } from './calendar-store';
import { generateAccountId } from '../lib/account-utils';
import { runOAuthFlow, OAuthCancelledError } from '../lib/oauth';
import {
teardownPushNotifications,
teardownPushNotificationsForAccount,
@@ -38,6 +39,7 @@ export interface AuthState {
client: typeof jmapClient | null;
login: (serverUrl: string, username: string, password: string, opts?: { addAccount?: boolean }) => Promise<void>;
loginOAuth: (serverUrl: string, opts?: { addAccount?: boolean }) => Promise<void>;
logout: () => Promise<void>;
logoutAll: () => Promise<void>;
switchAccount: (accountId: string) => Promise<void>;
@@ -167,6 +169,51 @@ export const useAuthStore = create<AuthState>((set, get) => ({
}
},
loginOAuth: async (serverUrl, opts) => {
set({ isLoading: true, error: null });
try {
if (opts?.addAccount && get().isAuthenticated) {
jmapClient.reset();
useContactsStore.getState().reset();
useCalendarStore.getState().reset();
}
const baseUrl = serverUrl.replace(/\/+$/, '');
const tokens = await runOAuthFlow(baseUrl);
const { session, username, accountId } = await jmapClient.connectWithOAuth(baseUrl, tokens);
const accountStore = useAccountStore.getState();
accountStore.addAccount({
serverUrl: baseUrl,
username,
displayName: username,
email: username,
lastLoginAt: Date.now(),
isConnected: true,
hasError: false,
});
accountStore.setActiveAccount(accountId);
useEmailStore.getState().setActiveAccount(accountId);
applyConnectedState(set, session, baseUrl, username, accountId);
} catch (err) {
if (err instanceof OAuthCancelledError) {
// User backed out of the browser tab — no error message, just stop
// the spinner. This matches the common "I changed my mind" path.
set({ isLoading: false, error: null });
return;
}
const message =
err instanceof AuthenticationError
? 'Authentication rejected by server'
: err instanceof Error
? err.message
: 'OAuth login failed';
set({ isLoading: false, error: message });
throw err;
}
},
logout: async () => {
const accountStore = useAccountStore.getState();
const currentId = get().activeAccountId;
+65 -19
View File
@@ -22,9 +22,27 @@ import {
searchEmails as apiSearchEmails,
} from '../api/email';
import { toWildcardQuery } from '../lib/search-utils';
import { generateAccountId } from '../lib/account-utils';
import { useSettingsStore } from './settings-store';
import { useOfflineCacheStore } from './offline-cache-store';
// True only when the JMAP client is actually serving the email-store's active
// account. During an account switch there's a window between
// setActiveAccount() (which swaps the email-store view immediately) and
// jmapClient.loadAccount() resolving, when the client is still on the
// *previous* account. Without this guard, any fetchMailboxes/refreshEmails
// fired in that window (e.g. by an EmailListScreen useEffect reacting to
// the empty new-account view) would return the previous account's data and
// stamp it into the new account's snapshot.
function jmapClientServesActiveAccount(activeAccountId: string | null): boolean {
if (!activeAccountId) return false;
if (!jmapClient.isConnected) return false;
const username = jmapClient.username;
const serverUrl = jmapClient.serverUrl;
if (!username || !serverUrl) return false;
return generateAccountId(username, serverUrl) === activeAccountId;
}
export interface EmailFilters {
from?: string;
to?: string;
@@ -315,6 +333,12 @@ export const useEmailStore = create<EmailState>()(
error: null,
loading: false,
});
// Point the offline body cache at the same account so getEmailDetail's
// fallback and selectMailbox's seed read from the right bucket. Fire-
// and-forget — the cache returns empty until hydration completes,
// which is the correct degraded behaviour.
void useOfflineCacheStore.getState().setAccount(accountId);
},
removeAccount: (accountId) => {
@@ -336,6 +360,7 @@ export const useEmailStore = create<EmailState>()(
filters: {},
pendingUndo: null,
});
void useOfflineCacheStore.getState().setAccount(null);
} else {
set({ accountSnapshots: rest });
}
@@ -359,16 +384,20 @@ export const useEmailStore = create<EmailState>()(
error: null,
loading: false,
});
void useOfflineCacheStore.getState().setAccount(null);
},
fetchMailboxes: async () => {
// Skip silently when there's no live session. Screens fire this from
// mount-time useEffects, and on cold start App.tsx renders MainTabs
// before restoreSession() finishes; without this guard the underlying
// API call would throw "Not authenticated - call connect() first" and
// surface as a user-visible error before the real fetch (kicked off by
// refetchFeatureStores() once the session is live) replaces it.
if (!jmapClient.isConnected) return;
// Skip silently when there's no live session, or when jmapClient is
// mid-transition to a different account (see jmapClientServesActiveAccount).
// Screens fire this from mount-time useEffects, and on cold start
// App.tsx renders MainTabs before restoreSession() finishes; without
// this guard the underlying API call would either throw "Not
// authenticated - call connect() first" or — worse, during an account
// switch — return the *previous* account's mailboxes and stamp them
// into the new account's snapshot.
const activeAccountId = get().activeAccountId;
if (!jmapClientServesActiveAccount(activeAccountId)) return;
const prevState = get().mailboxState;
try {
@@ -377,6 +406,9 @@ export const useEmailStore = create<EmailState>()(
// we have no previous state to compare against.
if (prevState) {
const changes = await getMailboxChanges(prevState);
// Bail if the user switched accounts during the await — anything we
// set() now would land in the wrong account's bucket.
if (get().activeAccountId !== activeAccountId) return;
if (changes) {
// No changes at all — keep the cached list, just bump the state.
if (
@@ -391,6 +423,7 @@ export const useEmailStore = create<EmailState>()(
const fetched = toFetch.length > 0
? (await getMailboxesByIds(toFetch)).list
: [];
if (get().activeAccountId !== activeAccountId) return;
const destroyed = new Set(changes.destroyed);
const byId = new Map<string, Mailbox>();
for (const m of get().mailboxes) byId.set(m.id, m);
@@ -411,9 +444,11 @@ export const useEmailStore = create<EmailState>()(
}
const { list, state } = await getMailboxesWithState();
if (get().activeAccountId !== activeAccountId) return;
set({ mailboxes: list, mailboxState: state });
} catch (err) {
console.warn('[email-store] fetchMailboxes failed:', err);
if (get().activeAccountId !== activeAccountId) return;
// Don't overwrite the cached list on a transient failure — the user
// can still navigate folders. Only surface the error when we have no
// mailboxes at all to show.
@@ -481,11 +516,11 @@ export const useEmailStore = create<EmailState>()(
pendingUndo: null,
});
// Stop here if there's no live session yet — the cached seed already
// gave the user something to look at, and the refetch driven by
// restoreSession() / switchAccount will run the network half once the
// client is connected.
if (!jmapClient.isConnected) {
// Stop here if there's no live session OR jmapClient is mid-transition
// to a different account. The cached seed already gave the user
// something to look at, and the refetch driven by restoreSession() /
// switchAccount will run the network half once the client catches up.
if (!jmapClientServesActiveAccount(get().activeAccountId)) {
set({ loading: false });
return;
}
@@ -494,9 +529,9 @@ export const useEmailStore = create<EmailState>()(
},
loadMoreEmails: async () => {
const { currentMailboxId, emails, totalEmails, loading, searchQuery, filters } = get();
const { currentMailboxId, emails, totalEmails, loading, searchQuery, filters, activeAccountId } = get();
if (!currentMailboxId || loading || emails.length >= totalEmails) return;
if (!jmapClient.isConnected) return;
if (!jmapClientServesActiveAccount(activeAccountId)) return;
set({ loading: true });
try {
@@ -507,7 +542,9 @@ export const useEmailStore = create<EmailState>()(
limit,
filter,
});
if (get().activeAccountId !== activeAccountId || get().currentMailboxId !== currentMailboxId) return;
const newEmails = ids.length > 0 ? await fetchEmailsChunked(ids) : [];
if (get().activeAccountId !== activeAccountId || get().currentMailboxId !== currentMailboxId) return;
const merged = [...emails, ...newEmails];
const updates: Partial<EmailState> = { emails: merged, loading: false };
if (isBaseView(searchQuery, filters)) {
@@ -522,15 +559,16 @@ export const useEmailStore = create<EmailState>()(
}
set(updates);
} catch (err) {
if (get().activeAccountId !== activeAccountId) return;
set({ loading: false, error: err instanceof Error ? err.message : 'Failed to load more' });
}
},
refreshEmails: async () => {
const state = get();
const { currentMailboxId, searchQuery, filters, emails: existing, queryState, emailState } = state;
const { currentMailboxId, searchQuery, filters, emails: existing, queryState, emailState, activeAccountId } = state;
if (!currentMailboxId) return;
if (!jmapClient.isConnected) return;
if (!jmapClientServesActiveAccount(activeAccountId)) return;
set({ loading: true, error: null });
const filter = buildJmapFilter(currentMailboxId, searchQuery, filters);
@@ -613,7 +651,7 @@ export const useEmailStore = create<EmailState>()(
const nextQueryState = queryChanges.newQueryState;
const nextTotal = queryChanges.total;
if (get().currentMailboxId !== currentMailboxId) return;
if (get().activeAccountId !== activeAccountId || get().currentMailboxId !== currentMailboxId) return;
set({
emails: trimmed,
@@ -666,7 +704,7 @@ export const useEmailStore = create<EmailState>()(
set(updates);
} catch (err) {
console.warn('[email-store] refreshEmails failed:', err);
if (get().currentMailboxId !== currentMailboxId) return;
if (get().activeAccountId !== activeAccountId || get().currentMailboxId !== currentMailboxId) return;
// Keep whatever's visible; only surface the error when the list is
// empty. With cached emails on screen the OfflineBanner already
// tells the user the data is stale.
@@ -679,7 +717,11 @@ export const useEmailStore = create<EmailState>()(
currentMailboxId,
Math.max(limit, 50),
);
if (get().currentMailboxId === currentMailboxId && cached.length > 0) {
if (
get().activeAccountId === activeAccountId &&
get().currentMailboxId === currentMailboxId &&
cached.length > 0
) {
set({ emails: cached, totalEmails: cached.length, loading: false, error: null });
return;
}
@@ -697,6 +739,10 @@ export const useEmailStore = create<EmailState>()(
handleStateChange: async (change) => {
if (!jmapClient.currentSession) return;
// Drop changes that arrived for a different account than the one we're
// currently showing (e.g. push notifications received during/just after
// an account switch).
if (!jmapClientServesActiveAccount(get().activeAccountId)) return;
const accountId = jmapClient.accountId;
const accountChanges = change.changed?.[accountId];
if (!accountChanges) return;
+103 -32
View File
@@ -3,16 +3,25 @@
// AsyncStorage; attachment blobs go to expo-file-system under
// `Paths.document/offline-attachments/`. The store also exposes the live
// progress state the OfflineCacheBanner reads from.
//
// Storage is keyed by the email-store's `activeAccountId` so logged-in
// accounts don't leak cached bodies into each other. The store loads one
// account's bucket at a time (the active one); switching accounts via
// setAccount() persists the current bucket then hydrates the new one.
import { create } from 'zustand';
import AsyncStorage from '@react-native-async-storage/async-storage';
import type { Email } from '../api/types';
const INDEX_KEY = 'webmail:offline-cache:index:v1';
const ENTRY_KEY_PREFIX = 'webmail:offline-cache:entry:v1:';
const INDEX_KEY_PREFIX = 'webmail:offline-cache:index:v2:';
const ENTRY_KEY_PREFIX = 'webmail:offline-cache:entry:v2:';
function entryKey(id: string): string {
return `${ENTRY_KEY_PREFIX}${id}`;
function indexKey(accountId: string): string {
return `${INDEX_KEY_PREFIX}${accountId}`;
}
function entryKey(accountId: string, emailId: string): string {
return `${ENTRY_KEY_PREFIX}${accountId}:${emailId}`;
}
export interface OfflineCacheIndexEntry {
@@ -23,8 +32,6 @@ export interface OfflineCacheIndexEntry {
}
interface CacheIndex {
// Per-account is keyed at the storage layer (one app session = one account
// active at a time). Cross-account separation is left to a future change.
entries: Record<string, OfflineCacheIndexEntry>;
}
@@ -42,8 +49,11 @@ export interface SyncState {
}
const IDLE: SyncState = { phase: 'idle', total: 0, completed: 0, fetched: 0, bytes: 0 };
const EMPTY_INDEX: CacheIndex = { entries: {} };
interface OfflineCacheState {
// Currently-loaded bucket. null = no account active (no reads/writes).
activeAccountId: string | null;
index: CacheIndex;
hydrated: boolean;
sync: SyncState;
@@ -52,6 +62,9 @@ interface OfflineCacheState {
// AbortControllers need to survive across the function boundary.
abortRequested: boolean;
// Point the store at the given account, hydrating its bucket from
// AsyncStorage. Pass null to detach (no reads/writes will hit storage).
setAccount: (accountId: string | null) => Promise<void>;
hydrate: () => Promise<void>;
has: (id: string) => boolean;
get: (id: string) => Promise<Email | null>;
@@ -74,41 +87,83 @@ interface OfflineCacheState {
consumeAbort: () => boolean;
}
function persistIndex(index: CacheIndex): void {
void AsyncStorage.setItem(INDEX_KEY, JSON.stringify(index)).catch((err) => {
function persistIndex(accountId: string, index: CacheIndex): void {
void AsyncStorage.setItem(indexKey(accountId), JSON.stringify(index)).catch((err) => {
console.warn('[offline-cache] persist index failed', err);
});
}
async function loadIndex(accountId: string): Promise<CacheIndex> {
try {
const raw = await AsyncStorage.getItem(indexKey(accountId));
if (raw) {
const parsed = JSON.parse(raw) as CacheIndex;
if (parsed && typeof parsed === 'object' && parsed.entries) {
return parsed;
}
}
} catch (err) {
console.warn('[offline-cache] hydrate failed', err);
}
return { entries: {} };
}
export const useOfflineCacheStore = create<OfflineCacheState>((set, get) => ({
activeAccountId: null,
index: { entries: {} },
hydrated: false,
sync: { ...IDLE },
abortRequested: false,
hydrate: async () => {
if (get().hydrated) return;
try {
const raw = await AsyncStorage.getItem(INDEX_KEY);
if (raw) {
const parsed = JSON.parse(raw) as CacheIndex;
if (parsed && typeof parsed === 'object' && parsed.entries) {
set({ index: parsed, hydrated: true });
return;
}
}
} catch (err) {
console.warn('[offline-cache] hydrate failed', err);
setAccount: async (accountId) => {
const state = get();
if (state.activeAccountId === accountId) {
// Same account — make sure we've hydrated.
if (!state.hydrated) await get().hydrate();
return;
}
set({ hydrated: true });
// Drop any in-flight sync state from the previous account; the abort flag
// makes runOfflineSync stop on its next chunk boundary.
set({
activeAccountId: accountId,
index: { ...EMPTY_INDEX },
hydrated: false,
sync: { ...IDLE },
abortRequested: true,
});
if (accountId) {
const index = await loadIndex(accountId);
// Re-check in case another setAccount call raced past us.
if (get().activeAccountId !== accountId) return;
set({ index, hydrated: true, abortRequested: false });
} else {
set({ hydrated: true, abortRequested: false });
}
},
hydrate: async () => {
const state = get();
if (state.hydrated) return;
const accountId = state.activeAccountId;
if (!accountId) {
// No active account yet — mark hydrated so callers that block on this
// (selectMailbox cache-seed path) don't spin. Reads will return empty.
set({ hydrated: true });
return;
}
const index = await loadIndex(accountId);
if (get().activeAccountId !== accountId) return;
set({ index, hydrated: true });
},
has: (id) => Boolean(get().index.entries[id]),
get: async (id) => {
if (!get().index.entries[id]) return null;
const state = get();
if (!state.activeAccountId) return null;
if (!state.index.entries[id]) return null;
try {
const raw = await AsyncStorage.getItem(entryKey(id));
const raw = await AsyncStorage.getItem(entryKey(state.activeAccountId, id));
if (!raw) return null;
return JSON.parse(raw) as Email;
} catch (err) {
@@ -118,12 +173,19 @@ export const useOfflineCacheStore = create<OfflineCacheState>((set, get) => ({
},
put: async (email, approxBytes) => {
const state = get();
const accountId = state.activeAccountId;
if (!accountId) return;
try {
await AsyncStorage.setItem(entryKey(email.id), JSON.stringify(email));
await AsyncStorage.setItem(entryKey(accountId, email.id), JSON.stringify(email));
} catch (err) {
console.warn('[offline-cache] put failed', email.id, err);
return;
}
// Re-read the active account in case it changed while we were awaiting
// AsyncStorage — don't stamp the new account's index with the old
// account's entry.
if (get().activeAccountId !== accountId) return;
const nextEntries = {
...get().index.entries,
[email.id]: {
@@ -135,35 +197,44 @@ export const useOfflineCacheStore = create<OfflineCacheState>((set, get) => ({
};
const index = { entries: nextEntries };
set({ index });
persistIndex(index);
persistIndex(accountId, index);
},
remove: async (ids) => {
if (ids.length === 0) return;
const accountId = get().activeAccountId;
if (!accountId) return;
await Promise.all(
ids.map((id) => AsyncStorage.removeItem(entryKey(id)).catch(() => undefined)),
ids.map((id) => AsyncStorage.removeItem(entryKey(accountId, id)).catch(() => undefined)),
);
if (get().activeAccountId !== accountId) return;
const next = { ...get().index.entries };
for (const id of ids) delete next[id];
const index = { entries: next };
set({ index });
persistIndex(index);
persistIndex(accountId, index);
},
clearAll: async () => {
const accountId = get().activeAccountId;
if (!accountId) return;
const ids = Object.keys(get().index.entries);
await Promise.all(
ids.map((id) => AsyncStorage.removeItem(entryKey(id)).catch(() => undefined)),
ids.map((id) => AsyncStorage.removeItem(entryKey(accountId, id)).catch(() => undefined)),
);
if (get().activeAccountId !== accountId) return;
const index = { entries: {} };
set({ index, sync: { ...IDLE } });
persistIndex(index);
persistIndex(accountId, index);
},
getEmailsInMailbox: async (mailboxId, limit = 200) => {
const state = get();
const accountId = state.activeAccountId;
if (!accountId) return [];
// Sort the index by receivedAt descending first so we don't have to read
// entries we won't return — the index already carries receivedAt.
const sorted = Object.values(get().index.entries).sort((a, b) => {
const sorted = Object.values(state.index.entries).sort((a, b) => {
const at = a.receivedAt ? new Date(a.receivedAt).getTime() : 0;
const bt = b.receivedAt ? new Date(b.receivedAt).getTime() : 0;
return bt - at;
@@ -172,7 +243,7 @@ export const useOfflineCacheStore = create<OfflineCacheState>((set, get) => ({
for (const entry of sorted) {
if (matches.length >= limit) break;
try {
const raw = await AsyncStorage.getItem(entryKey(entry.id));
const raw = await AsyncStorage.getItem(entryKey(accountId, entry.id));
if (!raw) continue;
const email = JSON.parse(raw) as Email;
if (email.mailboxIds?.[mailboxId]) {
+30
View File
@@ -64,3 +64,33 @@ vi.mock('expo-secure-store', () => ({
getItemAsync: vi.fn(async () => null),
deleteItemAsync: vi.fn(async () => undefined),
}));
// expo-auth-session and expo-web-browser transitively pull in
// expo-modules-core, which evaluates RN-only globals at module load. The unit
// tests don't exercise the real OAuth flow, so stubbing the surface is
// enough — individual tests that need the real shapes can override.
vi.mock('expo-auth-session', () => ({
AuthRequest: class {
codeVerifier?: string;
async promptAsync() {
return { type: 'cancel' as const };
}
},
ResponseType: { Code: 'code' },
exchangeCodeAsync: vi.fn(async () => ({
accessToken: 'test-access',
refreshToken: 'test-refresh',
expiresIn: 3600,
})),
refreshAsync: vi.fn(async () => ({
accessToken: 'test-access-refreshed',
refreshToken: 'test-refresh-rotated',
expiresIn: 3600,
})),
makeRedirectUri: () => 'bulwarkmobile://auth/callback',
}));
vi.mock('expo-web-browser', () => ({
warmUpAsync: vi.fn(async () => undefined),
maybeCompleteAuthSession: vi.fn(),
}));