From 38bcf8b8937230e2e1bb5fd25d9709787ec46c2c Mon Sep 17 00:00:00 2001 From: le king fu Date: Mon, 2 Nov 2026 21:06:10 -0500 Subject: [PATCH] fix(sync): no merge across accounts, sync off until the first-sync choice MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs #165 A device holding another account's data (dataOwnerId, persisted, kept at sign-out) only offers « Charger ce compte » (initialReset) or « Annuler » (sign-out, data untouched), at sign-in and on « Synchroniser ». The rule lives in syncRules.ts (firstSyncChoice). Sync stays off until initialMerge or initialReset has succeeded, and the scheduler refuses every sync while the local data belong to another account (canSync): the outbox of the old account is never pushed under the new one. The sync's own outbox writes (kept rows, the Inbox of initialReset) no longer depend on syncEnabled, and the token getter follows the session, so that the first sync runs with sync still off. Sign-out pushes the outbox first (10 s at most, in the first-sync state of the scheduler, one request reserved outside its budget) and warns with the number of changes still unsent. Co-Authored-By: Claude Opus 5.5 --- app/(tabs)/settings.tsx | 200 ++++++++++++++++++++------------- app/_layout.tsx | 8 +- src/db/repository/outbox.ts | 14 +++ src/i18n/en.json | 7 +- src/i18n/fr.json | 7 +- src/services/syncClient.ts | 70 +++++++++--- src/services/syncRules.ts | 34 ++++++ src/services/syncSchedule.ts | 42 ++++++- src/stores/useSettingsStore.ts | 7 ++ tests/smoke.test.cjs | 85 +++++++++++++- tests/syncRules.test.mjs | 44 ++++++++ tests/syncSchedule.test.mjs | 91 +++++++++++++++ 12 files changed, 505 insertions(+), 104 deletions(-) diff --git a/app/(tabs)/settings.tsx b/app/(tabs)/settings.tsx index 7ea22e1..3644515 100644 --- a/app/(tabs)/settings.tsx +++ b/app/(tabs)/settings.tsx @@ -12,7 +12,9 @@ import { redirectUri, postSignOutRedirectUri } from '@/src/lib/logtoConfig'; import { getAllTags, createTag, updateTag, deleteTag } from '@/src/db/repository/tags'; import { initCalendar } from '@/src/services/calendar'; import { syncWidgetData } from '@/src/services/widgetSync'; -import { scheduleSync, initialMerge, initialReset } from '@/src/services/syncClient'; +import { scheduleSync, initialMerge, initialReset, pushBeforeSignOut } from '@/src/services/syncClient'; +import { firstSyncChoice } from '@/src/services/syncRules'; +import { getInboxId } from '@/src/db/repository/lists'; import i18n from '@/src/i18n'; import FeedbackModal from '@/src/components/FeedbackModal'; @@ -104,54 +106,109 @@ export default function SettingsScreen() { ]); }; + // First sync (#165): sync stays off until initialMerge or initialReset has + // succeeded. Switched on before the choice, it would push the outbox left + // by another account under the account just signed in. + const runFirstSync = async (kind: 'merge' | 'reset') => { + const accountId = useSettingsStore.getState().userId; + if (!accountId) return; + setIsSyncing(true); + try { + if (kind === 'merge') { + await initialMerge(accountId); + } else { + await initialReset(accountId); + } + setSyncEnabled(true); + Alert.alert(t('sync.firstSyncTitle'), t(kind === 'merge' ? 'sync.mergeDone' : 'sync.resetDone')); + } catch { + Alert.alert(t('sync.syncError')); + } finally { + setIsSyncing(false); + } + }; + + // Sign out of Logto and forget the account. Local data and dataOwnerId stay + // on the device: nothing is pushed nor deleted here. + const finishSignOut = async () => { + try { + await logtoSignOut(postSignOutRedirectUri); + } catch { + // Sign-out may fail if session expired, that's OK + } + setSyncEnabled(false); + setUserId(null); + setLastSyncAt(null); + }; + + // The first-sync choice, at sign-in and on « Synchroniser » before the + // first sync. A device holding another account's data only offers to load + // the signed-in account; « Annuler » signs out (#165). + const offerFirstSync = async () => { + const { dataOwnerId, userId: signedInId } = useSettingsStore.getState(); + if (!signedInId) return; + const localInboxId = await getInboxId(); + const choice = firstSyncChoice({ dataOwnerId, signedInId, localInboxId }); + + if (choice === 'reset-only') { + Alert.alert( + t('sync.firstSyncTitle'), + t('sync.accountSwitchMessage'), + [ + { + text: t('common.cancel'), + style: 'cancel', + onPress: () => { + finishSignOut(); + }, + }, + { + text: t('sync.loadAccount'), + style: 'destructive', + onPress: () => { + runFirstSync('reset'); + }, + }, + ], + { cancelable: false }, + ); + return; + } + + Alert.alert( + t('sync.firstSyncTitle'), + t('sync.firstSyncMessage'), + [ + { + text: t('sync.mergeLocal'), + onPress: () => { + runFirstSync('merge'); + }, + }, + { + text: t('sync.resetFromServer'), + style: 'destructive', + onPress: () => { + runFirstSync('reset'); + }, + }, + ], + ); + }; + const handleSignIn = async () => { try { await logtoSignIn({ redirectUri }); const claims = await getIdTokenClaims(); setUserId(claims.sub); - setSyncEnabled(true); - - // First sync: show merge/reset choice - Alert.alert( - t('sync.firstSyncTitle'), - t('sync.firstSyncMessage'), - [ - { - text: t('sync.mergeLocal'), - onPress: async () => { - setIsSyncing(true); - try { - await initialMerge(); - Alert.alert(t('sync.firstSyncTitle'), t('sync.mergeDone')); - } catch { - Alert.alert(t('sync.syncError')); - } finally { - setIsSyncing(false); - } - }, - }, - { - text: t('sync.resetFromServer'), - style: 'destructive', - onPress: async () => { - setIsSyncing(true); - try { - await initialReset(); - Alert.alert(t('sync.firstSyncTitle'), t('sync.resetDone')); - } catch { - Alert.alert(t('sync.syncError')); - } finally { - setIsSyncing(false); - } - }, - }, - ], - ); + await offerFirstSync(); } catch (err) { console.warn('[auth] sign-in error:', err); } }; + // Sign-out pushes the pending changes to the account first (#165). Those + // still unsent (offline) are counted, and the user may cancel. const handleSignOut = () => { Alert.alert(t('sync.signOutConfirm'), '', [ { text: t('common.cancel'), style: 'cancel' }, @@ -159,57 +216,38 @@ export default function SettingsScreen() { text: t('sync.signOut'), style: 'destructive', onPress: async () => { + setIsSyncing(true); + let unsent = 0; try { - await logtoSignOut(postSignOutRedirectUri); + unsent = await pushBeforeSignOut(); } catch { - // Sign-out may fail if session expired, that's OK + // Counted as nothing unsent: the push logs its own errors + } finally { + setIsSyncing(false); } - setSyncEnabled(false); - setUserId(null); - setLastSyncAt(null); + if (unsent > 0) { + Alert.alert(t('sync.unsentWarning', { count: unsent }), '', [ + { text: t('common.cancel'), style: 'cancel' }, + { + text: t('sync.signOutAnyway'), + style: 'destructive', + onPress: () => { + finishSignOut(); + }, + }, + ]); + return; + } + await finishSignOut(); }, }, ]); }; const handleSyncNow = async () => { - // If never synced before, show first-sync choice - if (!lastSyncAt) { - Alert.alert( - t('sync.firstSyncTitle'), - t('sync.firstSyncMessage'), - [ - { - text: t('sync.mergeLocal'), - onPress: async () => { - setIsSyncing(true); - try { - await initialMerge(); - Alert.alert(t('sync.firstSyncTitle'), t('sync.mergeDone')); - } catch { - Alert.alert(t('sync.syncError')); - } finally { - setIsSyncing(false); - } - }, - }, - { - text: t('sync.resetFromServer'), - style: 'destructive', - onPress: async () => { - setIsSyncing(true); - try { - await initialReset(); - Alert.alert(t('sync.firstSyncTitle'), t('sync.resetDone')); - } catch { - Alert.alert(t('sync.syncError')); - } finally { - setIsSyncing(false); - } - }, - }, - ], - ); + // First sync not done yet (sync still off): offer the choice + if (!syncEnabled || !lastSyncAt) { + await offerFirstSync(); return; } diff --git a/app/_layout.tsx b/app/_layout.tsx index f0bbc74..b7ac5fb 100644 --- a/app/_layout.tsx +++ b/app/_layout.tsx @@ -114,15 +114,17 @@ function AppContent() { const appState = useRef(AppState.currentState); const { getAccessToken, isAuthenticated } = useLogto(); - // Register the token getter for syncClient when authenticated + // Register the token getter for syncClient when authenticated, sync on or + // off: the first sync (initialMerge, initialReset) runs before sync is + // switched on (#165). Scheduled syncs stay behind canSync (syncEnabled). useEffect(() => { - if (isAuthenticated && syncEnabled) { + if (isAuthenticated) { setTokenGetter(getAccessToken); } else { clearTokenGetter(); } return () => clearTokenGetter(); - }, [isAuthenticated, syncEnabled, getAccessToken]); + }, [isAuthenticated, getAccessToken]); // Sync (#178): on launch, every 30 s in the foreground, on return from // background and after a local write, always through the scheduler (one diff --git a/src/db/repository/outbox.ts b/src/db/repository/outbox.ts index 162f84f..d00303b 100644 --- a/src/db/repository/outbox.ts +++ b/src/db/repository/outbox.ts @@ -18,7 +18,21 @@ export async function writeOutboxEntry( ): Promise { const { syncEnabled } = useSettingsStore.getState(); if (!syncEnabled) return; + await queueOutboxEntry(entityType, entityId, action, payload); +} +/** + * Write an entry to the sync outbox whatever the setting: for the sync's own + * writes (a newer local row kept by the pull, the Inbox created by + * initialReset). The first sync runs while sync is still off (#165), and + * these entries must reach the server once it is switched on. + */ +export async function queueOutboxEntry( + entityType: EntityType, + entityId: string, + action: Action, + payload: Record +): Promise { await db.insert(syncOutbox).values({ id: randomUUID(), entityType, diff --git a/src/i18n/en.json b/src/i18n/en.json index 93df87d..413bbad 100644 --- a/src/i18n/en.json +++ b/src/i18n/en.json @@ -167,7 +167,12 @@ "merging": "Merging...", "mergeDone": "Tasks merged successfully!", "resetDone": "Data synced from server.", - "syncError": "Sync error" + "syncError": "Sync error", + "accountSwitchMessage": "This phone holds the data of another account. They stay on that other account; they will be removed from the phone to load the data of this account. What was created on this phone since signing out will be removed too.", + "loadAccount": "Load this account", + "unsentWarning_one": "{{count}} change has not been sent yet. It will be lost if you switch accounts.", + "unsentWarning_other": "{{count}} changes have not been sent yet. They will be lost if you switch accounts.", + "signOutAnyway": "Sign out anyway" }, "widget": { "title": "Simpl-Liste", diff --git a/src/i18n/fr.json b/src/i18n/fr.json index ac6d78e..8295ead 100644 --- a/src/i18n/fr.json +++ b/src/i18n/fr.json @@ -167,7 +167,12 @@ "merging": "Fusion en cours...", "mergeDone": "Tâches fusionnées avec succès !", "resetDone": "Données synchronisées depuis le serveur.", - "syncError": "Erreur de synchronisation" + "syncError": "Erreur de synchronisation", + "accountSwitchMessage": "Ce téléphone contient les données d'un autre compte. Elles restent sur cet autre compte ; elles vont être retirées du téléphone pour charger celles de ce compte. Ce qui a été créé sur ce téléphone depuis la déconnexion sera aussi retiré.", + "loadAccount": "Charger ce compte", + "unsentWarning_one": "{{count}} modification n'est pas encore envoyée. Elle sera perdue si vous changez de compte.", + "unsentWarning_other": "{{count}} modifications ne sont pas encore envoyées. Elles seront perdues si vous changez de compte.", + "signOutAnyway": "Se déconnecter quand même" }, "widget": { "title": "Simpl-Liste", diff --git a/src/services/syncClient.ts b/src/services/syncClient.ts index 4500c70..c2df178 100644 --- a/src/services/syncClient.ts +++ b/src/services/syncClient.ts @@ -5,7 +5,7 @@ import { useSettingsStore } from '@/src/stores/useSettingsStore'; import { getAccessToken } from '@/src/lib/authToken'; import { randomUUID } from '@/src/lib/uuid'; import { syncWidgetData } from '@/src/services/widgetSync'; -import { writeOutboxEntry } from '@/src/db/repository/outbox'; +import { queueOutboxEntry } from '@/src/db/repository/outbox'; import { SYNC_EPOCH, keepLocal, @@ -24,6 +24,7 @@ import { type PostResponse, } from '@/src/services/syncRules'; import { + canSync, createSyncScheduler, type RequestTracker, type RunOutcome, @@ -227,7 +228,7 @@ async function applyListChange(id: string, action: string, payload: Record { } // One scheduler per process: launch, the 30 s interval, the return to the -// foreground, local writes and the Settings button all go through it. +// foreground, local writes and the Settings button all go through it. No run +// while sync is off or the local data belong to another account (#165). const scheduler = createSyncScheduler({ now: () => Date.now(), setTimer: (fn, ms) => setTimeout(fn, ms), - canRun: () => useSettingsStore.getState().syncEnabled, + canRun: () => canSync(useSettingsStore.getState()), run: async (run) => { const outcome = await fullSync(run); await cleanOutbox().catch(() => {}); @@ -347,16 +349,52 @@ export function scheduleSync(): Promise { return scheduler.request(); } +/** Wait for the sign-out push, in ms (#165). */ +const SIGN_OUT_PUSH_TIMEOUT_MS = 10_000; + +/** + * Last push before sign-out (#165): the pending outbox goes to the account + * still signed in. Held in the first-sync state of the scheduler, so never + * alongside a sync, with a request reserved outside its budget. Waits + * SIGN_OUT_PUSH_TIMEOUT_MS at most (a push still in flight goes on, the + * first-sync state ends with it). Pushes nothing when the scheduler could + * not run (sync off, data of another account). Returns the number of outbox + * entries still unsent. + */ +export async function pushBeforeSignOut(): Promise { + if (canSync(useSettingsStore.getState())) { + const push = (async () => { + await scheduler.beginInitialSync(); + try { + await pushChanges(scheduler.reserve()); + } catch (err) { + console.warn('[sync] sign-out push error:', err); + } finally { + scheduler.endInitialSync(); + } + })(); + await Promise.race([push, sleep(SIGN_OUT_PUSH_TIMEOUT_MS)]); + } + const unsent = await db + .select({ id: syncOutbox.id }) + .from(syncOutbox) + .where(isNull(syncOutbox.syncedAt)); + return unsent.length; +} + /** * First-time sync: merge all local data to server. * Creates an Inbox on the server, remaps the local hardcoded Inbox ID, * then pushes all lists, tasks, tags, and task-tag relations, and finally - * pulls the whole account from SYNC_EPOCH. + * pulls the whole account from SYNC_EPOCH. Runs while sync is still off + * (#165): `accountId` (the signed-in `sub`) becomes the owner of the local + * data once done. Throws when it could not run, so that sync stays off. */ -export async function initialMerge(): Promise { +export async function initialMerge(accountId: string): Promise { await scheduler.beginInitialSync(); try { await mergeLocalData(); + useSettingsStore.getState().setDataOwnerId(accountId); } finally { scheduler.endInitialSync(); } @@ -364,7 +402,7 @@ export async function initialMerge(): Promise { async function mergeLocalData(): Promise { const headers = await getAuthHeaders(); - if (!headers['Authorization']) return; + if (!headers['Authorization']) throw new Error('Not signed in'); const operations: SyncOperation[] = []; @@ -479,12 +517,17 @@ async function mergeLocalData(): Promise { } /** - * First-time sync: discard local data and pull everything from server. + * First-time sync: discard local data and pull everything from server. Also + * « Charger ce compte » on a device holding another account's data (#165): + * the outbox of that account is deleted with the rest. Runs while sync is + * still off: `accountId` (the signed-in `sub`) becomes the owner of the local + * data once done. Throws when it could not run, so that sync stays off. */ -export async function initialReset(): Promise { +export async function initialReset(accountId: string): Promise { await scheduler.beginInitialSync(); try { await resetFromServer(); + useSettingsStore.getState().setDataOwnerId(accountId); } finally { scheduler.endInitialSync(); } @@ -492,14 +535,15 @@ export async function initialReset(): Promise { async function resetFromServer(): Promise { const headers = await getAuthHeaders(); - if (!headers['Authorization']) return; + if (!headers['Authorization']) throw new Error('Not signed in'); - // 1. Delete all local data + // 1. Delete all local data: the device holds nobody's data any more await db.delete(taskTags); await db.delete(tasks); await db.delete(tags); await db.delete(lists); await db.delete(syncOutbox); + useSettingsStore.getState().setDataOwnerId(null); // 2. Pull everything from server await pullChanges(SYNC_EPOCH, scheduler.tracker); @@ -514,7 +558,7 @@ async function resetFromServer(): Promise { const now = new Date(); const inbox = { id, name: 'Inbox', color: null, icon: null, position: 0, isInbox: true }; await db.insert(lists).values({ ...inbox, createdAt: now, updatedAt: now }); - await writeOutboxEntry('list', id, 'create', inbox); + await queueOutboxEntry('list', id, 'create', inbox); } } diff --git a/src/services/syncRules.ts b/src/services/syncRules.ts index 3209a08..a90bf22 100644 --- a/src/services/syncRules.ts +++ b/src/services/syncRules.ts @@ -561,3 +561,37 @@ export function planInboxRepair( return { inboxId, movedTaskIds: moved.map((t) => t.id), ops, rewrites, discardIds }; } + +// --------------------------------------------------------------------------- +// First sync after a sign-in: no merge across accounts (#165) +// --------------------------------------------------------------------------- + +/** + * Choice offered by the first sync: `merge-or-reset` (Fusionner / Remplacer) + * or `reset-only` (« Charger ce compte » alone, which empties the device). + */ +export type FirstSyncChoice = 'merge-or-reset' | 'reset-only'; + +export interface FirstSyncInput { + /** Account the local data come from (settings store), null when unknown. */ + dataOwnerId: string | null; + /** `sub` of the account just signed in. */ + signedInId: string; + /** Id of the local Inbox (pickInboxId), null when there is none. */ + localInboxId: string | null; +} + +/** + * The server refuses every local row of another account (ids taken, lists + * not owned), so a device holding another account's data only offers to load + * the new one: nothing passes from one account to the other (decision of Max, + * 2026-10-25). A known owner decides alone. An unknown owner (device signed + * out before #165) is told by the Inbox: the fixed id means the device has + * never synced, a server id means it has, under an account that may be + * another one, so it is treated as one. + */ +export function firstSyncChoice({ dataOwnerId, signedInId, localInboxId }: FirstSyncInput): FirstSyncChoice { + if (dataOwnerId !== null) return dataOwnerId === signedInId ? 'merge-or-reset' : 'reset-only'; + if (localInboxId === null || localInboxId === LOCAL_INBOX_ID) return 'merge-or-reset'; + return 'reset-only'; +} diff --git a/src/services/syncSchedule.ts b/src/services/syncSchedule.ts index e71fc4a..a5eef92 100644 --- a/src/services/syncSchedule.ts +++ b/src/services/syncSchedule.ts @@ -48,12 +48,33 @@ export interface SchedulerDeps { /** One sync (push then pull). Its errors are swallowed by the scheduler. */ run(ctx: SyncRun): Promise; /** - * Checked before each run: false drops the pending requests (sync off, and - * later other guards such as the account check of #165). + * Checked before each run: false drops the pending requests (canSync: sync + * off, or local data of another account, #165). */ canRun?(): boolean; } +/** Settings read by canSync (#165). */ +export interface SyncGuardState { + syncEnabled: boolean; + /** Account the local data come from, null when unknown. */ + dataOwnerId: string | null; + /** `sub` of the signed-in account. */ + userId: string | null; +} + +/** + * True when a scheduled sync may run: sync on, and no local data of another + * account (#165). A known owner other than the signed-in account blocks every + * sync: its outbox would be pushed under the wrong account. An unknown owner + * (device synced before #165) does not block: sync is only switched on once + * the first-sync choice has succeeded. + */ +export function canSync(state: SyncGuardState): boolean { + if (!state.syncEnabled) return false; + return state.dataOwnerId === null || state.dataOwnerId === state.userId; +} + export interface SyncScheduler { /** * Ask for a sync. Resolves when the run that serves this request ends, or @@ -70,6 +91,14 @@ export interface SyncScheduler { */ beginInitialSync(): Promise; endInitialSync(): void; + /** + * Run for the push before sign-out (#165), to call inside the first-sync + * state: its request is reserved outside the budget. It may send the + * remaining budget, and at least one POST even when the budget is spent; + * none while a 429 suspends the scheduler. Its requests count in the budget + * of the next runs. + */ + reserve(): SyncRun; } export function createSyncScheduler(deps: SchedulerDeps): SyncScheduler { @@ -184,5 +213,14 @@ export function createSyncScheduler(deps: SchedulerDeps): SyncScheduler { initial = Math.max(0, initial - 1); pump(); }, + reserve() { + const now = deps.now(); + return { + pushBatches: now < suspendedUntil ? 0 : Math.max(1, remaining(now)), + request: tracker.request, + rateLimited: tracker.rateLimited, + isSuspended: () => deps.now() < suspendedUntil, + }; + }, }; } diff --git a/src/stores/useSettingsStore.ts b/src/stores/useSettingsStore.ts index 4270e24..4124395 100644 --- a/src/stores/useSettingsStore.ts +++ b/src/stores/useSettingsStore.ts @@ -15,6 +15,10 @@ interface SettingsState { syncEnabled: boolean; lastSyncAt: string | null; // ISO timestamp userId: string | null; + // Account the local data come from (#165): set by initialMerge and + // initialReset once done, kept at sign-out, null when the app empties the + // device or before any sync (also on a device synced before #165). + dataOwnerId: string | null; setTheme: (theme: ThemeMode) => void; setLocale: (locale: 'fr' | 'en') => void; setNotificationsEnabled: (enabled: boolean) => void; @@ -24,6 +28,7 @@ interface SettingsState { setSyncEnabled: (enabled: boolean) => void; setLastSyncAt: (timestamp: string | null) => void; setUserId: (userId: string | null) => void; + setDataOwnerId: (dataOwnerId: string | null) => void; } // Error of a failed settings load, and who waits for it (whenSettingsHydrated) @@ -42,6 +47,7 @@ export const useSettingsStore = create()( syncEnabled: false, lastSyncAt: null, userId: null, + dataOwnerId: null, setTheme: (theme) => set({ theme }), setLocale: (locale) => set({ locale }), setNotificationsEnabled: (notificationsEnabled) => set({ notificationsEnabled }), @@ -51,6 +57,7 @@ export const useSettingsStore = create()( setSyncEnabled: (syncEnabled) => set({ syncEnabled }), setLastSyncAt: (lastSyncAt) => set({ lastSyncAt }), setUserId: (userId) => set({ userId }), + setDataOwnerId: (dataOwnerId) => set({ dataOwnerId }), }), { name: 'simpl-liste-settings', diff --git a/tests/smoke.test.cjs b/tests/smoke.test.cjs index b51ac94..6f7004f 100644 --- a/tests/smoke.test.cjs +++ b/tests/smoke.test.cjs @@ -245,6 +245,84 @@ check('sync on write and every sync go through the scheduler (#178)', () => { assert.equal((client.match(/pullChanges\(SYNC_EPOCH, scheduler\.tracker\)/g) || []).length, 2, 'the first-sync pulls are counted'); }); +// No merge across accounts (#165). firstSyncChoice and canSync are executed +// by tests/syncRules.test.mjs and tests/syncSchedule.test.mjs; this check +// locks their wiring in files node cannot load: sync stays off until the +// first-sync choice has succeeded, the owner of the local data is recorded, +// « Annuler » touches no data, and sign-out pushes first. +check('account switch: sync off until the choice, owner recorded, sign-out pushes first (#165)', () => { + const read = (rel) => fs.readFileSync(path.join(__dirname, '..', rel), 'utf8'); + const body = (src, head) => { + const start = src.indexOf(head); + assert.ok(start >= 0, `${head} not found`); + const end = src.indexOf('\n };\n', start); + return src.slice(start, end < 0 ? undefined : end); + }; + const settings = read('app/(tabs)/settings.tsx'); + // setSyncEnabled(true) only once, after a successful initialMerge / initialReset + assert.equal((settings.match(/setSyncEnabled\(true\)/g) || []).length, 1, 'one setSyncEnabled(true), in runFirstSync'); + const run = body(settings, 'const runFirstSync = async ('); + assert.match(run, /await initialMerge\(accountId\);\s*\} else \{\s*await initialReset\(accountId\);\s*\}\s*setSyncEnabled\(true\);/, 'sync on only after the first sync succeeded'); + const signIn = body(settings, 'const handleSignIn = async ('); + assert.ok(!/setSyncEnabled/.test(signIn), 'handleSignIn must not switch sync on before the choice'); + assert.match(signIn, /setUserId\(claims\.sub\);\s*await offerFirstSync\(\);/); + const syncNow = body(settings, 'const handleSyncNow = async ('); + assert.match(syncNow, /if \(!syncEnabled \|\| !lastSyncAt\) \{\s*await offerFirstSync\(\);\s*return;/); + // Both sites go through firstSyncChoice, fed by the persisted owner + const offer = body(settings, 'const offerFirstSync = async ('); + assert.match(offer, /const \{ dataOwnerId, userId: signedInId \} = useSettingsStore\.getState\(\);/); + assert.match(offer, /firstSyncChoice\(\{ dataOwnerId, signedInId, localInboxId \}\)/); + const onlyStart = offer.indexOf("if (choice === 'reset-only')"); + assert.ok(onlyStart >= 0, 'reset-only branch not found'); + const only = offer.slice(onlyStart, offer.indexOf('return;', onlyStart)); + assert.ok(!/initialMerge|runFirstSync\('merge'\)/.test(only), 'reset-only offers no merge'); + assert.match(only, /text: t\('common\.cancel'\),\s*style: 'cancel',\s*onPress: \(\) => \{\s*finishSignOut\(\);/, '« Annuler » signs out'); + assert.match(only, /text: t\('sync\.loadAccount'\),[^]*?runFirstSync\('reset'\);/, '« Charger ce compte » goes through initialReset'); + // « Annuler » touches no data: neither push, nor reset, nor database + const finish = body(settings, 'const finishSignOut = async ('); + assert.ok(!/initialReset|initialMerge|pushBeforeSignOut|setDataOwnerId|\bdb\b|delete/.test(finish), 'finishSignOut must touch no data'); + // Sign-out pushes first, then counts what is left + const signOut = body(settings, 'const handleSignOut = ('); + assert.match(signOut, /unsent = await pushBeforeSignOut\(\);[^]*if \(unsent > 0\) \{\s*Alert\.alert\(t\('sync\.unsentWarning', \{ count: unsent \}\)/); + assert.ok(signOut.indexOf('pushBeforeSignOut()') < signOut.indexOf('await finishSignOut();'), 'push before the sign-out'); + + const client = read('src/services/syncClient.ts'); + // The scheduler's guard reads the owner of the data + assert.match(client, /canRun: \(\) => canSync\(useSettingsStore\.getState\(\)\),/); + const fnBody = (name) => { + const start = client.indexOf(`export async function ${name}(`); + assert.ok(start >= 0, `${name} not found`); + return client.slice(start, client.indexOf('\n}\n', start)); + }; + // The owner is recorded once the first sync is done, cleared with the data + assert.match(fnBody('initialMerge'), /await mergeLocalData\(\);\s*useSettingsStore\.getState\(\)\.setDataOwnerId\(accountId\);/); + assert.match(fnBody('initialReset'), /await resetFromServer\(\);\s*useSettingsStore\.getState\(\)\.setDataOwnerId\(accountId\);/); + const reset = client.slice(client.indexOf('async function resetFromServer(')); + assert.match(reset, /await db\.delete\(syncOutbox\);\s*useSettingsStore\.getState\(\)\.setDataOwnerId\(null\);/, 'the outbox of the other account is deleted, owner cleared'); + // Neither first sync runs silently without a session: sync would stay off + for (const name of ['mergeLocalData', 'resetFromServer']) { + const start = client.indexOf(`async function ${name}(`); + assert.match(client.slice(start, start + 300), /if \(!headers\['Authorization'\]\) throw new Error\(/, `${name} must throw without a session`); + } + // Sign-out push: guarded, in the first-sync state, reserved run, bounded + const push = fnBody('pushBeforeSignOut'); + assert.match(client, /const SIGN_OUT_PUSH_TIMEOUT_MS = 10_000;/); + assert.match(push, /if \(canSync\(useSettingsStore\.getState\(\)\)\) \{/); + assert.match(push, /await scheduler\.beginInitialSync\(\);\s*try \{\s*await pushChanges\(scheduler\.reserve\(\)\);[^]*\} finally \{\s*scheduler\.endInitialSync\(\);/); + assert.match(push, /await Promise\.race\(\[push, sleep\(SIGN_OUT_PUSH_TIMEOUT_MS\)\]\);/); + assert.match(push, /\.where\(isNull\(syncOutbox\.syncedAt\)\);\s*return unsent\.length;/); + assert.ok(!/pullChanges|fullSync/.test(push), 'the sign-out push does not pull'); + + // dataOwnerId is persisted with the settings and never cleared at sign-out + const store = read('src/stores/useSettingsStore.ts'); + assert.match(store, /dataOwnerId: null,/); + assert.ok(!/partialize/.test(store), 'every setting is persisted, dataOwnerId included'); + + // The token getter follows the session, not syncEnabled: the first sync runs sync off + const layout = read('app/_layout.tsx'); + assert.match(layout, /if \(isAuthenticated\) \{\s*setTokenGetter\(getAccessToken\);/); +}); + // Tags must not go through keepLocal: the server's tag updated_at is its // created_at (no updatedAt column), so a local rename would always look newer // (PR #157 review). syncClient.ts cannot load under node, hence a source check. @@ -320,7 +398,7 @@ check('syncClient.ts wires the #149-#151 sync rules', () => { const body = fn(name); assert.match( body, - new RegExp(`if \\(keepLocal\\(local, payload, since\\)\\) \\{\\s*(//[^\\n]*\\s*)?await writeOutboxEntry\\('${type}', id, 'update', ${snapshot}\\(local\\)\\);\\s*return;\\s*\\}`), + new RegExp(`if \\(keepLocal\\(local, payload, since\\)\\) \\{\\s*(//[^\\n]*\\s*)?await queueOutboxEntry\\('${type}', id, 'update', ${snapshot}\\(local\\)\\);\\s*return;\\s*\\}`), `${name}: a kept row must be re-queued, then left untouched` ); assert.match(body, new RegExp(`${values}\\(id, payload, local\\)`), `${name} must pass the local row`); @@ -328,7 +406,7 @@ check('syncClient.ts wires the #149-#151 sync rules', () => { // Tags always take the server version (decision of Max, PR #157) const tag = fn('applyTagChange'); assert.match(tag, /pulledTagValues\(id, payload, local\)/); - assert.ok(!/\bkeepLocal\b|writeOutboxEntry|updated_at/.test(tag), 'applyTagChange must never keep a local tag'); + assert.ok(!/\bkeepLocal\b|writeOutboxEntry|queueOutboxEntry|updated_at/.test(tag), 'applyTagChange must never keep a local tag'); // #150: lastSyncAt goes back to SYNC_EPOCH before the full pull, never after const merge = fn('mergeLocalData'); const stamp = merge.indexOf('setLastSyncAt(SYNC_EPOCH)'); @@ -432,7 +510,8 @@ check('lists.ts and _layout.tsx wire the #152 Inbox rules', () => { const reset = client.slice(client.indexOf('export async function initialReset('), client.indexOf('export async function cleanOutbox(')); assert.ok(!/ensureInbox/.test(reset), 'initialReset must not fall back to the fixed Inbox'); assert.match(reset, /if \(!hasInbox\) \{\s*(\/\/[^\n]*\s*)*const id = randomUUID\(\);/); - assert.match(reset, /await writeOutboxEntry\('list', id, 'create', inbox\);/); + // #165: written whatever syncEnabled, since initialReset runs before sync is on + assert.match(reset, /await queueOutboxEntry\('list', id, 'create', inbox\);/); assert.match(reset, /const inbox = \{[^}]*isInbox: true \}/); // Callers await the Inbox read from the database assert.match(read('app/(tabs)/index.tsx'), /await getInboxId\(\)/); diff --git a/tests/syncRules.test.mjs b/tests/syncRules.test.mjs index af7e60c..7dcad55 100644 --- a/tests/syncRules.test.mjs +++ b/tests/syncRules.test.mjs @@ -33,6 +33,7 @@ import { LOCAL_INBOX_ID, pickInboxId, planInboxRepair, + firstSyncChoice, } from '../src/services/syncRules.ts'; const ID = '11111111-1111-4111-8111-111111111111'; @@ -845,3 +846,46 @@ test('planInboxRepair: the repaired outbox of a split device is pushed without a assert.deepEqual(server.state.tasks.get(T4), { listId: SERVER_INBOX, deleted: true }); assert.deepEqual([...server.state.links], [`${T1}:${TAG_A}`]); }); + +// --------------------------------------------------------------------------- +// firstSyncChoice: no merge across accounts (#165) +// --------------------------------------------------------------------------- + +const ACCOUNT_A = 'logto-sub-account-a'; +const ACCOUNT_B = 'logto-sub-account-b'; +const SERVER_INBOX_ID = '33333333-3333-4333-8333-333333333333'; + +test('firstSyncChoice: table of the first-sync choice', () => { + const rows = [ + // [case, dataOwnerId, signedInId, localInboxId, expected] + ['never synced, fixed Inbox', null, ACCOUNT_B, LOCAL_INBOX_ID, 'merge-or-reset'], + ['never synced, no Inbox yet', null, ACCOUNT_B, null, 'merge-or-reset'], + ['same account', ACCOUNT_A, ACCOUNT_A, SERVER_INBOX_ID, 'merge-or-reset'], + ['other account', ACCOUNT_A, ACCOUNT_B, SERVER_INBOX_ID, 'reset-only'], + ['unknown owner, fixed Inbox', null, ACCOUNT_A, LOCAL_INBOX_ID, 'merge-or-reset'], + ['unknown owner, server Inbox', null, ACCOUNT_A, SERVER_INBOX_ID, 'reset-only'], + ]; + for (const [name, dataOwnerId, signedInId, localInboxId, expected] of rows) { + assert.equal(firstSyncChoice({ dataOwnerId, signedInId, localInboxId }), expected, name); + } +}); + +// Regression (#165): sign-out resets userId to null but keeps dataOwnerId. +// A device holding A's data, signed in to B, only offers to load B, whatever +// its Inbox says: comparing to the userId of before the sign-in (null) would +// offer the merge again. +test('firstSyncChoice: data of A, signed in to B gives reset-only (regression)', () => { + const afterSignOut = { dataOwnerId: ACCOUNT_A, userId: null }; + for (const localInboxId of [SERVER_INBOX_ID, LOCAL_INBOX_ID, null]) { + assert.equal( + firstSyncChoice({ dataOwnerId: afterSignOut.dataOwnerId, signedInId: ACCOUNT_B, localInboxId }), + 'reset-only', + String(localInboxId), + ); + } + // Back to A: the choice is offered again + assert.equal( + firstSyncChoice({ dataOwnerId: afterSignOut.dataOwnerId, signedInId: ACCOUNT_A, localInboxId: SERVER_INBOX_ID }), + 'merge-or-reset', + ); +}); diff --git a/tests/syncSchedule.test.mjs b/tests/syncSchedule.test.mjs index 0a3af67..3e4dc11 100644 --- a/tests/syncSchedule.test.mjs +++ b/tests/syncSchedule.test.mjs @@ -13,6 +13,7 @@ import { BUDGET_WINDOW_MS, DEFAULT_RETRY_AFTER_S, REQUEST_BUDGET, + canSync, createSyncScheduler, } from '../src/services/syncSchedule.ts'; import { SYNC_DEBOUNCE_MS, requestSync, setSyncSubscriber } from '../src/services/syncTrigger.ts'; @@ -336,3 +337,93 @@ test('a failing run releases the scheduler', async () => { await s.request(); assert.equal(runs, 2); }); + +// --- Account guard and sign-out push (#165) --- + +const A = 'logto-sub-account-a'; +const B = 'logto-sub-account-b'; + +test('canSync: sync on, and local data of the signed-in account or of an unknown owner', () => { + assert.equal(canSync({ syncEnabled: true, dataOwnerId: A, userId: A }), true); + assert.equal(canSync({ syncEnabled: true, dataOwnerId: null, userId: A }), true, 'device synced before #165'); + assert.equal(canSync({ syncEnabled: true, dataOwnerId: A, userId: B }), false, 'data of another account'); + assert.equal(canSync({ syncEnabled: true, dataOwnerId: A, userId: null }), false, 'signed out'); + assert.equal(canSync({ syncEnabled: false, dataOwnerId: A, userId: A }), false, 'sync off'); + assert.equal(canSync({ syncEnabled: false, dataOwnerId: null, userId: null }), false); +}); + +test('data owner other than the signed-in account: the scheduler refuses every sync', async () => { + const clock = fakeClock(); + const server = fakeServer(clock, { batches: 3 }); + // Even with sync on: the guard reads the owner, not only syncEnabled + const settings = { syncEnabled: true, dataOwnerId: A, userId: B }; + const s = createSyncScheduler({ + now: clock.now, + setTimer: clock.setTimer, + run: server.run, + canRun: () => canSync(settings), + }); + for (let i = 0; i < 5; i++) s.request(); + await clock.advance(5 * BUDGET_WINDOW_MS); + assert.equal(server.runs, 0); + assert.deepEqual(server.requests, [], 'not one request sent under the other account'); + // « Charger ce compte » done: B owns the data + settings.dataOwnerId = B; + s.request(); + await flush(); + assert.equal(server.runs, 1); +}); + +test('reserve: the sign-out push gets one request outside a spent budget', async () => { + const clock = fakeClock(); + const server = fakeServer(clock); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + assert.equal(s.reserve().pushBatches, REQUEST_BUDGET, 'the whole budget when nothing was sent'); + for (let i = 0; i < REQUEST_BUDGET; i++) s.tracker.request(); + const run = s.reserve(); + assert.equal(run.pushBatches, 1, 'one request outside the spent budget'); + // Its request counts in the budget of the next runs + run.request(); + s.request(); + await clock.advance(BUDGET_WINDOW_MS - 1); + assert.equal(server.runs, 0); + await clock.advance(1); + assert.equal(server.runs, 1); +}); + +test('reserve: nothing while a 429 suspends the scheduler', async () => { + const clock = fakeClock(); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: async () => {} }); + s.tracker.rateLimited(20); + const run = s.reserve(); + assert.equal(run.pushBatches, 0); + assert.equal(run.isSuspended(), true); + await clock.advance(20_000); + assert.equal(s.reserve().pushBatches, REQUEST_BUDGET, 'the budget once the Retry-After has passed'); + assert.equal(run.isSuspended(), false); +}); + +test('the sign-out push never runs alongside a sync, and a sync waits for its end', async () => { + const clock = fakeClock(); + const server = fakeServer(clock, { duration: 1000 }); + const s = createSyncScheduler({ now: clock.now, setTimer: clock.setTimer, run: server.run }); + s.request(); + await flush(); + assert.equal(server.runs, 1); + // pushBeforeSignOut: first-sync state, then a reserved run + let pushing = false; + s.beginInitialSync().then(() => { + pushing = true; + }); + await flush(); + assert.equal(pushing, false, 'waits for the sync in flight'); + await clock.advance(1000); + assert.equal(pushing, true); + assert.equal(server.active, 0, 'no sync during the sign-out push'); + s.request(); + await clock.advance(BUDGET_WINDOW_MS); + assert.equal(server.runs, 1, 'no sync before the push ends'); + s.endInitialSync(); + await flush(); + assert.equal(server.runs, 2); +});