Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

test(app): remove storage migration and auth session tests

Hampusd12865998fd8
diff --git a/fluxer_app/src/features/platform/state/AuthSession.test.ts b/fluxer_app/src/features/platform/state/AuthSession.test.ts
deleted file mode 100644
index b8b8ea287..000000000
--- a/fluxer_app/src/features/platform/state/AuthSession.test.ts
+++ /dev/null
@@ -1,1145 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {
- CommittedRuntimeConfig,
- PreparedRuntimeConfig,
- RuntimeConfigSnapshot,
-} from '@app/features/app/state/RuntimeConfig';
-import {installHarnessBootstrap} from '@app/features/auth/state/__fixtures__/AccountSwitchHarness';
-import type {
- AccountPresenceIntent,
- QualifiedStoredAccount,
- StoredAccount,
- StoredAccountList,
- StoredAccountSource,
- UserData,
-} from '@app/features/auth/state/AccountStorageContract';
-import type {
- StoredAccountInventory,
- StoredAccountInventoryReplacement,
-} from '@app/features/auth/state/StoredAccountInventoryContract';
-import {StoredAccountInventoryReplacementConflictError} from '@app/features/auth/state/StoredAccountInventoryContract';
-import {
- classifyStoredAccount,
- createStoredAccountInventory,
- inventoryEntriesHaveSameRevision,
- inventoryEntryStorageKey,
- normalizeStoredAccountInventoryReplacement,
-} from '@app/features/auth/state/StoredAccountInventoryPolicy';
-import type {AuthSessionDependencies, AuthSessionManager} from '@app/features/platform/state/AuthSession';
-import type {AuthSessionTransitionContext} from '@app/features/platform/state/auth_session/AuthSessionTransitionGate';
-import type {ResetClientStateOptions} from '@app/features/platform/state/ResetClientState';
-import {HttpError} from '@app/features/platform/types/EndpointError';
-import type {UserSettingsAccountTransitionCheckpoint} from '@app/features/user/state/UserSettings';
-import type {MessageDescriptor} from '@lingui/core';
-import {autorun, configure} from 'mobx';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
-
-const desktopRuntime = vi.hoisted(() => ({required: false}));
-
-vi.mock('@lingui/core/macro', () => ({msg: (descriptor: MessageDescriptor) => descriptor}));
-vi.mock('@app/features/app/state/DesktopRuntimeTransaction', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@app/features/app/state/DesktopRuntimeTransaction')>();
- return {...actual, requiresDesktopRuntimeTransaction: () => desktopRuntime.required};
-});
-vi.mock('@app/features/gateway/transport/GatewaySessionPool', () => ({
- default: {
- foregroundConnection: {
- logout: () => undefined,
- startSession: () => undefined,
- sendInvisiblePresenceForCurrentSession: () => undefined,
- },
- },
-}));
-
-vi.mock('@app/features/presence/state/LocalPresence', () => ({
- default: {captureIntent: () => null, restoreIntent: () => undefined},
-}));
-
-vi.mock('@app/features/ui/state/LayerManager', () => ({default: {closeAll: () => undefined}}));
-
-installHarnessBootstrap();
-
-const {default: RuntimeConfig} = await import('@app/features/app/state/RuntimeConfig');
-const {AccountInstanceMismatchError, createSessionManager, SessionExpiredError, SessionState} = await import(
- '@app/features/platform/state/AuthSession'
-);
-const {AuthSessionStorageKey} = await import('@app/features/platform/state/auth_session/AuthSessionStorage');
-const {DurableSessionCredentialMirror} = await import(
- '@app/features/platform/state/auth_session/SessionCredentialMirror'
-);
-const {GATEWAY_PREBOOT_SESSION_STORAGE_KEY} = await import('@app/features/platform/state/PrebootMirror');
-const {default: AppStorage, UNAUTHENTICATED_APP_STORAGE_SCOPE} = await import(
- '@app/features/platform/state/PersistentStorage'
-);
-const {AccountScopedWork} = await import('@app/features/platform/state/AccountScopedWork');
-const {default: DesktopRuntimeTransactions} = await import('@app/features/app/state/DesktopRuntimeTransaction');
-
-const PRIMARY: RuntimeConfigSnapshot = RuntimeConfig.getSnapshot();
-const FOREIGN: RuntimeConfigSnapshot = {...PRIMARY, apiEndpoint: 'https://foreign.test/api'};
-const BLANK: RuntimeConfigSnapshot = {...PRIMARY, apiEndpoint: ''};
-
-const PRIMARY_KEY = 'https://primary.test/api';
-const FOREIGN_KEY = 'https://foreign.test/api';
-
-const NOOP_AUTH_SESSION_TRANSITION: AuthSessionTransitionContext = {
- notifyLogout: async () => undefined,
-};
-
-type AccountStorageDep = AuthSessionDependencies['accountStorage'];
-
-interface StashCall {
- userId: string;
- token: string | null;
- userData?: UserData;
- instance?: RuntimeConfigSnapshot;
- presenceIntent?: AccountPresenceIntent | null;
- mirroredUserId: string | null;
-}
-
-function instanceKeyOf(instance: RuntimeConfigSnapshot | undefined): string | null {
- if (instance === undefined || instance.apiEndpoint.length === 0) {
- return null;
- }
- return instance.apiEndpoint;
-}
-
-class FakeAccountStorage implements AccountStorageDep {
- readonly records = new Map<string, StoredAccount>();
- readonly stashes: Array<StashCall> = [];
- readonly deletes: Array<string> = [];
- source: StoredAccountSource = 'idb';
- listError: Error | null = null;
- stashError: Error | null = null;
-
- seed(record: Partial<StoredAccount> & {userId: string}): StoredAccount {
- const instance = record.instance;
- const instanceKey = instanceKeyOf(instance);
- const stored: StoredAccount = {
- userId: record.userId,
- token: record.token === undefined ? `token-${record.userId}` : record.token,
- userData: record.userData,
- presenceIntent: record.presenceIntent ?? null,
- localStorageData: {},
- managedStorageData: {},
- lastActive: record.lastActive ?? 1,
- instance,
- isValid: record.isValid,
- storageKey: record.storageKey ?? (instanceKey === null ? undefined : `${instanceKey}::${record.userId}`),
- };
- this.records.set(stored.storageKey ?? stored.userId, stored);
- return stored;
- }
-
- private findByUserId(userId: string): StoredAccount | undefined {
- for (const record of this.records.values()) {
- if (record.userId === userId) {
- return record;
- }
- }
- return undefined;
- }
-
- async getAllAccounts(): Promise<StoredAccountList> {
- if (this.listError !== null) {
- throw this.listError;
- }
- return {records: [...this.records.values()].map((record) => ({...record})), source: this.source};
- }
-
- async getAccountInventory(): Promise<StoredAccountInventory> {
- if (this.listError !== null) {
- throw this.listError;
- }
- return createStoredAccountInventory(
- this.source,
- [...this.records.entries()].map(([storageKey, record]) =>
- classifyStoredAccount({
- value: record,
- authoritativeStorageKey: record.storageKey ?? storageKey,
- source: this.source,
- }),
- ),
- );
- }
-
- async replaceInventoryEntry(request: StoredAccountInventoryReplacement): Promise<QualifiedStoredAccount> {
- const storageKey = inventoryEntryStorageKey(request.expected);
- const current = this.records.get(storageKey);
- if (current === undefined) {
- throw new StoredAccountInventoryReplacementConflictError(storageKey, 'The stored account no longer exists');
- }
- const classified = classifyStoredAccount({
- value: current,
- authoritativeStorageKey: storageKey,
- source: this.source,
- });
- if (
- (classified.kind !== 'ready' && classified.kind !== 'runtime-recovery') ||
- !inventoryEntriesHaveSameRevision(classified, request.expected)
- ) {
- throw new StoredAccountInventoryReplacementConflictError(storageKey, 'The stored account changed');
- }
- const replacement = normalizeStoredAccountInventoryReplacement(request);
- this.records.set(storageKey, replacement);
- return replacement;
- }
-
- async stashAccountData(
- userId: string,
- token: string | null,
- userData?: UserData,
- instance?: RuntimeConfigSnapshot,
- presenceIntent?: AccountPresenceIntent | null,
- ): Promise<void> {
- this.stashes.push({
- userId,
- token,
- userData,
- instance,
- presenceIntent,
- mirroredUserId: window.localStorage.getItem(AuthSessionStorageKey.UserId),
- });
- if (this.stashError !== null) {
- throw this.stashError;
- }
- const existing = this.findByUserId(userId);
- this.seed({
- userId,
- token,
- userData: userData ?? existing?.userData,
- presenceIntent: presenceIntent ?? existing?.presenceIntent,
- lastActive: 2,
- instance,
- isValid: existing?.isValid,
- });
- }
-
- private findByAccountKey(accountKey: string): StoredAccount | undefined {
- return this.records.get(accountKey) ?? this.findByUserId(accountKey);
- }
-
- async restoreAccountData(accountKey: string): Promise<StoredAccount | null> {
- const record = this.findByAccountKey(accountKey);
- if (record === undefined) {
- return null;
- }
- return {...record};
- }
-
- async upsertAccount(record: StoredAccount, currentInstance: RuntimeConfigSnapshot): Promise<void> {
- this.seed({...record, instance: record.instance ?? currentInstance});
- }
-
- async deleteAccount(accountKey: string): Promise<void> {
- this.deletes.push(accountKey);
- const record = this.findByAccountKey(accountKey);
- if (record === undefined) {
- return;
- }
- this.records.delete(record.storageKey ?? record.userId);
- }
-
- async updateAccountValidity(accountKey: string, isValid: boolean): Promise<void> {
- const record = this.findByAccountKey(accountKey);
- if (record !== undefined) {
- record.isValid = isValid;
- }
- }
-}
-
-interface Harness {
- session: AuthSessionManager;
- accountStorage: FakeAccountStorage;
- activatedScopes: Array<string | null>;
- deletedScopes: Array<string>;
- clientStateResets: Array<ResetClientStateOptions>;
- appliedSnapshots: Array<RuntimeConfigSnapshot>;
- gatewayTeardowns: Array<string>;
- validTokens: Map<string, string>;
-}
-
-function createHarness(overrides: Partial<AuthSessionDependencies> = {}): Harness {
- const accountStorage = new FakeAccountStorage();
- const activatedScopes: Array<string | null> = [];
- const deletedScopes: Array<string> = [];
- const clientStateResets: Array<ResetClientStateOptions> = [];
- const appliedSnapshots: Array<RuntimeConfigSnapshot> = [];
- const gatewayTeardowns: Array<string> = [];
- const validTokens = new Map<string, string>();
- let currentInstance: RuntimeConfigSnapshot | null = PRIMARY;
- let storageScope = UNAUTHENTICATED_APP_STORAGE_SCOPE;
- let clock = 100;
- const mirrorGatewayPrebootSession = (sessionPresent: boolean): void => {
- if (sessionPresent) {
- window.localStorage.setItem(GATEWAY_PREBOOT_SESSION_STORAGE_KEY, '1');
- } else {
- window.localStorage.removeItem(GATEWAY_PREBOOT_SESSION_STORAGE_KEY);
- }
- };
- const credentialMirror = new DurableSessionCredentialMirror(AppStorage, mirrorGatewayPrebootSession);
- const userSettingsCheckpoint = Object.freeze({}) as UserSettingsAccountTransitionCheckpoint;
- const prepareRuntimeSnapshot = async (snapshot: RuntimeConfigSnapshot): Promise<PreparedRuntimeConfig> => ({
- snapshot,
- transportApiEndpoint: snapshot.apiEndpoint,
- expectedGeneration: 0,
- desktopRuntime: null,
- });
- const commitRuntimeSnapshot = async (prepared: PreparedRuntimeConfig): Promise<CommittedRuntimeConfig> => ({
- ...prepared,
- previousRuntime:
- currentInstance === null ? null : {snapshot: currentInstance, transportApiEndpoint: currentInstance.apiEndpoint},
- activeRuntime: {snapshot: prepared.snapshot, transportApiEndpoint: prepared.transportApiEndpoint},
- desktopRuntime: null,
- publication: {phase: 'committed'},
- });
- const {
- activateStorageScope: activateStorageScopeOverride,
- credentialMirror: credentialMirrorOverride,
- ...remainingOverrides
- } = overrides;
- const deps: AuthSessionDependencies = {
- accountStorage,
- credentialMirror: credentialMirrorOverride ?? credentialMirror,
- http: {
- get: async (_url, options) => {
- const headers = options.headers ?? {};
- const token = headers.Authorization ?? '';
- const userId = validTokens.get(token);
- if (userId === undefined) {
- throw new HttpError({method: 'GET', path: '/users/@me', status: 401});
- }
- return {body: {id: userId} as never};
- },
- },
- getRuntimeSnapshot: () => currentInstance,
- resolveRuntimeEndpoint: async (input) => {
- const snapshot = input === FOREIGN_KEY ? FOREIGN : PRIMARY;
- return {snapshot, instanceKey: input, productName: 'Fluxer'};
- },
- getStorageScope: () => storageScope,
- resolveAndPrepareRuntimeSnapshot: prepareRuntimeSnapshot,
- prepareRuntimeSnapshot,
- commitRuntimeSnapshot,
- publishRuntimeSnapshot: (committed) => {
- const snapshot = committed.snapshot;
- appliedSnapshots.push(snapshot);
- currentInstance = snapshot;
- },
- rollbackPublishedRuntime: (committed) => {
- currentInstance = committed.previousRuntime?.snapshot ?? null;
- },
- finalizeRuntimeSnapshot: async () => undefined,
- rollbackRuntimeSnapshot: async () => undefined,
- abortRuntimeSnapshot: async () => undefined,
- deactivateRuntime: async () => {
- currentInstance = null;
- },
- allowsCrossInstanceSwitching: () => false,
- activateStorageScope: async (accountKey) => {
- if (activateStorageScopeOverride === undefined) {
- activatedScopes.push(accountKey);
- } else {
- await activateStorageScopeOverride(accountKey);
- }
- storageScope = accountKey ?? UNAUTHENTICATED_APP_STORAGE_SCOPE;
- },
- deleteAccountStorageScope: async (accountKey) => {
- deletedScopes.push(accountKey);
- },
- resetClientState: async (options) => {
- clientStateResets.push(options);
- window.localStorage.clear();
- },
- closeLayers: () => undefined,
- clearSudoToken: () => undefined,
- sendInvisiblePresence: () => undefined,
- cleanupGatewaySession: (reason) => {
- gatewayTeardowns.push(reason);
- },
- resetSyncedUserSettings: async () => undefined,
- captureSyncedUserSettingsCheckpoint: async () => userSettingsCheckpoint,
- restoreSyncedUserSettingsCheckpoint: async () => undefined,
- accountScopedWork: {
- runSuspended: async (_reason, operation) => operation(NOOP_AUTH_SESSION_TRANSITION),
- },
- captureLocalPresenceIntent: () => null,
- restoreLocalPresenceIntent: () => undefined,
- now: () => {
- clock += 1;
- return clock;
- },
- ...remainingOverrides,
- };
- return {
- session: createSessionManager(deps),
- accountStorage,
- activatedScopes,
- deletedScopes,
- clientStateResets,
- appliedSnapshots,
- gatewayTeardowns,
- validTokens,
- };
-}
-
-function seedCredentialMirror(accountKey: string | null, userId: string | null, token: string | null): void {
- if (accountKey !== null) {
- window.localStorage.setItem(AuthSessionStorageKey.ActiveAccountKey, accountKey);
- }
- if (userId !== null) {
- window.localStorage.setItem(AuthSessionStorageKey.UserId, userId);
- }
- if (token !== null) {
- window.localStorage.setItem(AuthSessionStorageKey.Token, token);
- }
-}
-
-function expectCredentialMirrorIntact(userId: string, token: string): void {
- expect(window.localStorage.getItem(AuthSessionStorageKey.UserId)).toBe(userId);
- expect(window.localStorage.getItem(AuthSessionStorageKey.Token)).toBe(token);
-}
-
-beforeEach(() => {
- window.localStorage.clear();
-});
-
-afterEach(() => {
- vi.restoreAllMocks();
- window.localStorage.clear();
-});
-
-describe('H1 the stored-token equality check', () => {
- test('a record whose token diverged from the mirror no longer clears the session', async () => {
- const harness = createHarness();
- harness.accountStorage.seed({
- userId: '100',
- token: 'stale-record-token',
- instance: PRIMARY,
- userData: {username: 'ada', discriminator: '0001'},
- });
- seedCredentialMirror(`${PRIMARY_KEY}::100`, '100', 'rotated-token');
-
- await harness.session.initialize();
-
- expect(harness.session.isAuthenticated).toBe(true);
- expect(harness.session.userId).toBe('100');
- expect(harness.session.token).toBe('rotated-token');
- expect(harness.session.currentAccount?.userData?.username).toBe('ada');
- expectCredentialMirrorIntact('100', 'rotated-token');
- });
-
- test('a record with no token is skipped rather than treated as a session', async () => {
- const harness = createHarness();
- harness.accountStorage.seed({userId: '100', token: null, instance: PRIMARY});
- seedCredentialMirror(`${PRIMARY_KEY}::100`, '100', 'mirror-token');
-
- await harness.session.initialize();
-
- expect(harness.session.isAuthenticated).toBe(true);
- expect(harness.session.token).toBe('mirror-token');
- expectCredentialMirrorIntact('100', 'mirror-token');
- });
-
- test('login persists the active pointer before the account record is stashed', async () => {
- const harness = createHarness();
- harness.accountStorage.stashError = new Error('IndexedDB is gone');
-
- await expect(harness.session.login({token: 'token-100', userId: '100', runtimeSnapshot: PRIMARY})).rejects.toThrow(
- 'IndexedDB is gone',
- );
-
- expectCredentialMirrorIntact('100', 'token-100');
- expect(window.localStorage.getItem(AuthSessionStorageKey.ActiveAccountKey)).toBe(`${PRIMARY_KEY}::100`);
- expect(window.localStorage.getItem(GATEWAY_PREBOOT_SESSION_STORAGE_KEY)).toBe('1');
- });
-});
-
-describe('H2 the load-time instance filter', () => {
- test('a blank current instance no longer drops every stored account', async () => {
- const harness = createHarness({getRuntimeSnapshot: () => BLANK});
- harness.accountStorage.seed({userId: '100', instance: PRIMARY});
- harness.accountStorage.seed({userId: '200', instance: PRIMARY, lastActive: 5});
- seedCredentialMirror(`${PRIMARY_KEY}::100`, '100', 'token-100');
-
- await harness.session.initialize();
-
- expect(harness.session.accounts).toHaveLength(2);
- expect(harness.session.isAuthenticated).toBe(true);
- expect(harness.session.currentAccountKey).toBe(`${PRIMARY_KEY}::100`);
- expectCredentialMirrorIntact('100', 'token-100');
- });
-
- test('a foreign-instance row is listed rather than dropped, and refused at switch time', async () => {
- const harness = createHarness();
- harness.accountStorage.seed({userId: '100', instance: PRIMARY});
- harness.accountStorage.seed({userId: '200', instance: FOREIGN});
- seedCredentialMirror(`${PRIMARY_KEY}::100`, '100', 'token-100');
- harness.validTokens.set('token-200', '200');
-
- await harness.session.initialize();
-
- expect(harness.session.accounts.map((account) => account.storageKey).sort()).toEqual([
- `${FOREIGN_KEY}::200`,
- `${PRIMARY_KEY}::100`,
- ]);
- await expect(harness.session.switchAccount(`${FOREIGN_KEY}::200`)).rejects.toBeInstanceOf(
- AccountInstanceMismatchError,
- );
- expect(harness.gatewayTeardowns).toHaveLength(0);
- expectCredentialMirrorIntact('100', 'token-100');
- });
-});
-
-describe('H3 storage inventory authority', () => {
- test('a missing desktop account is never reconstructed from the raw mirror', async () => {
- const harness = createHarness();
- harness.accountStorage.source = 'desktop';
- seedCredentialMirror(`${PRIMARY_KEY}::100`, '100', 'token-100');
-
- await harness.session.initialize();
-
- expect(harness.session.isAuthenticated).toBe(false);
- expect(harness.session.currentAccountKey).toBeNull();
- expectCredentialMirrorIntact('100', 'token-100');
- });
-
- test('an unresolved IDB pointer never clears the mirror', async () => {
- const harness = createHarness();
- seedCredentialMirror(`${PRIMARY_KEY}::100`, '100', null);
-
- await harness.session.initialize();
-
- expect(harness.session.isAuthenticated).toBe(false);
- expect(window.localStorage.getItem(AuthSessionStorageKey.UserId)).toBe('100');
- expect(window.localStorage.getItem(AuthSessionStorageKey.ActiveAccountKey)).toBe(`${PRIMARY_KEY}::100`);
- });
-});
-
-describe('H4 a throwing boot step', () => {
- test('an account-store read failure is observable and leaves the mirror untouched', async () => {
- const harness = createHarness();
- harness.accountStorage.listError = new Error('IndexedDB open timed out');
- seedCredentialMirror(`${PRIMARY_KEY}::100`, '100', 'token-100');
-
- await expect(harness.session.initialize()).rejects.toThrow('IndexedDB open timed out');
-
- expect(harness.session.state).toBe(SessionState.Error);
- expectCredentialMirrorIntact('100', 'token-100');
- });
-});
-
-describe('H5 storage that throws on read', () => {
- test('initialization rejects and deletes nothing when the mirror cannot be read', async () => {
- const harness = createHarness({
- credentialMirror: {
- read: () => {
- throw new Error('SecurityError');
- },
- write: () => undefined,
- persist: async () => undefined,
- },
- });
- harness.accountStorage.seed({userId: '100', instance: PRIMARY});
- seedCredentialMirror(`${PRIMARY_KEY}::100`, '100', 'token-100');
-
- await expect(harness.session.initialize()).rejects.toThrow('SecurityError');
-
- expect(harness.session.state).toBe(SessionState.Error);
- expectCredentialMirrorIntact('100', 'token-100');
- });
-});
-
-describe('H6 a corrupt active-account key', () => {
- test('an unparseable key is rejected without redirecting the session', async () => {
- const harness = createHarness();
- harness.accountStorage.seed({userId: '100', instance: PRIMARY});
- seedCredentialMirror(' not-a-key', '100', 'token-100');
-
- await harness.session.initialize();
-
- expect(harness.session.currentAccountKey).toBeNull();
- expect(harness.session.isAuthenticated).toBe(false);
- expectCredentialMirrorIntact('100', 'token-100');
- });
-
- test('a key for an account that is gone never selects the most recently active record', async () => {
- const harness = createHarness();
- harness.accountStorage.seed({userId: '100', instance: PRIMARY, lastActive: 1});
- harness.accountStorage.seed({userId: '200', instance: PRIMARY, lastActive: 9});
- seedCredentialMirror(`${PRIMARY_KEY}::999`, null, null);
-
- await harness.session.initialize();
-
- expect(harness.session.currentAccountKey).toBeNull();
- expect(window.localStorage.getItem(AuthSessionStorageKey.ActiveAccountKey)).toBe(`${PRIMARY_KEY}::999`);
- });
-
- test('a pointer whose account is gone never adopts an unrelated account over the raw mirror', async () => {
- const harness = createHarness();
- harness.accountStorage.seed({userId: '200', token: 'token-200', instance: PRIMARY, lastActive: 9});
- seedCredentialMirror(`${PRIMARY_KEY}::100`, '100', 'token-100');
-
- await harness.session.initialize();
-
- expect(harness.session.userId).toBeNull();
- expect(harness.session.token).toBeNull();
- expect(harness.session.isAuthenticated).toBe(false);
- expectCredentialMirrorIntact('100', 'token-100');
- });
-
- test('a pointer that resolves to nothing at all still leaves the mirror in place', async () => {
- const harness = createHarness();
- seedCredentialMirror(`${PRIMARY_KEY}::100`, '100', null);
-
- await harness.session.initialize();
-
- expect(harness.session.isAuthenticated).toBe(false);
- expect(window.localStorage.getItem(AuthSessionStorageKey.UserId)).toBe('100');
- });
-
- test('no pointer at all is a clean signed-out boot, not a resurrection of the newest record', async () => {
- const harness = createHarness();
- harness.accountStorage.seed({userId: '100', instance: PRIMARY, lastActive: 9});
-
- await harness.session.initialize();
-
- expect(harness.session.isAuthenticated).toBe(false);
- expect(harness.session.accounts).toHaveLength(1);
- });
-});
-
-describe('H7 a failing scope activation', () => {
- test('a rejecting scope activation never costs the caller its credentials', async () => {
- const harness = createHarness({
- activateStorageScope: async () => {
- throw new Error('scope activation failed');
- },
- });
-
- await expect(harness.session.login({token: 'token-100', userId: '100', runtimeSnapshot: PRIMARY})).rejects.toThrow(
- 'scope activation failed',
- );
-
- expectCredentialMirrorIntact('100', 'token-100');
- expect(harness.accountStorage.records.get(`${PRIMARY_KEY}::100`)?.token).toBe('token-100');
- });
-});
-
-describe('H10 logout', () => {
- test('logout clears the pointer, the preboot marker and the account scope', async () => {
- const harness = createHarness();
- await harness.session.login({token: 'token-100', userId: '100', runtimeSnapshot: PRIMARY});
- harness.activatedScopes.length = 0;
-
- await harness.session.logout();
-
- expect(window.localStorage.getItem(AuthSessionStorageKey.Token)).toBeNull();
- expect(window.localStorage.getItem(AuthSessionStorageKey.UserId)).toBeNull();
- expect(window.localStorage.getItem(AuthSessionStorageKey.ActiveAccountKey)).toBeNull();
- expect(window.localStorage.getItem(GATEWAY_PREBOOT_SESSION_STORAGE_KEY)).toBeNull();
- expect(harness.activatedScopes).toEqual([null]);
- expect(harness.clientStateResets).toEqual([{reason: 'logout', keepDrafts: false}]);
- expect(harness.accountStorage.records.size).toBe(0);
- });
-
- test('a scope wipe that fails still drops the stored credential', async () => {
- const harness = createHarness({
- resetClientState: async () => {
- throw new Error('storage unavailable');
- },
- });
- harness.validTokens.set('token-100', '100');
- await harness.session.login({token: 'token-100', userId: '100', runtimeSnapshot: PRIMARY});
-
- await expect(harness.session.logout()).rejects.toThrow(/storage unavailable/u);
-
- expect(harness.accountStorage.records.size).toBe(0);
- expect(harness.session.getAccount(`${PRIMARY_KEY}::100`)).toBeNull();
- });
-});
-
-describe('H11 sticky account validity', () => {
- test('stashing the current account does not resurrect an invalidated account', async () => {
- const harness = createHarness();
- harness.validTokens.set('token-100', '100');
- harness.validTokens.set('token-200', '200');
- await harness.session.login({token: 'token-100', userId: '100', runtimeSnapshot: PRIMARY});
- await harness.session.login({token: 'token-200', userId: '200', runtimeSnapshot: PRIMARY});
- harness.session.markAccountInvalid(`${PRIMARY_KEY}::200`);
-
- await harness.session.stashCurrentAccount();
-
- expect(harness.session.getAccount(`${PRIMARY_KEY}::200`)?.isValid).toBe(false);
- expectCredentialMirrorIntact('200', 'token-200');
- });
-});
-
-describe('R14 the switch transaction', () => {
- test('a failed validation is a no-op: the gateway stays up and no scope is activated', async () => {
- const harness = createHarness();
- harness.validTokens.set('token-100', '100');
- await harness.session.login({token: 'token-100', userId: '100', runtimeSnapshot: PRIMARY});
- harness.accountStorage.seed({userId: '200', token: 'token-200', instance: PRIMARY});
- await harness.session.reset();
- await harness.session.initialize();
- harness.activatedScopes.length = 0;
- harness.appliedSnapshots.length = 0;
- harness.gatewayTeardowns.length = 0;
- harness.accountStorage.stashes.length = 0;
-
- await expect(harness.session.switchAccount(`${PRIMARY_KEY}::200`)).rejects.toBeInstanceOf(SessionExpiredError);
-
- expect(harness.gatewayTeardowns).toHaveLength(0);
- expect(harness.activatedScopes).toHaveLength(0);
- expect(harness.accountStorage.stashes).toHaveLength(0);
- expect(harness.session.currentAccountKey).toBe(`${PRIMARY_KEY}::100`);
- expect(harness.session.getAccount(`${PRIMARY_KEY}::200`)?.isValid).toBe(false);
- expectCredentialMirrorIntact('100', 'token-100');
- });
-
- test('the target keeps its own instance snapshot and its own scope across a cross-instance switch', async () => {
- const harness = createHarness({allowsCrossInstanceSwitching: () => true});
- harness.validTokens.set('token-100', '100');
- harness.validTokens.set('token-200', '200');
- await harness.session.login({token: 'token-100', userId: '100', runtimeSnapshot: PRIMARY});
- harness.accountStorage.seed({userId: '200', token: 'token-200', instance: FOREIGN});
- await harness.session.reset();
- await harness.session.initialize();
- harness.activatedScopes.length = 0;
- harness.appliedSnapshots.length = 0;
-
- await harness.session.switchAccount(`${FOREIGN_KEY}::200`);
-
- expect(harness.accountStorage.records.get(`${FOREIGN_KEY}::200`)?.instance?.apiEndpoint).toBe(FOREIGN.apiEndpoint);
- expect(harness.accountStorage.records.get(`${PRIMARY_KEY}::100`)?.instance?.apiEndpoint).toBe(PRIMARY.apiEndpoint);
- expect(harness.activatedScopes).toEqual([`${FOREIGN_KEY}::200`]);
- expect(harness.appliedSnapshots.map((snapshot) => snapshot.apiEndpoint)).toEqual([FOREIGN.apiEndpoint]);
- expect(harness.session.currentAccountKey).toBe(`${FOREIGN_KEY}::200`);
- expectCredentialMirrorIntact('200', 'token-200');
- });
-
- test('the target record is stashed only after the mirror already names the target', async () => {
- const harness = createHarness();
- harness.validTokens.set('token-100', '100');
- harness.validTokens.set('token-200', '200');
- await harness.session.login({token: 'token-100', userId: '100', runtimeSnapshot: PRIMARY});
- harness.accountStorage.seed({userId: '200', token: 'token-200', instance: PRIMARY});
- await harness.session.reset();
- await harness.session.initialize();
- harness.accountStorage.stashes.length = 0;
-
- await harness.session.switchAccount(`${PRIMARY_KEY}::200`);
-
- expect(harness.accountStorage.stashes.map((call) => [call.userId, call.mirroredUserId])).toEqual([
- ['100', '100'],
- ['200', '200'],
- ]);
- });
-
- test('the switch stashes the source account under the source instance', async () => {
- const harness = createHarness({allowsCrossInstanceSwitching: () => true});
- harness.validTokens.set('token-100', '100');
- harness.validTokens.set('token-200', '200');
- await harness.session.login({token: 'token-100', userId: '100', runtimeSnapshot: PRIMARY});
- harness.accountStorage.seed({userId: '200', token: 'token-200', instance: FOREIGN});
- await harness.session.reset();
- await harness.session.initialize();
- harness.accountStorage.stashes.length = 0;
-
- await harness.session.switchAccount(`${FOREIGN_KEY}::200`);
-
- expect(harness.accountStorage.stashes.map((call) => [call.userId, call.instance?.apiEndpoint])).toEqual([
- ['100', PRIMARY.apiEndpoint],
- ['200', FOREIGN.apiEndpoint],
- ]);
- });
-});
-
-describe('the active account pointer', () => {
- test('persisting it writes the account key, both raw mirror keys and the preboot marker', async () => {
- const harness = createHarness();
-
- await harness.session.login({token: 'token-100', userId: '100', runtimeSnapshot: PRIMARY});
-
- expect(window.localStorage.getItem(AuthSessionStorageKey.ActiveAccountKey)).toBe(`${PRIMARY_KEY}::100`);
- expect(window.localStorage.getItem(AuthSessionStorageKey.Token)).toBe('token-100');
- expect(window.localStorage.getItem(AuthSessionStorageKey.UserId)).toBe('100');
- expect(window.localStorage.getItem(GATEWAY_PREBOOT_SESSION_STORAGE_KEY)).toBe('1');
- });
-
- test('a 4004 close clears the pointer and the preboot marker', async () => {
- const harness = createHarness();
- await harness.session.login({token: 'token-100', userId: '100', runtimeSnapshot: PRIMARY});
-
- await harness.session.handleConnectionClosed(4004);
-
- expect(window.localStorage.getItem(AuthSessionStorageKey.Token)).toBeNull();
- expect(window.localStorage.getItem(AuthSessionStorageKey.UserId)).toBeNull();
- expect(window.localStorage.getItem(AuthSessionStorageKey.ActiveAccountKey)).toBeNull();
- expect(window.localStorage.getItem(GATEWAY_PREBOOT_SESSION_STORAGE_KEY)).toBeNull();
- });
-
- test('a token rotation refreshes the mirror without moving the account key', async () => {
- const harness = createHarness();
- await harness.session.login({token: 'token-100', userId: '100', runtimeSnapshot: PRIMARY});
-
- await harness.session.setToken('rotated-token');
-
- expect(window.localStorage.getItem(AuthSessionStorageKey.Token)).toBe('rotated-token');
- expect(window.localStorage.getItem(AuthSessionStorageKey.ActiveAccountKey)).toBe(`${PRIMARY_KEY}::100`);
- expect(window.localStorage.getItem(AuthSessionStorageKey.UserId)).toBe('100');
- });
-});
-
-describe('account keys', () => {
- test('two accounts sharing a user id on different instances are both addressable', async () => {
- const harness = createHarness();
- harness.accountStorage.seed({userId: '100', token: 'token-primary', instance: PRIMARY, lastActive: 1});
- harness.accountStorage.seed({userId: '100', token: 'token-foreign', instance: FOREIGN, lastActive: 5});
- seedCredentialMirror(`${FOREIGN_KEY}::100`, '100', 'token-foreign');
-
- await harness.session.initialize();
-
- expect(harness.session.accounts).toHaveLength(2);
- expect(harness.session.currentAccountKey).toBe(`${FOREIGN_KEY}::100`);
- expect(harness.session.getAccount(`${PRIMARY_KEY}::100`)?.token).toBe('token-primary');
- });
-
- test('accounts stay sorted by last activity, newest first', async () => {
- const harness = createHarness();
- harness.accountStorage.seed({userId: '100', instance: PRIMARY, lastActive: 1});
- harness.accountStorage.seed({userId: '200', instance: PRIMARY, lastActive: 9});
- harness.accountStorage.seed({userId: '300', instance: PRIMARY, lastActive: 5});
-
- await harness.session.initialize();
-
- expect(harness.session.accounts.map((account) => account.userId)).toEqual(['200', '300', '100']);
- });
-});
-
-describe('H12 in-flight work from the outgoing account', () => {
- test('a response resolving after the switch is refused and leaves the mirror naming the incoming account', async () => {
- let releaseResponse = (): void => undefined;
- let responseIsInFlight = false;
- const response = new Promise<void>((resolve) => {
- releaseResponse = resolve;
- });
- const applied: Array<string> = [];
- const harness = createHarness({
- accountScopedWork: {
- runSuspended: (reason, operation) =>
- AccountScopedWork.runSuspended(reason, () => operation(NOOP_AUTH_SESSION_TRANSITION)),
- },
- });
- const unregisterRelease = AccountScopedWork.registerCancellation(() => {
- if (responseIsInFlight) {
- releaseResponse();
- }
- });
- try {
- harness.validTokens.set('token-100', '100');
- harness.validTokens.set('token-200', '200');
- await harness.session.login({token: 'token-100', userId: '100', runtimeSnapshot: PRIMARY});
- harness.accountStorage.seed({userId: '200', token: 'token-200', instance: PRIMARY});
- await harness.session.reset();
- await harness.session.initialize();
-
- const ticket = AccountScopedWork.begin();
- responseIsInFlight = true;
- const outcome = (async () => {
- try {
- await response;
- ticket.assertCurrent();
- applied.push(AppStorage.getItem(AuthSessionStorageKey.UserId) ?? 'none');
- return 'applied';
- } finally {
- ticket.dispose();
- }
- })().catch((error: Error) => error.name);
-
- await harness.session.switchAccount(`${PRIMARY_KEY}::200`);
-
- await expect(outcome).resolves.toBe('AbortError');
- expect(applied).toEqual([]);
- expect(ticket.isStale).toBe(true);
- expectCredentialMirrorIntact('200', 'token-200');
- } finally {
- unregisterRelease();
- }
- });
-});
-
-describe('account scoped work fences', () => {
- function fenceLog(): {steps: Array<string>; overrides: Partial<AuthSessionDependencies>} {
- const steps: Array<string> = [];
- return {
- steps,
- overrides: {
- accountScopedWork: {
- runSuspended: async (reason, operation) => {
- steps.push(`cancel:${reason}`);
- steps.push('idle');
- try {
- return await operation(NOOP_AUTH_SESSION_TRANSITION);
- } finally {
- steps.push(`resume:${reason}`);
- }
- },
- },
- activateStorageScope: async (accountKey) => {
- steps.push(`scope:${accountKey ?? 'null'}`);
- },
- },
- };
- }
-
- test('a switch cancels and drains account scoped work before the storage scope swaps', async () => {
- const {steps, overrides} = fenceLog();
- const harness = createHarness(overrides);
- harness.validTokens.set('token-100', '100');
- harness.validTokens.set('token-200', '200');
- await harness.session.login({token: 'token-100', userId: '100', runtimeSnapshot: PRIMARY});
- harness.accountStorage.seed({userId: '200', token: 'token-200', instance: PRIMARY});
- await harness.session.reset();
- await harness.session.initialize();
- steps.length = 0;
-
- await harness.session.switchAccount(`${PRIMARY_KEY}::200`);
-
- expect(steps).toEqual(['cancel:account-switch', 'idle', `scope:${PRIMARY_KEY}::200`, 'resume:account-switch']);
- });
-
- test('a switch that fails validation neither cancels work nor swaps the scope', async () => {
- const {steps, overrides} = fenceLog();
- const harness = createHarness(overrides);
- harness.validTokens.set('token-100', '100');
- await harness.session.login({token: 'token-100', userId: '100', runtimeSnapshot: PRIMARY});
- harness.accountStorage.seed({userId: '200', token: 'token-200', instance: PRIMARY});
- await harness.session.reset();
- await harness.session.initialize();
- steps.length = 0;
-
- await expect(harness.session.switchAccount(`${PRIMARY_KEY}::200`)).rejects.toBeInstanceOf(SessionExpiredError);
-
- expect(steps).toEqual([]);
- });
-
- test('logout fences before the client state reset and the scope teardown', async () => {
- const {steps, overrides} = fenceLog();
- const harness = createHarness({
- ...overrides,
- resetClientState: async () => {
- steps.push('reset');
- },
- });
- harness.validTokens.set('token-100', '100');
- await harness.session.login({token: 'token-100', userId: '100', runtimeSnapshot: PRIMARY});
- steps.length = 0;
-
- await harness.session.logout();
-
- expect(steps).toEqual(['cancel:logout', 'idle', 'reset', 'scope:null', 'resume:logout']);
- });
-
- test('removing the current account fences, removing another account does not', async () => {
- const {steps, overrides} = fenceLog();
- const harness = createHarness(overrides);
- harness.validTokens.set('token-100', '100');
- await harness.session.login({token: 'token-100', userId: '100', runtimeSnapshot: PRIMARY});
- harness.accountStorage.seed({userId: '200', token: 'token-200', instance: PRIMARY});
- await harness.session.reset();
- await harness.session.initialize();
- steps.length = 0;
-
- await harness.session.removeAccount(`${PRIMARY_KEY}::200`);
- expect(steps).toEqual([]);
-
- await harness.session.removeAccount(`${PRIMARY_KEY}::100`);
- expect(steps).toEqual(['cancel:logout', 'idle', 'scope:null', 'resume:logout']);
- });
-
- test('work is resumed even when the switch throws after the point of no return', async () => {
- const {steps, overrides} = fenceLog();
- const harness = createHarness(overrides);
- harness.validTokens.set('token-100', '100');
- harness.validTokens.set('token-200', '200');
- await harness.session.login({token: 'token-100', userId: '100', runtimeSnapshot: PRIMARY});
- harness.accountStorage.seed({userId: '200', token: 'token-200', instance: PRIMARY});
- await harness.session.reset();
- await harness.session.initialize();
- harness.accountStorage.records.delete(`${PRIMARY_KEY}::200`);
- steps.length = 0;
-
- await expect(harness.session.switchAccount(`${PRIMARY_KEY}::200`)).rejects.toThrow();
-
- expect(steps).toEqual(['cancel:account-switch', 'idle', 'resume:account-switch']);
- });
-});
-
-describe('R18 a login that names another instance', () => {
- test('files the account under the named instance, not the one the app is running', async () => {
- const harness = createHarness();
-
- await harness.session.login({token: 'token-100', userId: '100', runtimeSnapshot: FOREIGN});
-
- expect(harness.session.currentAccountKey).toBe(`${FOREIGN_KEY}::100`);
- expect(harness.session.currentAccount?.instance).toEqual(FOREIGN);
- expect(harness.accountStorage.stashes.at(-1)?.instance).toEqual(FOREIGN);
- expect(harness.accountStorage.records.get(`${FOREIGN_KEY}::100`)?.instance).toEqual(FOREIGN);
- expect(harness.accountStorage.records.has(`${PRIMARY_KEY}::100`)).toBe(false);
- expect(harness.activatedScopes.at(-1)).toBe(`${FOREIGN_KEY}::100`);
- expect(window.localStorage.getItem(AuthSessionStorageKey.ActiveAccountKey)).toBe(`${FOREIGN_KEY}::100`);
- });
-
- test('repoints the runtime at the named instance so the session that follows talks to it', async () => {
- const harness = createHarness();
-
- await harness.session.login({token: 'token-100', userId: '100', runtimeSnapshot: FOREIGN});
-
- expect(harness.appliedSnapshots).toEqual([FOREIGN]);
- });
-
- test('the first account activates its explicit runtime after a zero-account boot', async () => {
- const harness = createHarness();
-
- await harness.session.login({token: 'token-100', userId: '100', runtimeSnapshot: PRIMARY});
-
- expect(harness.session.currentAccountKey).toBe(`${PRIMARY_KEY}::100`);
- expect(harness.accountStorage.stashes.at(-1)?.instance).toEqual(PRIMARY);
- expect(harness.appliedSnapshots).toEqual([PRIMARY]);
- });
-
- test('a second account on another instance does not collide with the first instance key', async () => {
- const harness = createHarness();
- harness.validTokens.set('token-100', '100');
-
- await harness.session.login({token: 'token-100', userId: '100', runtimeSnapshot: PRIMARY});
- await harness.session.login({token: 'token-100-elsewhere', userId: '100', runtimeSnapshot: FOREIGN});
-
- expect(harness.session.accounts.map((account) => account.storageKey).sort()).toEqual([
- `${FOREIGN_KEY}::100`,
- `${PRIMARY_KEY}::100`,
- ]);
- expect(harness.session.getAccount(`${PRIMARY_KEY}::100`)?.token).toBe('token-100');
- expect(harness.session.getAccount(`${FOREIGN_KEY}::100`)?.token).toBe('token-100-elsewhere');
- });
-});
-
-describe('logging out of the active account while its screens are still mounted', () => {
- const platforms = [
- {name: 'web', desktop: false},
- {name: 'desktop', desktop: true},
- ] as const;
- const scenarios = [
- {name: 'with another account present', otherAccount: true},
- {name: 'with no other account', otherAccount: false},
- ] as const;
-
- afterEach(() => {
- configure({disableErrorBoundaries: false});
- desktopRuntime.required = false;
- RuntimeConfig.applySnapshot(PRIMARY);
- });
-
- function mountAuthenticatedReaders(): {reads: Array<string>; dispose: () => void} {
- const reads: Array<string> = [];
- const dispose = autorun(() => {
- reads.push(
- `${RuntimeConfig.singleCommunityEnabled}:${RuntimeConfig.features.self_hosted}:${RuntimeConfig.getSnapshot().apiEndpoint}`,
- );
- });
- return {reads, dispose};
- }
-
- async function signIn(desktop: boolean, otherAccount: boolean) {
- const steps: Array<string> = [];
- const harness = createHarness({
- deactivateRuntime: async () => {
- steps.push('deactivate');
- await RuntimeConfig.deactivate();
- },
- closeLayers: () => {
- steps.push('close-layers');
- },
- accountScopedWork: {
- runSuspended: async (_reason, operation) =>
- operation({
- notifyLogout: async () => {
- steps.push('notify-logout');
- },
- }),
- },
- });
- harness.validTokens.set('token-100', '100');
- harness.validTokens.set('token-200', '200');
- if (otherAccount) {
- await harness.session.login({token: 'token-200', userId: '200', runtimeSnapshot: PRIMARY});
- }
- await harness.session.login({token: 'token-100', userId: '100', runtimeSnapshot: PRIMARY});
- desktopRuntime.required = desktop;
- const nativeDeactivate = vi.spyOn(DesktopRuntimeTransactions, 'deactivate').mockResolvedValue(undefined);
- configure({disableErrorBoundaries: true});
- return {harness, steps, nativeDeactivate};
- }
-
- function expectRuntimeAfterSignOut(desktop: boolean, reads: Array<string>): void {
- expect(reads.at(-1)).toBe(`false:false:${PRIMARY_KEY}`);
- expect(RuntimeConfig.getSnapshotOrNull()?.apiEndpoint ?? null).toBe(desktop ? null : PRIMARY_KEY);
- }
-
- for (const platform of platforms) {
- for (const scenario of scenarios) {
- test(`${platform.name} sign-out ${scenario.name} completes and the mounted readers keep working`, async () => {
- const {harness, steps, nativeDeactivate} = await signIn(platform.desktop, scenario.otherAccount);
- const {reads, dispose} = mountAuthenticatedReaders();
- try {
- await harness.session.logout();
- } finally {
- dispose();
- }
-
- expect(harness.session.isAuthenticated).toBe(false);
- expect(harness.session.getAccount(`${PRIMARY_KEY}::100`)).toBeNull();
- expect(harness.session.accounts.map((account) => account.storageKey)).toEqual(
- scenario.otherAccount ? [`${PRIMARY_KEY}::200`] : [],
- );
- expect(steps).toEqual(['deactivate', 'close-layers', 'notify-logout']);
- expect(nativeDeactivate).toHaveBeenCalledTimes(platform.desktop ? 1 : 0);
- expectRuntimeAfterSignOut(platform.desktop, reads);
- });
-
- test(`${platform.name} removing the current account ${scenario.name} completes`, async () => {
- const {harness, steps} = await signIn(platform.desktop, scenario.otherAccount);
- const {reads, dispose} = mountAuthenticatedReaders();
- try {
- await harness.session.removeAccount(`${PRIMARY_KEY}::100`);
- } finally {
- dispose();
- }
-
- expect(harness.session.isAuthenticated).toBe(false);
- expect(harness.session.accounts).toHaveLength(scenario.otherAccount ? 1 : 0);
- expect(steps).toEqual(['deactivate', 'close-layers']);
- expectRuntimeAfterSignOut(platform.desktop, reads);
- });
-
- test(`${platform.name} server revocation ${scenario.name} invalidates without breaking the readers`, async () => {
- const {harness} = await signIn(platform.desktop, scenario.otherAccount);
- const {reads, dispose} = mountAuthenticatedReaders();
- let result: Awaited<ReturnType<AuthSessionManager['handleConnectionClosed']>>;
- try {
- result = await harness.session.handleConnectionClosed(4004);
- } finally {
- dispose();
- }
-
- expect(result.invalidatedCurrentSession).toBe(true);
- expect(harness.session.getAccount(`${PRIMARY_KEY}::100`)?.isValid).toBe(false);
- expect(harness.session.accounts).toHaveLength(scenario.otherAccount ? 2 : 1);
- expectRuntimeAfterSignOut(platform.desktop, reads);
- });
- }
- }
-});
diff --git a/fluxer_app/src/features/platform/state/FrozenStorageRegistry.test.ts b/fluxer_app/src/features/platform/state/FrozenStorageRegistry.test.ts
deleted file mode 100644
index 00227e7c9..000000000
--- a/fluxer_app/src/features/platform/state/FrozenStorageRegistry.test.ts
+++ /dev/null
@@ -1,177 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {readdirSync, readFileSync, statSync} from 'node:fs';
-import {join, relative} from 'node:path';
-import {fileURLToPath} from 'node:url';
-import {
- EVICTION_SYMBOLS,
- EVICTION_TARGET_PREFIX,
- FROZEN_STORAGE_REGISTRY,
- FrozenStorageDeletableAt,
- type FrozenStorageEntry,
- FrozenStorageKind,
-} from '@app/features/platform/state/FrozenStorageRegistry';
-import {isNotMigratedLegacyKey, NOT_MIGRATED_LEGACY_KEYS} from '@app/features/platform/state/LegacyAppStorageKeyMap';
-import {describe, expect, test} from 'vitest';
-
-const REPO_ROOT = fileURLToPath(new URL('../../../../../', import.meta.url));
-
-const SCANNED_ROOTS: ReadonlyArray<string> = ['fluxer_app/src', 'fluxer_desktop/src', 'packages'];
-const SCANNED_EXTENSIONS: ReadonlyArray<string> = ['.ts', '.tsx', '.mjs', '.cjs', '.js'];
-const EXCLUDED_PATH_PATTERN = /node_modules|\.test\.|\.spec\.|__tests__|__fixtures__|\/dist\//;
-
-const DESTRUCTIVE_CALL_PATTERNS: ReadonlyArray<(target: string) => RegExp> = [
- (target) => new RegExp(`removeItem\\(\\s*${target}`),
- (target) => new RegExp(`deleteDatabase\\(\\s*${target}`),
- (target) => new RegExp(`deleteObjectStore\\(\\s*${target}`),
- (target) => new RegExp(`writeRawStorageItem\\(\\s*${target}\\s*,\\s*null`),
-];
-
-function escapeForRegExp(value: string): string {
- return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
-}
-
-function collectSourceFiles(root: string): Array<string> {
- const absoluteRoot = join(REPO_ROOT, root);
- const files: Array<string> = [];
- const walk = (directory: string): void => {
- for (const name of readdirSync(directory)) {
- const path = join(directory, name);
- if (EXCLUDED_PATH_PATTERN.test(path)) {
- continue;
- }
- if (statSync(path).isDirectory()) {
- walk(path);
- continue;
- }
- if (SCANNED_EXTENSIONS.some((extension) => name.endsWith(extension))) {
- files.push(path);
- }
- }
- };
- walk(absoluteRoot);
- return files;
-}
-
-const SOURCE_FILES: ReadonlyArray<string> = SCANNED_ROOTS.flatMap(collectSourceFiles);
-
-const SOURCE_BY_PATH: ReadonlyMap<string, string> = new Map(
- SOURCE_FILES.map((path) => [relative(REPO_ROOT, path), readFileSync(path, 'utf8')]),
-);
-
-function destructiveReferences(entry: FrozenStorageEntry): Array<string> {
- const targets = [
- ...entry.names.map((name) => `['"\`]${escapeForRegExp(name)}['"\`]`),
- ...entry.aliases.map((alias) => escapeForRegExp(alias)),
- ];
- const offenders: Array<string> = [];
- for (const [path, source] of SOURCE_BY_PATH) {
- if (entry.clearableBy.includes(path)) {
- continue;
- }
- for (const target of targets) {
- if (DESTRUCTIVE_CALL_PATTERNS.some((build) => build(target).test(source))) {
- offenders.push(path);
- break;
- }
- }
- }
- return offenders;
-}
-
-const NEVER_DELETABLE_ENTRIES = FROZEN_STORAGE_REGISTRY.filter(
- (entry) => entry.deletableAt === FrozenStorageDeletableAt.NEVER,
-);
-
-describe('the frozen storage registry describes real stores', () => {
- test('every entry has a unique id and at least one name', () => {
- const ids = FROZEN_STORAGE_REGISTRY.map((entry) => entry.id);
- expect(new Set(ids).size).toBe(ids.length);
- for (const entry of FROZEN_STORAGE_REGISTRY) {
- expect(entry.names.length).toBeGreaterThan(0);
- }
- });
-
- test('an IndexedDB entry pins its version and no other kind claims one', () => {
- for (const entry of FROZEN_STORAGE_REGISTRY) {
- if (entry.kind === FrozenStorageKind.INDEXED_DB) {
- expect(entry.version, entry.id).toBeTypeOf('number');
- continue;
- }
- expect(entry.version, entry.id).toBeNull();
- }
- });
-
- test('every declared writer module exists and still performs its write', () => {
- for (const entry of FROZEN_STORAGE_REGISTRY) {
- for (const writer of entry.writers) {
- const source = SOURCE_BY_PATH.get(writer.module);
- expect(source, `${entry.id}: ${writer.module} is gone`).toBeTypeOf('string');
- expect(source?.includes(writer.marker), `${entry.id}: ${writer.module} no longer writes ${writer.marker}`).toBe(
- true,
- );
- }
- }
- });
-
- test('a never-deletable store is written by live code, or is a legacy key nothing migrates', () => {
- for (const entry of NEVER_DELETABLE_ENTRIES) {
- if (entry.writers.length > 0) {
- continue;
- }
- for (const name of entry.names) {
- expect(isNotMigratedLegacyKey(name), `${entry.id}: ${name} is written by nobody and migrated anyway`).toBe(
- true,
- );
- }
- }
- });
-
- test('the registry classifies every frozen legacy key', () => {
- const registered = new Set(
- FROZEN_STORAGE_REGISTRY.filter(
- (entry) => entry.kind === FrozenStorageKind.LOCAL_STORAGE || entry.kind === FrozenStorageKind.SESSION_STORAGE,
- ).flatMap((entry) => entry.names),
- );
- for (const key of NOT_MIGRATED_LEGACY_KEYS) {
- expect(registered.has(key), `${key} is frozen out of the migration but absent from the registry`).toBe(true);
- }
- });
-});
-
-describe('nothing deletes a never-deletable store', () => {
- test('no source file deletes an IndexedDB database or object store', () => {
- const offenders = [...SOURCE_BY_PATH]
- .filter(([, source]) => /deleteDatabase\(|deleteObjectStore\(/.test(source))
- .map(([path]) => path);
- expect(offenders).toEqual([]);
- });
-
- test.each(NEVER_DELETABLE_ENTRIES.map((entry) => [entry.id, entry] as const))(
- '%s is cleared only by the modules that own it',
- (_id, entry) => {
- expect(destructiveReferences(entry)).toEqual([]);
- },
- );
-});
-
-describe('eviction and prune stay bounded', () => {
- test('no eviction path exists outside the state cache', () => {
- for (const [path, source] of SOURCE_BY_PATH) {
- for (const symbol of EVICTION_SYMBOLS) {
- if (!source.includes(symbol)) {
- continue;
- }
- expect(
- source.includes(EVICTION_TARGET_PREFIX),
- `${path} evicts something that is not ${EVICTION_TARGET_PREFIX}`,
- ).toBe(true);
- }
- }
- });
-
- test('the account prune contract cannot be called without an authoritative key list', () => {
- const contract = SOURCE_BY_PATH.get('packages/desktop_ipc/src/AccountContract.ts');
- expect(contract).toContain('readonly listIsAuthoritative: boolean;');
- });
-});
diff --git a/fluxer_app/src/features/platform/state/FrozenStorageRegistry.ts b/fluxer_app/src/features/platform/state/FrozenStorageRegistry.ts
deleted file mode 100644
index 9b6b5cf8f..000000000
--- a/fluxer_app/src/features/platform/state/FrozenStorageRegistry.ts
+++ /dev/null
@@ -1,283 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-export const FrozenStorageKind = Object.freeze({
- INDEXED_DB: 'indexed-db',
- LOCAL_STORAGE: 'local-storage',
- SESSION_STORAGE: 'session-storage',
- DESKTOP_DIRECTORY: 'desktop-directory',
- DESKTOP_FILE: 'desktop-file',
-} as const);
-
-export type FrozenStorageKind = (typeof FrozenStorageKind)[keyof typeof FrozenStorageKind];
-
-export const FrozenStorageDeletableAt = Object.freeze({
- NEVER: 'never',
- NEXT_RELEASE: 'N+1',
- RELEASE_AFTER_NEXT: 'N+2',
-} as const);
-
-export type FrozenStorageDeletableAt = (typeof FrozenStorageDeletableAt)[keyof typeof FrozenStorageDeletableAt];
-
-export interface FrozenStorageWriter {
- readonly module: string;
- readonly marker: string;
-}
-
-export interface FrozenStorageEntry {
- readonly id: string;
- readonly kind: FrozenStorageKind;
- readonly names: ReadonlyArray<string>;
- readonly aliases: ReadonlyArray<string>;
- readonly version: number | null;
- readonly deletableAt: FrozenStorageDeletableAt;
- readonly writers: ReadonlyArray<FrozenStorageWriter>;
- readonly clearableBy: ReadonlyArray<string>;
- readonly note: string;
-}
-
-export const EVICTION_TARGET_PREFIX = 'state-cache/';
-
-export const EVICTION_SYMBOLS: ReadonlyArray<string> = Object.freeze(['stateEvict', 'evictStateCache', 'evictScope']);
-
-const SSO_PENDING_CONTEXT = 'fluxer_app/src/features/auth/state/SsoPendingContext.ts';
-const ACCOUNT_STORAGE = 'fluxer_app/src/features/auth/state/BrowserAccountStorageRepository.ts';
-const PREBOOT_MIRROR = 'fluxer_app/src/features/platform/state/PrebootMirror.ts';
-const RESET_CLIENT_STATE = 'fluxer_app/src/features/platform/state/ResetClientState.ts';
-const SESSION_CREDENTIAL_MIRROR = 'fluxer_app/src/features/platform/state/auth_session/SessionCredentialMirror.ts';
-
-export const FROZEN_STORAGE_REGISTRY: ReadonlyArray<FrozenStorageEntry> = Object.freeze([
- {
- id: 'idb.fluxer-accounts',
- kind: FrozenStorageKind.INDEXED_DB,
- names: ['FluxerAccounts'],
- aliases: [],
- version: 2,
- deletableAt: FrozenStorageDeletableAt.NEVER,
- writers: [
- {module: ACCOUNT_STORAGE, marker: 'transaction.store.put(record)'},
- {module: ACCOUNT_STORAGE, marker: 'transaction.store.put(normalized)'},
- ],
- clearableBy: [],
- note: 'Every stored account of every deployed user. Pinned at v2 by R1: a bump reruns onupgradeneeded against stores this release did not create.',
- },
- {
- id: 'idb.fluxer-custom-sounds',
- kind: FrozenStorageKind.INDEXED_DB,
- names: ['FluxerCustomSounds'],
- aliases: [],
- version: 2,
- deletableAt: FrozenStorageDeletableAt.NEVER,
- writers: [
- {module: 'fluxer_app/src/features/notification/utils/CustomSoundDB.ts', marker: 'store.put(customSound)'},
- ],
- clearableBy: [],
- note: 'User-uploaded notification sounds. Origin-partitioned and never re-uploadable once dropped.',
- },
- {
- id: 'idb.fluxer-theme-library',
- kind: FrozenStorageKind.INDEXED_DB,
- names: ['fluxer-theme-library'],
- aliases: [],
- version: 1,
- deletableAt: FrozenStorageDeletableAt.NEVER,
- writers: [{module: 'fluxer_app/src/features/theme/utils/ThemeLibraryDb.ts', marker: 'store.put(asset)'}],
- clearableBy: [],
- note: 'Custom theme assets (binary), authored by the user and stored nowhere else. Theme definitions, enabled ids and local file metadata moved to durable AppStorage.',
- },
- {
- id: 'idb.fluxer-voice-stats',
- kind: FrozenStorageKind.INDEXED_DB,
- names: ['FluxerVoiceStats'],
- aliases: [],
- version: 1,
- deletableAt: FrozenStorageDeletableAt.NEVER,
- writers: [{module: 'fluxer_app/src/features/voice/diagnostics/VoiceStatsDB.ts', marker: 'store.put(entry)'}],
- clearableBy: [],
- note: 'Voice diagnostics history, the only record of a call that already happened.',
- },
- {
- id: 'local.session-user-id',
- kind: FrozenStorageKind.LOCAL_STORAGE,
- names: ['userId'],
- aliases: ['AuthSessionStorageKey.UserId', 'AppStorageKey.AUTH_SESSION_USER_ID'],
- version: null,
- deletableAt: FrozenStorageDeletableAt.NEVER,
- writers: [
- {module: SESSION_CREDENTIAL_MIRROR, marker: 'this.writeValue(AuthSessionStorageKey.UserId, mirror.userId)'},
- {module: SESSION_CREDENTIAL_MIRROR, marker: 'this.storage.setItem(key, value)'},
- ],
- clearableBy: [SESSION_CREDENTIAL_MIRROR, RESET_CLIENT_STATE],
- note: 'Never deleted, in any release: AuthSession restores the credential mirror before an account scope is active.',
- },
- {
- id: 'local.session-token',
- kind: FrozenStorageKind.LOCAL_STORAGE,
- names: ['token'],
- aliases: ['AuthSessionStorageKey.Token', 'AppStorageKey.AUTH_SESSION_TOKEN'],
- version: null,
- deletableAt: FrozenStorageDeletableAt.NEXT_RELEASE,
- writers: [
- {module: SESSION_CREDENTIAL_MIRROR, marker: 'this.writeValue(AuthSessionStorageKey.Token, mirror.token)'},
- {module: SESSION_CREDENTIAL_MIRROR, marker: 'this.storage.setItem(key, value)'},
- ],
- clearableBy: [SESSION_CREDENTIAL_MIRROR, RESET_CLIENT_STATE],
- note: 'Retained until R2 stops writing it and deletes AuthSessionStorageKey.Token.',
- },
- {
- id: 'local.gateway-preboot-session',
- kind: FrozenStorageKind.LOCAL_STORAGE,
- names: ['fluxer:gateway:preboot:session'],
- aliases: ['GATEWAY_PREBOOT_SESSION_STORAGE_KEY'],
- version: null,
- deletableAt: FrozenStorageDeletableAt.NEVER,
- writers: [{module: PREBOOT_MIRROR, marker: 'writeRawStorageItem(GATEWAY_PREBOOT_SESSION_STORAGE_KEY'}],
- clearableBy: [PREBOOT_MIRROR, RESET_CLIENT_STATE],
- note: 'The boolean marker R2 switches index.html onto. It replaces a raw token read, so it must already be written before R2 ships.',
- },
- {
- id: 'local.deployed-build-leftovers',
- kind: FrozenStorageKind.LOCAL_STORAGE,
- names: ['runtimeConfig', 'AccountManager'],
- aliases: [],
- version: null,
- deletableAt: FrozenStorageDeletableAt.NEVER,
- writers: [],
- clearableBy: [RESET_CLIENT_STATE],
- note: 'Written only by the deployed build and read by nothing here. Inert, not preserved for a downgrade, but still deployed user data that only a reset may clear.',
- },
- {
- id: 'local.frozen-preference-keys',
- kind: FrozenStorageKind.LOCAL_STORAGE,
- names: [
- 'UserSettings:syncedPreferencesWire',
- 'UserSettings:syncedPreferencesDirtyFields',
- 'UserSettings:syncedPreferencesRecentAck',
- 'PremiumCheckoutReturnIntent',
- 'userEntranceSound',
- 'entranceSound:guilds',
- 'entranceSound:dms',
- 'enabledThemeIds',
- 'closeToTrayV2',
- 'minimizeToTrayV2',
- ],
- aliases: [],
- version: null,
- deletableAt: FrozenStorageDeletableAt.NEVER,
- writers: [
- {module: 'fluxer_app/src/features/user/state/UserSettings.ts', marker: 'UserSettings:syncedPreferencesWire'},
- {
- module: 'fluxer_app/src/features/premium/utils/PremiumCheckoutReturnIntent.ts',
- marker: 'PremiumCheckoutReturnIntent',
- },
- {module: 'fluxer_app/src/features/theme/state/ThemeLibrary.ts', marker: 'enabledThemeIds'},
- {module: 'fluxer_desktop/src/common/DesktopConfig.ts', marker: 'closeToTrayV2'},
- ],
- clearableBy: [RESET_CLIENT_STATE],
- note: 'Raw keys the scoped migration deliberately never moves. Both eras read and write them in place.',
- },
- {
- id: 'local.domain-migration',
- kind: FrozenStorageKind.LOCAL_STORAGE,
- names: [
- 'fluxer:domain-migration',
- 'fluxer:domain-migration:device',
- 'fluxer:domain-migration:notifications',
- 'fluxer:domain-migration:moved-dismissed-at',
- ],
- aliases: [],
- version: null,
- deletableAt: FrozenStorageDeletableAt.NEVER,
- writers: [
- {
- module: 'fluxer_app/src/features/app/domain_migration/DomainMigrationCore.ts',
- marker: 'storage?.setItem(DOMAIN_MIGRATION_MARKER_KEY',
- },
- {
- module: 'fluxer_app/src/features/app/domain_migration/DomainMigrationPreMount.ts',
- marker: 'storage?.setItem(DOMAIN_MIGRATION_DEVICE_KEY',
- },
- ],
- clearableBy: [
- 'fluxer_app/src/features/app/domain_migration/DomainMigrationTrigger.ts',
- 'fluxer_app/src/features/app/domain_migration/DomainMovedNotice.ts',
- RESET_CLIENT_STATE,
- ],
- note: 'Raw keys the domain move reads and writes in place on both origins. The scoped migration never moves them.',
- },
- {
- id: 'session.sso-redirect-to',
- kind: FrozenStorageKind.SESSION_STORAGE,
- names: ['fluxer:sso:redirect_to'],
- aliases: ['LEGACY_SSO_REDIRECT_TO_STORAGE_KEY'],
- version: null,
- deletableAt: FrozenStorageDeletableAt.NEVER,
- writers: [],
- clearableBy: [SSO_PENDING_CONTEXT],
- note: 'An SSO round trip started on the deployed build lands on this build, and the reverse. Only the module that consumes it may clear it.',
- },
- {
- id: 'desktop.voice-background-media',
- kind: FrozenStorageKind.DESKTOP_DIRECTORY,
- names: ['voice-background-media'],
- aliases: ['CACHE_DIR_NAME'],
- version: null,
- deletableAt: FrozenStorageDeletableAt.NEVER,
- writers: [
- {
- module: 'fluxer_desktop/src/main/VoiceBackgroundMediaCache.ts',
- marker: "CACHE_DIR_NAME = 'voice-background-media'",
- },
- ],
- clearableBy: ['fluxer_desktop/src/main/VoiceBackgroundMediaCache.ts'],
- note: 'User-supplied voice background media. R2 re-scopes the directory per account by moving files. It is never emptied.',
- },
- {
- id: 'desktop.settings-json',
- kind: FrozenStorageKind.DESKTOP_FILE,
- names: ['settings.json'],
- aliases: ['CONFIG_FILE_NAME'],
- version: null,
- deletableAt: FrozenStorageDeletableAt.NEVER,
- writers: [{module: 'fluxer_desktop/src/common/DesktopConfig.ts', marker: "CONFIG_FILE_NAME = 'settings.json'"}],
- clearableBy: [],
- note: 'Every desktop shell preference. An old shell and a new renderer read the same file, in both skew directions.',
- },
- {
- id: 'desktop.window-state-json',
- kind: FrozenStorageKind.DESKTOP_FILE,
- names: ['window-state.json'],
- aliases: [],
- version: null,
- deletableAt: FrozenStorageDeletableAt.NEVER,
- writers: [{module: 'fluxer_desktop/src/main/Window.ts', marker: "'window-state.json'"}],
- clearableBy: [],
- note: 'Window geometry. --fluxer-reset-window-state ignores it for one launch. Nothing deletes it.',
- },
- {
- id: 'desktop.native-strings-json',
- kind: FrozenStorageKind.DESKTOP_FILE,
- names: ['native-strings.json'],
- aliases: ['STORAGE_FILE_NAME'],
- version: null,
- deletableAt: FrozenStorageDeletableAt.NEVER,
- writers: [{module: 'fluxer_desktop/src/main/MainI18n.ts', marker: "STORAGE_FILE_NAME = 'native-strings.json'"}],
- clearableBy: [],
- note: 'The tray and menu strings the shell renders before the renderer exists.',
- },
- {
- id: 'desktop.app-store-sqlite',
- kind: FrozenStorageKind.DESKTOP_FILE,
- names: ['desktop-app-store.sqlite3'],
- aliases: ['DESKTOP_APP_STORE_FILE_NAME'],
- version: null,
- deletableAt: FrozenStorageDeletableAt.NEVER,
- writers: [
- {
- module: 'fluxer_desktop/src/main/DesktopAppStorage.ts',
- marker: "DESKTOP_APP_STORE_FILE_NAME = 'desktop-app-store.sqlite3'",
- },
- ],
- clearableBy: [],
- note: 'The desktop account store. A corrupt file is renamed aside and rebuilt. It is never unlinked.',
- },
-]);
diff --git a/fluxer_app/src/features/platform/state/LegacyAppStorageKeyMap.test.ts b/fluxer_app/src/features/platform/state/LegacyAppStorageKeyMap.test.ts
deleted file mode 100644
index d67368c48..000000000
--- a/fluxer_app/src/features/platform/state/LegacyAppStorageKeyMap.test.ts
+++ /dev/null
@@ -1,272 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- CONTENT_STORAGE_KEYS,
- DEPLOYED_MANAGED_KEY_PREFIXES,
- GOLDEN_DEPLOYED_STORAGE_ENTRIES,
- GOLDEN_LOCAL_STORAGE_CORPUS,
- GOLDEN_UNKNOWN_STORAGE_ENTRIES,
- OWNED_CONTENT_STORAGE_KEYS,
- SHARED_CONTENT_STORAGE_KEYS,
-} from '@app/features/platform/state/__fixtures__/LegacyStorageFixtures';
-import {
- readPersistedStoreNames,
- STORES_WITHOUT_DEPLOYED_DATA,
-} from '@app/features/platform/state/__fixtures__/PersistedStoreNames';
-import {AppStorageKey, isGlobalAppStorageKey} from '@app/features/platform/state/AppStorageKeys';
-import {
- isLegacyAccountSwappedKey,
- isNotMigratedLegacyKey,
- LEGACY_APP_STORAGE_KEY_MAP,
- type LegacyAppStorageKeyRow,
- NOT_MIGRATED_LEGACY_KEYS,
- resolveLegacyAppStorageKey,
-} from '@app/features/platform/state/LegacyAppStorageKeyMap';
-import {describe, expect, test} from 'vitest';
-
-const GOLDEN_USER_ID = '100000000000000003';
-const DEPLOYED_PER_ACCOUNT_KEY_PATTERN = new RegExp(`^(?:${DEPLOYED_MANAGED_KEY_PREFIXES.join('|')})`);
-const SHARED_DESPITE_DEPLOYED_PER_ACCOUNT: ReadonlySet<string> = new Set([
- 'fluxer.lastPushEndpoint',
- 'fluxer:media_caps:v2',
- 'fluxer:media:volume',
- 'fluxer:media:muted',
- 'fluxer:media:playbackRate',
- 'fluxer:media_player:playback-rate',
-]);
-
-function rowLabel(row: LegacyAppStorageKeyRow): string {
- return row.kind === 'exact' ? row.key : row.prefix;
-}
-
-describe('legacy key map totality', () => {
- test('every deployed golden key is mapped or explicitly not migrated', () => {
- for (const entry of GOLDEN_DEPLOYED_STORAGE_ENTRIES) {
- const covered = resolveLegacyAppStorageKey(entry.key) !== null || isNotMigratedLegacyKey(entry.key);
- expect(covered, entry.key).toBe(true);
- }
- });
-
- test('a mapped key is never also on the not-migrated list', () => {
- for (const key of NOT_MIGRATED_LEGACY_KEYS) {
- expect(resolveLegacyAppStorageKey(key), key).toBeNull();
- }
- });
-
- test('unknown keys resolve to nothing so the migration can bucket them as unclassified', () => {
- for (const entry of GOLDEN_UNKNOWN_STORAGE_ENTRIES) {
- expect(resolveLegacyAppStorageKey(entry.key), entry.key).toBeNull();
- expect(isNotMigratedLegacyKey(entry.key), entry.key).toBe(false);
- }
- });
-
- test('no two rows claim the same key', () => {
- const seen = new Set<string>();
- for (const row of LEGACY_APP_STORAGE_KEY_MAP) {
- const label = rowLabel(row);
- expect(seen.has(label), label).toBe(false);
- seen.add(label);
- }
- });
-
- test('no key is classified by both the map and the registry of keys this build introduced', () => {
- for (const row of LEGACY_APP_STORAGE_KEY_MAP) {
- const probe = row.kind === 'exact' ? row.key : `${row.prefix}:probe`;
- expect(isGlobalAppStorageKey(probe), probe).toBe(false);
- }
- });
-
- test('every golden entry resolves to the scope and fan-out its destination names', () => {
- const expectations = {
- global: {scope: 'global', fanout: 'preference'},
- 'every-account': {scope: 'account', fanout: 'preference'},
- 'content-account': {scope: 'account', fanout: 'content'},
- 'shared-content': {scope: 'account', fanout: 'content'},
- 'named-account': {scope: 'account', fanout: 'preference'},
- } as const;
- for (const entry of GOLDEN_DEPLOYED_STORAGE_ENTRIES) {
- if (entry.destination === 'raw') {
- expect(isNotMigratedLegacyKey(entry.key), entry.key).toBe(true);
- continue;
- }
- const match = resolveLegacyAppStorageKey(entry.key);
- expect({scope: match?.row.scope, fanout: match?.row.fanout}, entry.key).toEqual(expectations[entry.destination]);
- expect(match?.userId != null, entry.key).toBe(entry.destination === 'named-account');
- }
- });
-});
-
-describe('persisted stores', () => {
- test('every makePersistent store is carried under the exact name the store reads and writes', () => {
- const names = readPersistedStoreNames();
- expect(names.length).toBeGreaterThan(25);
- for (const name of names) {
- if (STORES_WITHOUT_DEPLOYED_DATA.has(name)) {
- expect(resolveLegacyAppStorageKey(name), name).toBeNull();
- continue;
- }
- const match = resolveLegacyAppStorageKey(name);
- expect(match?.row.kind, name).toBe('exact');
- expect(
- GOLDEN_DEPLOYED_STORAGE_ENTRIES.some((entry) => entry.key === name),
- `${name} has no golden corpus entry`,
- ).toBe(true);
- }
- });
-
- test('no store name is left out of the audit as a stale exemption', () => {
- const names = new Set(readPersistedStoreNames());
- for (const name of STORES_WITHOUT_DEPLOYED_DATA) {
- expect(names.has(name), name).toBe(true);
- }
- });
-});
-
-describe('fan-out split', () => {
- test('exactly the golden content keys carry the content fan-out', () => {
- const contentRows = LEGACY_APP_STORAGE_KEY_MAP.filter((row) => row.fanout === 'content');
- expect(CONTENT_STORAGE_KEYS).toHaveLength(22);
- for (const key of CONTENT_STORAGE_KEYS) {
- expect(resolveLegacyAppStorageKey(key)?.row.fanout, key).toBe('content');
- }
- for (const row of contentRows) {
- const label = rowLabel(row);
- expect(
- CONTENT_STORAGE_KEYS.some((key) => (row.kind === 'exact' ? key === label : key.startsWith(label))),
- label,
- ).toBe(true);
- }
- });
-
- test('every content row is account scoped', () => {
- for (const row of LEGACY_APP_STORAGE_KEY_MAP) {
- if (row.fanout === 'content') {
- expect(row.scope, rowLabel(row)).toBe('account');
- }
- }
- });
-
- test('a key the deployed build swapped per account never fans out to another account', () => {
- for (const row of LEGACY_APP_STORAGE_KEY_MAP) {
- const label = rowLabel(row);
- if (!DEPLOYED_PER_ACCOUNT_KEY_PATTERN.test(label)) {
- continue;
- }
- if (SHARED_DESPITE_DEPLOYED_PER_ACCOUNT.has(label)) {
- expect(row.scope, label).toBe('global');
- continue;
- }
- expect({scope: row.scope, fanout: row.fanout}, label).toEqual({scope: 'account', fanout: 'content'});
- }
- });
-
- test('the per-account swap rule matches the deployed build for every corpus key', () => {
- for (const entry of GOLDEN_LOCAL_STORAGE_CORPUS) {
- expect(isLegacyAccountSwappedKey(entry.key), entry.key).toBe(DEPLOYED_PER_ACCOUNT_KEY_PATTERN.test(entry.key));
- }
- });
-
- test('content the deployed build kept in one map for every account is the shared content', () => {
- expect([...SHARED_CONTENT_STORAGE_KEYS].sort()).toEqual(
- [
- 'ChannelFrecencyLocal',
- 'ChannelFrecencyThreadGuilds',
- 'Drafts',
- 'GuildMatureContentAgreeLocal',
- 'SelectedGuild',
- 'SelectedChannel',
- 'Inbox',
- 'Location',
- 'SearchHistory',
- 'MessageEdit',
- 'TrustedDomain',
- 'member_list_default_hidden_channel_overrides',
- 'ThreadPanelWidth',
- ].sort(),
- );
- for (const key of SHARED_CONTENT_STORAGE_KEYS) {
- expect(isLegacyAccountSwappedKey(key), key).toBe(false);
- }
- for (const key of OWNED_CONTENT_STORAGE_KEYS) {
- expect(isLegacyAccountSwappedKey(key), key).toBe(true);
- }
- });
-
- test('the synced-preference wire, dirty and ack keys are not migrated at all', () => {
- for (const key of [
- 'UserSettings:syncedPreferencesWire',
- 'UserSettings:syncedPreferencesDirtyFields',
- 'UserSettings:syncedPreferencesRecentAck',
- ]) {
- expect(resolveLegacyAppStorageKey(key), key).toBeNull();
- expect(isNotMigratedLegacyKey(key), key).toBe(true);
- }
- expect(resolveLegacyAppStorageKey('UserSettings:syncedPreferencesLocal')?.row.scope).toBe('account');
- });
-});
-
-describe('never scoped keys', () => {
- test('token, userId, runtimeConfig and AccountManager never reach scoped storage', () => {
- for (const key of ['token', 'userId', 'runtimeConfig', 'AccountManager']) {
- expect(resolveLegacyAppStorageKey(key), key).toBeNull();
- expect(isNotMigratedLegacyKey(key), key).toBe(true);
- }
- });
-});
-
-describe('voice keys', () => {
- test('every voice store stays shared by all accounts, as the stores read it', () => {
- for (const key of [
- 'VoiceSettings',
- 'LocalVoiceState',
- 'VoiceSessionRestore',
- 'ParticipantVolume',
- 'StreamAudioPrefs',
- 'EntranceSoundListenerPrefs',
- 'AudioVolume',
- 'VideoVolume',
- ]) {
- expect(resolveLegacyAppStorageKey(key)?.row.scope, key).toBe('global');
- }
- });
-});
-
-describe('scheduled maintenance dismissals', () => {
- test('both deployed forms belong to the account that dismissed them', () => {
- for (const key of [
- 'fluxer_scheduled_maintenance_dismissed:9876543210',
- 'fluxer_scheduled_maintenance_dismissed:9876543210:in_progress',
- ]) {
- const match = resolveLegacyAppStorageKey(key);
- expect(match?.row.scope, key).toBe('account');
- expect(match?.row.fanout, key).toBe('content');
- expect(match?.userId, key).toBeNull();
- }
- });
-
- test('the bare prefix with no maintenance id resolves to nothing', () => {
- expect(resolveLegacyAppStorageKey('fluxer_scheduled_maintenance_dismissed:')).toBeNull();
- });
-});
-
-describe('accessibility keys', () => {
- test('the suffixed neko keys turn their user id into the scope', () => {
- for (const prefix of ['Accessibility:showNeko', 'Accessibility:keepNekoStill', 'Accessibility:pinNekoToTextarea']) {
- const match = resolveLegacyAppStorageKey(`${prefix}:${GOLDEN_USER_ID}`);
- expect(match?.row.kind, prefix).toBe('suffixed');
- expect(match?.userId, prefix).toBe(GOLDEN_USER_ID);
- }
- });
-
- test('the un-suffixed neko keys carry no user id and fan out', () => {
- const showNeko = resolveLegacyAppStorageKey('Accessibility:showNeko');
- expect(showNeko?.userId).toBeNull();
- expect(showNeko?.row.fanout).toBe('preference');
- });
-
- test('the legacy Accessibility blob is carried into every account scope', () => {
- const match = resolveLegacyAppStorageKey(AppStorageKey.ACCESSIBILITY_LEGACY_STORE);
- expect(match?.row.scope).toBe('account');
- expect(match?.row.fanout).toBe('preference');
- });
-});
diff --git a/fluxer_app/src/features/platform/state/LegacyAppStorageMigration.test.ts b/fluxer_app/src/features/platform/state/LegacyAppStorageMigration.test.ts
deleted file mode 100644
index 54b10a611..000000000
--- a/fluxer_app/src/features/platform/state/LegacyAppStorageMigration.test.ts
+++ /dev/null
@@ -1,949 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- FIXTURE_CURRENT_INSTANCE_KEY,
- FIXTURE_CURRENT_INSTANCE_SNAPSHOT,
- FIXTURE_NOW,
- FLUXER_ACCOUNTS_V2_RECORD_CLASSES,
-} from '@app/features/auth/state/__fixtures__/AccountRecordFixtures';
-import type {
- AccountRekeyOutcome,
- AccountRekeyTarget,
- KeyedStoredAccount,
-} from '@app/features/auth/state/AccountStorageContract';
-import {
- CONTENT_STORAGE_KEYS,
- expectedGoldenStorageRows,
- GOLDEN_DEPLOYED_STORAGE_ENTRIES,
- GOLDEN_LOCAL_STORAGE_CORPUS,
- GOLDEN_UNKNOWN_STORAGE_ENTRIES,
- goldenStorageRowIdentity,
- NOT_MIGRATED_STORAGE_KEYS,
- OWNED_CONTENT_STORAGE_KEYS,
- readGoldenLocalStorageSnapshot,
- SHARED_CONTENT_STORAGE_KEYS,
- seedGoldenLocalStorage,
-} from '@app/features/platform/state/__fixtures__/LegacyStorageFixtures';
-import {installRuntimeBootstrap} from '@app/features/platform/state/__fixtures__/RuntimeBootstrapFixture';
-import type {AppStorageWrite, PersistentStorageBackend} from '@app/features/platform/state/PersistentStorageBackend';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
-
-type MigrationModule = typeof import('@app/features/platform/state/LegacyAppStorageMigration');
-type BackendModule = typeof import('@app/features/platform/state/PersistentStorageBackend');
-
-const ACTIVE_USER_ID = '100000000000000002';
-const OTHER_USER_ID = '100000000000000003';
-const THIRD_USER_ID = '100000000000000007';
-const ACTIVE_SCOPE = `${FIXTURE_CURRENT_INSTANCE_KEY}::${ACTIVE_USER_ID}`;
-const OTHER_SCOPE = `${FIXTURE_CURRENT_INSTANCE_KEY}::${OTHER_USER_ID}`;
-const THIRD_SCOPE = `${FIXTURE_CURRENT_INSTANCE_KEY}::${THIRD_USER_ID}`;
-const UNAUTHENTICATED_SCOPE = 'unauthenticated';
-const GLOBAL_SCOPE = 'global';
-const SHARED_CONTENT_REVIEW_KEY = 'fluxer:migration:shared-content-review';
-const ALL_ACCOUNT_SCOPES = [UNAUTHENTICATED_SCOPE, ACTIVE_SCOPE, OTHER_SCOPE];
-const DEPLOYED_ACCOUNT_SCOPES = [ACTIVE_SCOPE, OTHER_SCOPE];
-const ACTIVE_TOKEN = GOLDEN_LOCAL_STORAGE_CORPUS.find((entry) => entry.key === 'token')!.value;
-const CURRENT_ACCOUNT: AccountRekeyTarget = {
- userId: ACTIVE_USER_ID,
- token: ACTIVE_TOKEN,
- instance: FIXTURE_CURRENT_INSTANCE_SNAPSHOT,
-};
-
-const KEYED_ACCOUNTS: ReadonlyArray<KeyedStoredAccount> = (() => {
- const recordClass = FLUXER_ACCOUNTS_V2_RECORD_CLASSES.find((candidate) => candidate.id === 'same-instance-pair')!;
- return recordClass.records.map((record, index) => ({
- ...record,
- token: record.userId === ACTIVE_USER_ID ? ACTIVE_TOKEN : record.token,
- storageKey: recordClass.expectedStorageKeys[index],
- }));
-})();
-
-const THREE_KEYED_ACCOUNTS: ReadonlyArray<KeyedStoredAccount> = [
- ...KEYED_ACCOUNTS,
- {...KEYED_ACCOUNTS[1]!, userId: THIRD_USER_ID, token: `token.${THIRD_USER_ID}`, storageKey: THIRD_SCOPE},
-];
-
-const identity = goldenStorageRowIdentity;
-
-function expectedPlanEntries(): Map<string, string> {
- const rows = expectedGoldenStorageRows({
- global: GLOBAL_SCOPE,
- everyAccount: ALL_ACCOUNT_SCOPES,
- contentAccount: ACTIVE_SCOPE,
- sharedContent: DEPLOYED_ACCOUNT_SCOPES,
- namedAccount: OTHER_SCOPE,
- });
- for (const scope of DEPLOYED_ACCOUNT_SCOPES) {
- rows.set(identity(scope, SHARED_CONTENT_REVIEW_KEY), 'pending');
- }
- return rows;
-}
-
-function completeMarker(marker: {
- readonly status: 'complete' | 'partial';
- readonly pendingScopes: ReadonlyArray<string>;
- readonly deferredAccounts?: number;
- readonly sharedContentScopes?: ReadonlyArray<string>;
- readonly deferredUserIds?: ReadonlyArray<string>;
-}): string {
- return JSON.stringify({
- version: 1,
- status: marker.status,
- pendingScopes: marker.pendingScopes,
- deferredAccounts: marker.deferredAccounts ?? 0,
- contentScope: ACTIVE_SCOPE,
- sharedContentScopes: marker.sharedContentScopes ?? DEPLOYED_ACCOUNT_SCOPES,
- deferredUserIds: marker.deferredUserIds ?? [],
- });
-}
-
-function planEntries(writes: ReadonlyArray<AppStorageWrite>): Map<string, string> {
- return new Map(writes.map((write) => [identity(write.scope, write.key), write.value]));
-}
-
-async function loadModules(): Promise<{migration: MigrationModule; backendModule: BackendModule}> {
- const backendModule = await import('@app/features/platform/state/PersistentStorageBackend');
- const migration = await import('@app/features/platform/state/LegacyAppStorageMigration');
- window.localStorage.clear();
- seedGoldenLocalStorage(window.localStorage);
- window.localStorage.setItem('userId', ACTIVE_USER_ID);
- return {migration, backendModule};
-}
-
-function accountSource(outcome: Partial<AccountRekeyOutcome> = {}): {
- migrateAccountStorageKeys: () => Promise<AccountRekeyOutcome>;
-} {
- return {
- migrateAccountStorageKeys: () =>
- Promise.resolve({
- status: 'complete',
- source: 'idb',
- qualifiedRecords: [...KEYED_ACCOUNTS],
- deferredRecords: [],
- written: 0,
- ...outcome,
- }),
- };
-}
-
-async function readBackend(backend: PersistentStorageBackend): Promise<Map<string, string>> {
- const entries = new Map<string, string>();
- for (const scope of [GLOBAL_SCOPE, ...ALL_ACCOUNT_SCOPES]) {
- for (const [key, entry] of await backend.load(scope)) {
- entries.set(identity(scope, key), entry.value);
- }
- }
- return entries;
-}
-
-function installLockManager(): {readonly names: Array<string>} {
- const names: Array<string> = [];
- let tail: Promise<unknown> = Promise.resolve();
- const manager = {
- request<T>(name: string, callback: () => Promise<T>): Promise<T> {
- names.push(name);
- const run = tail.then(() => callback());
- tail = run.then(
- () => undefined,
- () => undefined,
- );
- return run;
- },
- };
- Object.defineProperty(navigator, 'locks', {value: manager, configurable: true, writable: true});
- return {names};
-}
-
-beforeEach(() => {
- vi.resetModules();
- Object.defineProperty(window, 'indexedDB', {value: new IDBFactory(), configurable: true, writable: true});
- installLockManager();
- installRuntimeBootstrap();
- window.localStorage.clear();
-});
-
-afterEach(() => {
- Object.defineProperty(navigator, 'locks', {value: null, configurable: true, writable: true});
- window.localStorage.clear();
-});
-
-describe('the migration plan', () => {
- test('pins the names item 34 must clear and item 40 must invalidate', async () => {
- const {migration} = await loadModules();
-
- expect(migration.LEGACY_APP_STORAGE_MIGRATION_MARKER_KEY).toBe('fluxer:migration:legacy-app-storage');
- expect(migration.LEGACY_APP_STORAGE_UNCLASSIFIED_KEYS_KEY).toBe('fluxer:migration:unclassified-legacy-keys');
- expect(migration.LEGACY_APP_STORAGE_MIGRATION_VERSION).toBe(1);
- expect(Object.values(migration.LegacyAppStorageMigrationStatus)).toEqual([
- 'migrated',
- 'partial',
- 'already-done',
- 'skipped',
- 'failed',
- ]);
- expect(Object.values(migration.LegacyAppStorageMigrationSkipReason)).toEqual([
- 'memory-backend',
- 'no-local-storage',
- 'no-instance-key',
- 'accounts-not-authoritative',
- 'scope-not-pending',
- ]);
- });
-
- test('matches the golden corpus destination for destination and byte for byte', async () => {
- const {migration} = await loadModules();
-
- const plan = migration.buildLegacyAppStorageMigrationPlan({
- storage: window.localStorage,
- accounts: KEYED_ACCOUNTS,
- contentScope: ACTIVE_SCOPE,
- sharedContentScopes: DEPLOYED_ACCOUNT_SCOPES,
- });
-
- expect(plan.scopes).toEqual(ALL_ACCOUNT_SCOPES);
- expect(plan.contentScope).toBe(ACTIVE_SCOPE);
- expect(planEntries(plan.writes)).toEqual(expectedPlanEntries());
- expect(plan.writes.every((write) => write.ifAbsent === true)).toBe(true);
- });
-
- test('every deployed corpus key is resolved by the key map or explicitly not migrated', async () => {
- const {migration} = await loadModules();
- const {isNotMigratedLegacyKey, resolveLegacyAppStorageKey} = await import(
- '@app/features/platform/state/LegacyAppStorageKeyMap'
- );
-
- for (const entry of GOLDEN_DEPLOYED_STORAGE_ENTRIES) {
- const covered = resolveLegacyAppStorageKey(entry.key) != null || isNotMigratedLegacyKey(entry.key);
- expect(covered, `${entry.key} resolves to nothing`).toBe(true);
- }
-
- const plan = migration.buildLegacyAppStorageMigrationPlan({
- storage: window.localStorage,
- accounts: KEYED_ACCOUNTS,
- contentScope: ACTIVE_SCOPE,
- sharedContentScopes: DEPLOYED_ACCOUNT_SCOPES,
- });
- expect([...plan.unclassifiedKeys].sort()).toEqual(GOLDEN_UNKNOWN_STORAGE_ENTRIES.map((entry) => entry.key).sort());
- });
-
- test('content the deployed build swapped per account lands in the active scope only, content it shared lands in every deployed account, and the synced-preference wire keys land nowhere', async () => {
- const {migration} = await loadModules();
-
- const plan = migration.buildLegacyAppStorageMigrationPlan({
- storage: window.localStorage,
- accounts: KEYED_ACCOUNTS,
- contentScope: ACTIVE_SCOPE,
- sharedContentScopes: DEPLOYED_ACCOUNT_SCOPES,
- });
- const scopesByKey = new Map<string, Array<string>>();
- for (const write of plan.writes) {
- scopesByKey.set(write.key, [...(scopesByKey.get(write.key) ?? []), write.scope]);
- }
-
- for (const legacyKey of OWNED_CONTENT_STORAGE_KEYS) {
- expect(scopesByKey.get(legacyKey), legacyKey).toEqual([ACTIVE_SCOPE]);
- }
- for (const legacyKey of SHARED_CONTENT_STORAGE_KEYS) {
- expect(scopesByKey.get(legacyKey)?.sort(), legacyKey).toEqual(DEPLOYED_ACCOUNT_SCOPES);
- }
- for (const legacyKey of NOT_MIGRATED_STORAGE_KEYS) {
- expect(scopesByKey.has(legacyKey), legacyKey).toBe(false);
- }
- for (const rawKey of ['token', 'userId', 'runtimeConfig', 'AccountManager']) {
- expect(scopesByKey.has(rawKey), rawKey).toBe(false);
- }
- expect(scopesByKey.get('UserSettings:syncedPreferencesLocal')?.sort()).toEqual([...ALL_ACCOUNT_SCOPES].sort());
- expect(scopesByKey.get('Theme')).toEqual([GLOBAL_SCOPE]);
- });
-
- test('a per-user neko key lands in that account scope only, under the name the reader asks for', async () => {
- const {migration} = await loadModules();
-
- const plan = migration.buildLegacyAppStorageMigrationPlan({
- storage: window.localStorage,
- accounts: KEYED_ACCOUNTS,
- contentScope: ACTIVE_SCOPE,
- sharedContentScopes: DEPLOYED_ACCOUNT_SCOPES,
- });
- const entries = planEntries(plan.writes);
-
- const perUserKey = `Accessibility:showNeko:${OTHER_USER_ID}`;
- expect(entries.get(identity(OTHER_SCOPE, perUserKey))).toBe('false');
- expect(entries.has(identity(ACTIVE_SCOPE, perUserKey))).toBe(false);
- expect(entries.has(identity(UNAUTHENTICATED_SCOPE, perUserKey))).toBe(false);
- for (const scope of ALL_ACCOUNT_SCOPES) {
- expect(entries.get(identity(scope, 'Accessibility:showNeko')), scope).toBe('true');
- }
- });
-
- test('a suffixed key naming an unknown account is skipped rather than routed to the active scope', async () => {
- const {migration} = await loadModules();
- window.localStorage.setItem('Accessibility:showNeko:999000000000000999', 'false');
-
- const plan = migration.buildLegacyAppStorageMigrationPlan({
- storage: window.localStorage,
- accounts: KEYED_ACCOUNTS,
- contentScope: ACTIVE_SCOPE,
- sharedContentScopes: DEPLOYED_ACCOUNT_SCOPES,
- });
- const entries = planEntries(plan.writes);
-
- expect(entries.get(identity(ACTIVE_SCOPE, 'Accessibility:showNeko'))).toBe('true');
- expect([...entries.keys()].filter((key) => key.includes('999000000000000999'))).toEqual([]);
- expect(window.localStorage.getItem('Accessibility:showNeko:999000000000000999')).toBe('false');
- });
-
- test('an active scope outside the account list degrades to the unauthenticated scope', async () => {
- const {migration} = await loadModules();
-
- const plan = migration.buildLegacyAppStorageMigrationPlan({
- storage: window.localStorage,
- accounts: KEYED_ACCOUNTS,
- contentScope: `${FIXTURE_CURRENT_INSTANCE_KEY}::404000000000000404`,
- sharedContentScopes: [],
- });
-
- expect(plan.contentScope).toBe(UNAUTHENTICATED_SCOPE);
- expect(planEntries(plan.writes).get(identity(UNAUTHENTICATED_SCOPE, 'Drafts'))).toBe(
- window.localStorage.getItem('Drafts'),
- );
- });
-
- test('an account the deployed build swapped storage for keeps its own snapshot, and the live values stay with the active account', async () => {
- const {migration} = await loadModules();
- const ownedByOther = {
- token: `token.${OTHER_USER_ID}`,
- userId: OTHER_USER_ID,
- 'fluxer:ui:sidebar-width': '331',
- 'fluxer_scheduled_maintenance_dismissed:4242': '1',
- 'fluxer:experimental:unshipped-toggle': 'off',
- 'fluxer:media_caps:v2': '{"other":true}',
- 'fluxer:domain-migration': '{"other":true}',
- };
- const accounts = KEYED_ACCOUNTS.map((account) => ({
- ...account,
- localStorageData: account.userId === OTHER_USER_ID ? ownedByOther : {'fluxer:ui:sidebar-width': '205'},
- managedStorageData: account.userId === OTHER_USER_ID ? ownedByOther : {'fluxer:ui:sidebar-width': '205'},
- }));
-
- const plan = migration.buildLegacyAppStorageMigrationPlan({
- storage: window.localStorage,
- accounts,
- contentScope: ACTIVE_SCOPE,
- sharedContentScopes: DEPLOYED_ACCOUNT_SCOPES,
- });
- const entries = planEntries(plan.writes);
-
- expect(entries.get(identity(ACTIVE_SCOPE, 'fluxer:ui:sidebar-width'))).toBe('286');
- expect(entries.get(identity(OTHER_SCOPE, 'fluxer:ui:sidebar-width'))).toBe('331');
- expect(entries.has(identity(UNAUTHENTICATED_SCOPE, 'fluxer:ui:sidebar-width'))).toBe(false);
- expect(entries.get(identity(OTHER_SCOPE, 'fluxer_scheduled_maintenance_dismissed:4242'))).toBe('1');
- expect(entries.has(identity(ACTIVE_SCOPE, 'fluxer_scheduled_maintenance_dismissed:4242'))).toBe(false);
- expect(entries.get(identity(OTHER_SCOPE, 'fluxer:experimental:unshipped-toggle'))).toBe('off');
- expect(entries.get(identity(GLOBAL_SCOPE, 'fluxer:experimental:unshipped-toggle'))).toBe('on');
- expect(entries.get(identity(GLOBAL_SCOPE, 'fluxer:media_caps:v2'))).toBe(
- window.localStorage.getItem('fluxer:media_caps:v2'),
- );
- for (const neverCarried of ['token', 'userId', 'fluxer:media_caps:v2', 'fluxer:domain-migration']) {
- expect(entries.has(identity(OTHER_SCOPE, neverCarried)), neverCarried).toBe(false);
- }
- });
-
- test('shared content reaches only the accounts the deployed build stored, never one added since', async () => {
- const {migration} = await loadModules();
-
- const plan = migration.buildLegacyAppStorageMigrationPlan({
- storage: window.localStorage,
- accounts: THREE_KEYED_ACCOUNTS,
- contentScope: ACTIVE_SCOPE,
- sharedContentScopes: DEPLOYED_ACCOUNT_SCOPES,
- });
- const entries = planEntries(plan.writes);
-
- for (const contentKey of CONTENT_STORAGE_KEYS) {
- expect(entries.has(identity(THIRD_SCOPE, contentKey)), contentKey).toBe(false);
- expect(entries.has(identity(UNAUTHENTICATED_SCOPE, contentKey)), contentKey).toBe(false);
- }
- for (const contentKey of SHARED_CONTENT_STORAGE_KEYS) {
- expect(entries.get(identity(OTHER_SCOPE, contentKey)), contentKey).toBe(window.localStorage.getItem(contentKey));
- }
- expect(entries.get(identity(THIRD_SCOPE, 'Notification'))).toBe(window.localStorage.getItem('Notification'));
- });
-
- test('with no content scope nothing an account owns is planted anywhere', async () => {
- const {migration} = await loadModules();
-
- const plan = migration.buildLegacyAppStorageMigrationPlan({
- storage: window.localStorage,
- accounts: KEYED_ACCOUNTS,
- contentScope: null,
- sharedContentScopes: [],
- });
-
- expect(plan.contentScope).toBeNull();
- for (const contentKey of CONTENT_STORAGE_KEYS) {
- expect(
- plan.writes.some((write) => write.key === contentKey),
- contentKey,
- ).toBe(false);
- }
- });
-
- test('the raw mirror written by the scoped storage layer is never captured', async () => {
- const {migration} = await loadModules();
- window.localStorage.setItem(`fluxer:app-storage-mirror:${OTHER_SCOPE}::Drafts`, 'mirrored');
-
- const plan = migration.buildLegacyAppStorageMigrationPlan({
- storage: window.localStorage,
- accounts: KEYED_ACCOUNTS,
- contentScope: ACTIVE_SCOPE,
- sharedContentScopes: DEPLOYED_ACCOUNT_SCOPES,
- });
-
- expect(plan.writes.some((write) => write.value === 'mirrored')).toBe(false);
- expect(plan.unclassifiedKeys.some((key) => key.startsWith('fluxer:app-storage-mirror:'))).toBe(false);
- });
-});
-
-describe('the module graph', () => {
- async function staticImportClosure(entry: string): Promise<Array<string>> {
- const {readFileSync, existsSync} = await import('node:fs');
- const {dirname, join, relative, resolve} = await import('node:path');
- const {fileURLToPath} = await import('node:url');
- const sourceRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../../..');
-
- const resolveSpecifier = (specifier: string): string | null => {
- if (!specifier.startsWith('@app/')) {
- return null;
- }
- const base = join(sourceRoot, specifier.slice('@app/'.length));
- return [`${base}.ts`, `${base}.tsx`].find((candidate) => existsSync(candidate)) ?? null;
- };
-
- const visited = new Set<string>();
- const walk = (file: string): void => {
- if (visited.has(file)) {
- return;
- }
- visited.add(file);
- const pattern = /^import\s+([\s\S]*?)from\s+'([^']+)'/gm;
- const source = readFileSync(file, 'utf8');
- let match = pattern.exec(source);
- while (match != null) {
- const resolved = /^\s*type\s/.test(match[1]) ? null : resolveSpecifier(match[2]);
- if (resolved != null) {
- walk(resolved);
- }
- match = pattern.exec(source);
- }
- };
- walk(join(sourceRoot, entry));
- return [...visited].map((file) => relative(sourceRoot, file));
- }
-
- test('never reaches RuntimeConfig, whose constructor throws on an older server', async () => {
- const closure = await staticImportClosure('features/platform/state/LegacyAppStorageMigration.ts');
-
- expect(closure).not.toContain('features/app/state/RuntimeConfig.ts');
- });
-
- test('is never imported by the scoped storage module, which would close a boot-path cycle', async () => {
- const closure = await staticImportClosure('features/platform/state/PersistentStorage.ts');
-
- expect(closure).not.toContain('features/platform/state/LegacyAppStorageMigration.ts');
- });
-});
-
-describe('running the migration', () => {
- test('writes the whole plan and the marker, and never deletes a legacy entry', async () => {
- const {migration, backendModule} = await loadModules();
- const backend = backendModule.createPersistentStorageBackend(window.indexedDB);
- const corpusBefore = readGoldenLocalStorageSnapshot(window.localStorage);
-
- const result = await migration.runLegacyAppStorageMigration({
- backend,
- accounts: accountSource(),
- currentAccount: CURRENT_ACCOUNT,
- now: FIXTURE_NOW,
- });
-
- expect(result.status).toBe('migrated');
- expect(result.contentScope).toBe(ACTIVE_SCOPE);
- expect(result.scopes).toEqual(ALL_ACCOUNT_SCOPES);
- expect(result.pendingScopes).toEqual([]);
-
- const stored = await readBackend(backend);
- const marker = stored.get(identity(GLOBAL_SCOPE, 'fluxer:migration:legacy-app-storage'));
- expect(marker).toBe(completeMarker({status: 'complete', pendingScopes: []}));
- stored.delete(identity(GLOBAL_SCOPE, 'fluxer:migration:legacy-app-storage'));
- expect(stored).toEqual(expectedPlanEntries());
- expect(readGoldenLocalStorageSnapshot(window.localStorage)).toEqual(corpusBefore);
- });
-
- test('three runs are idempotent and a value the user changed between runs survives', async () => {
- const {migration, backendModule} = await loadModules();
- const backend = backendModule.createPersistentStorageBackend(window.indexedDB);
- const request = {
- backend,
- accounts: accountSource(),
- currentAccount: CURRENT_ACCOUNT,
- now: FIXTURE_NOW,
- };
-
- expect((await migration.runLegacyAppStorageMigration(request)).status).toBe('migrated');
- const afterFirstRun = await readBackend(backend);
-
- await backend.set(GLOBAL_SCOPE, 'Theme', '{"localTheme":"light"}');
- await backend.delete(GLOBAL_SCOPE, 'fluxer:migration:legacy-app-storage');
- expect((await migration.runLegacyAppStorageMigration(request)).status).toBe('migrated');
-
- await backend.delete(GLOBAL_SCOPE, 'fluxer:migration:legacy-app-storage');
- expect((await migration.runLegacyAppStorageMigration(request)).status).toBe('migrated');
-
- const afterThirdRun = await readBackend(backend);
- expect(afterThirdRun.get(identity(GLOBAL_SCOPE, 'Theme'))).toBe('{"localTheme":"light"}');
- afterFirstRun.set(identity(GLOBAL_SCOPE, 'Theme'), '{"localTheme":"light"}');
- expect(afterThirdRun).toEqual(afterFirstRun);
- });
-
- test('a marker already at the current version stops the migration before it reads localStorage', async () => {
- const {migration, backendModule} = await loadModules();
- const backend = backendModule.createPersistentStorageBackend(window.indexedDB);
- await backend.set(
- GLOBAL_SCOPE,
- 'fluxer:migration:legacy-app-storage',
- completeMarker({status: 'complete', pendingScopes: []}),
- );
- let consulted = false;
-
- const result = await migration.runLegacyAppStorageMigration({
- backend,
- accounts: {
- migrateAccountStorageKeys: () => {
- consulted = true;
- return accountSource().migrateAccountStorageKeys();
- },
- },
- currentAccount: CURRENT_ACCOUNT,
- now: FIXTURE_NOW,
- });
-
- expect(result.status).toBe('already-done');
- expect(consulted).toBe(false);
- expect((await readBackend(backend)).size).toBe(1);
- });
-
- test('a marker written while accounts were still deferred does not stop the next run', async () => {
- const {migration, backendModule} = await loadModules();
- const backend = backendModule.createPersistentStorageBackend(window.indexedDB);
- await backend.set(
- GLOBAL_SCOPE,
- 'fluxer:migration:legacy-app-storage',
- completeMarker({status: 'partial', pendingScopes: [], deferredAccounts: 1}),
- );
-
- const result = await migration.runLegacyAppStorageMigration({
- backend,
- accounts: accountSource(),
- currentAccount: CURRENT_ACCOUNT,
- now: FIXTURE_NOW,
- });
-
- expect(result.status).toBe('migrated');
- const stored = await readBackend(backend);
- expect(stored.get(identity(GLOBAL_SCOPE, 'fluxer:migration:legacy-app-storage'))).toBe(
- completeMarker({status: 'complete', pendingScopes: []}),
- );
- expect(stored.get(identity(OTHER_SCOPE, 'UserSettings:syncedPreferencesLocal'))).toBe(
- window.localStorage.getItem('UserSettings:syncedPreferencesLocal'),
- );
- });
-
- test('a run after a deferred account qualifies gives it the shared content and leaves the swapped content with its owner', async () => {
- const {migration, backendModule} = await loadModules();
- const backend = backendModule.createPersistentStorageBackend(window.indexedDB);
- const activeOnly = KEYED_ACCOUNTS.filter((account) => account.userId === ACTIVE_USER_ID);
- const deferred = KEYED_ACCOUNTS.filter((account) => account.userId !== ACTIVE_USER_ID);
- const first = await migration.runLegacyAppStorageMigration({
- backend,
- accounts: accountSource({status: 'deferred', qualifiedRecords: [...activeOnly], deferredRecords: [...deferred]}),
- currentAccount: CURRENT_ACCOUNT,
- now: FIXTURE_NOW,
- });
- expect(first.status).toBe('partial');
- expect(first.deferredAccounts).toBe(1);
- expect((await backend.get(GLOBAL_SCOPE, 'fluxer:migration:legacy-app-storage'))?.value).toBe(
- completeMarker({
- status: 'partial',
- pendingScopes: [],
- deferredAccounts: 1,
- sharedContentScopes: [ACTIVE_SCOPE],
- deferredUserIds: [OTHER_USER_ID],
- }),
- );
- const other = KEYED_ACCOUNTS.find((account) => account.userId === OTHER_USER_ID)!;
-
- const second = await migration.runLegacyAppStorageMigration({
- backend,
- accounts: accountSource(),
- currentAccount: {userId: OTHER_USER_ID, token: other.token!, instance: FIXTURE_CURRENT_INSTANCE_SNAPSHOT},
- now: FIXTURE_NOW,
- });
-
- expect(second.status).toBe('migrated');
- expect(second.contentScope).toBe(ACTIVE_SCOPE);
- const stored = await readBackend(backend);
- for (const contentKey of CONTENT_STORAGE_KEYS) {
- expect(stored.get(identity(ACTIVE_SCOPE, contentKey)), contentKey).toBe(window.localStorage.getItem(contentKey));
- }
- for (const contentKey of OWNED_CONTENT_STORAGE_KEYS) {
- expect(stored.has(identity(OTHER_SCOPE, contentKey)), contentKey).toBe(false);
- }
- for (const contentKey of SHARED_CONTENT_STORAGE_KEYS) {
- expect(stored.get(identity(OTHER_SCOPE, contentKey)), contentKey).toBe(window.localStorage.getItem(contentKey));
- }
- expect(stored.get(identity(OTHER_SCOPE, 'Notification'))).toBe(window.localStorage.getItem('Notification'));
- expect(stored.get(identity(GLOBAL_SCOPE, 'fluxer:migration:legacy-app-storage'))).toBe(
- completeMarker({status: 'complete', pendingScopes: []}),
- );
- });
-
- test('an account added after the upgrade never receives legacy content when a later run completes the migration', async () => {
- const {migration, backendModule} = await loadModules();
- const backend = backendModule.createPersistentStorageBackend(window.indexedDB);
- const activeOnly = KEYED_ACCOUNTS.filter((account) => account.userId === ACTIVE_USER_ID);
- const deferred = KEYED_ACCOUNTS.filter((account) => account.userId !== ACTIVE_USER_ID);
- const addedSince = THREE_KEYED_ACCOUNTS.filter((account) => account.userId === THIRD_USER_ID);
- await migration.runLegacyAppStorageMigration({
- backend,
- accounts: accountSource({status: 'deferred', qualifiedRecords: [...activeOnly], deferredRecords: [...deferred]}),
- currentAccount: CURRENT_ACCOUNT,
- now: FIXTURE_NOW,
- });
-
- const stillDeferred = await migration.runLegacyAppStorageMigration({
- backend,
- accounts: accountSource({
- status: 'deferred',
- qualifiedRecords: [...activeOnly, ...addedSince],
- deferredRecords: [...deferred],
- }),
- currentAccount: CURRENT_ACCOUNT,
- now: FIXTURE_NOW,
- });
- expect(stillDeferred.status).toBe('partial');
-
- const completed = await migration.runLegacyAppStorageMigration({
- backend,
- accounts: accountSource({qualifiedRecords: [...THREE_KEYED_ACCOUNTS]}),
- currentAccount: CURRENT_ACCOUNT,
- now: FIXTURE_NOW,
- });
-
- expect(completed.status).toBe('migrated');
- for (const contentKey of CONTENT_STORAGE_KEYS) {
- expect(await backend.get(THIRD_SCOPE, contentKey), contentKey).toBeNull();
- }
- for (const contentKey of SHARED_CONTENT_STORAGE_KEYS) {
- expect((await backend.get(OTHER_SCOPE, contentKey))?.value, contentKey).toBe(
- window.localStorage.getItem(contentKey),
- );
- }
- expect((await backend.get(THIRD_SCOPE, 'Notification'))?.value).toBe(window.localStorage.getItem('Notification'));
- expect((await backend.get(GLOBAL_SCOPE, 'fluxer:migration:legacy-app-storage'))?.value).toBe(
- completeMarker({status: 'complete', pendingScopes: []}),
- );
- });
-
- test('a memory backend is skipped and never marked', async () => {
- const {migration, backendModule} = await loadModules();
- const backend = backendModule.createPersistentStorageBackend(null);
-
- const result = await migration.runLegacyAppStorageMigration({
- backend,
- accounts: accountSource(),
- currentAccount: CURRENT_ACCOUNT,
- now: FIXTURE_NOW,
- });
-
- expect(result).toMatchObject({status: 'skipped', reason: 'memory-backend'});
- expect(await backend.get(GLOBAL_SCOPE, 'fluxer:migration:legacy-app-storage')).toBeNull();
- expect((await readBackend(backend)).size).toBe(0);
- });
-
- test('a non-authoritative account list is skipped and never marked', async () => {
- const {migration, backendModule} = await loadModules();
- const backend = backendModule.createPersistentStorageBackend(window.indexedDB);
-
- const result = await migration.runLegacyAppStorageMigration({
- backend,
- accounts: accountSource({status: 'skipped', source: 'desktop', qualifiedRecords: []}),
- currentAccount: CURRENT_ACCOUNT,
- now: FIXTURE_NOW,
- });
-
- expect(result).toMatchObject({status: 'skipped', reason: 'accounts-not-authoritative'});
- expect((await readBackend(backend)).size).toBe(0);
- });
-
- test('a failed account re-key is skipped rather than fanned out into unauthenticated alone', async () => {
- const {migration, backendModule} = await loadModules();
- const backend = backendModule.createPersistentStorageBackend(window.indexedDB);
-
- const result = await migration.runLegacyAppStorageMigration({
- backend,
- accounts: accountSource({status: 'failed', qualifiedRecords: []}),
- currentAccount: CURRENT_ACCOUNT,
- now: FIXTURE_NOW,
- });
-
- expect(result).toMatchObject({status: 'skipped', reason: 'accounts-not-authoritative'});
- expect((await readBackend(backend)).size).toBe(0);
- });
-
- test('an unusable active instance writes nothing and activates nothing', async () => {
- const {migration, backendModule} = await loadModules();
- const backend = backendModule.createPersistentStorageBackend(window.indexedDB);
- const unkeyable = {...FIXTURE_CURRENT_INSTANCE_SNAPSHOT, apiEndpoint: 'https://user:[email protected]/api?tenant=1'};
-
- const result = await migration.runLegacyAppStorageMigration({
- backend,
- accounts: accountSource(),
- currentAccount: {...CURRENT_ACCOUNT, instance: unkeyable},
- now: FIXTURE_NOW,
- });
-
- expect(result).toMatchObject({status: 'skipped', reason: 'no-instance-key'});
- expect(result.contentScope).toBe(UNAUTHENTICATED_SCOPE);
- expect(result.scopes).toEqual([]);
- expect((await readBackend(backend)).size).toBe(0);
- });
-
- test('a throwing backend leaves no marker and does not reject', async () => {
- const {migration, backendModule} = await loadModules();
- const backend = backendModule.createPersistentStorageBackend(window.indexedDB);
- const failing: PersistentStorageBackend = {
- ...backend,
- setMany: () => Promise.reject(new backendModule.AppStorageOperationError('write entries')),
- };
-
- const result = await migration.runLegacyAppStorageMigration({
- backend: failing,
- accounts: accountSource(),
- currentAccount: CURRENT_ACCOUNT,
- now: FIXTURE_NOW,
- });
-
- expect(result.status).toBe('failed');
- expect(await backend.get(GLOBAL_SCOPE, 'fluxer:migration:legacy-app-storage')).toBeNull();
- expect((await readBackend(backend)).size).toBe(0);
- });
-
- test('exactly one tab writes the plan when the migration lock serialises them', async () => {
- const {migration, backendModule} = await loadModules();
- const lock = installLockManager();
- const backend = backendModule.createPersistentStorageBackend(window.indexedDB);
- let setManyCalls = 0;
- const counting: PersistentStorageBackend = {
- ...backend,
- setMany: (writes) => {
- setManyCalls += 1;
- return backend.setMany(writes);
- },
- };
- const request = {
- backend: counting,
- accounts: accountSource(),
- currentAccount: CURRENT_ACCOUNT,
- now: FIXTURE_NOW,
- };
-
- const [first, second] = await Promise.all([
- migration.runLegacyAppStorageMigration(request),
- migration.runLegacyAppStorageMigration(request),
- ]);
-
- expect(lock.names).toEqual(['fluxer:app-storage:migration', 'fluxer:app-storage:migration']);
- expect([first.status, second.status]).toEqual(['migrated', 'already-done']);
- expect(setManyCalls).toBe(1);
- });
-});
-
-describe('quota degradation and first-touch completion', () => {
- const limits = {maxTotalBytes: 1, maxEntries: 1};
-
- test('a plan over the caps seeds the active scope and records the rest as pending', async () => {
- const {migration, backendModule} = await loadModules();
- const backend = backendModule.createPersistentStorageBackend(window.indexedDB);
-
- const result = await migration.runLegacyAppStorageMigration({
- backend,
- accounts: accountSource(),
- currentAccount: CURRENT_ACCOUNT,
- now: FIXTURE_NOW,
- limits,
- });
-
- expect(result.status).toBe('partial');
- expect(result.pendingScopes).toEqual([OTHER_SCOPE]);
- const stored = await readBackend(backend);
- expect(stored.get(identity(GLOBAL_SCOPE, 'fluxer:migration:legacy-app-storage'))).toBe(
- completeMarker({status: 'partial', pendingScopes: [OTHER_SCOPE]}),
- );
- expect([...stored.keys()].some((key) => key.startsWith(OTHER_SCOPE))).toBe(false);
- expect(stored.get(identity(ACTIVE_SCOPE, 'Drafts'))).toBe(window.localStorage.getItem('Drafts'));
- });
-
- test('a plan over the caps still seeds the global scope, which no pending-scope pass revisits', async () => {
- const {migration, backendModule} = await loadModules();
- const backend = backendModule.createPersistentStorageBackend(window.indexedDB);
-
- const result = await migration.runLegacyAppStorageMigration({
- backend,
- accounts: accountSource(),
- currentAccount: CURRENT_ACCOUNT,
- now: FIXTURE_NOW,
- limits,
- });
-
- expect(result.pendingScopes).toEqual([OTHER_SCOPE]);
- const stored = await readBackend(backend);
- expect(stored.get(identity(GLOBAL_SCOPE, 'Theme'))).toBe(window.localStorage.getItem('Theme'));
- expect(stored.get(identity(GLOBAL_SCOPE, 'fluxer:migration:unclassified-legacy-keys'))).toBe(
- JSON.stringify(GOLDEN_UNKNOWN_STORAGE_ENTRIES.map((entry) => entry.key).sort()),
- );
- });
-
- test('a QuotaExceededError from the transaction degrades to the same partial plan', async () => {
- const {migration, backendModule} = await loadModules();
- const backend = backendModule.createPersistentStorageBackend(window.indexedDB);
- let attempts = 0;
- const quotaBound: PersistentStorageBackend = {
- ...backend,
- setMany: (writes) => {
- attempts += 1;
- if (attempts === 1) {
- return Promise.reject(new backendModule.AppStorageQuotaExceededError('write entries'));
- }
- return backend.setMany(writes);
- },
- };
-
- const result = await migration.runLegacyAppStorageMigration({
- backend: quotaBound,
- accounts: accountSource(),
- currentAccount: CURRENT_ACCOUNT,
- now: FIXTURE_NOW,
- });
-
- expect(attempts).toBe(2);
- expect(result.status).toBe('partial');
- expect(result.pendingScopes).toEqual([OTHER_SCOPE]);
- });
-
- test('a persistent QuotaExceededError leaves no marker at all', async () => {
- const {migration, backendModule} = await loadModules();
- const backend = backendModule.createPersistentStorageBackend(window.indexedDB);
- const quotaBound: PersistentStorageBackend = {
- ...backend,
- setMany: () => Promise.reject(new backendModule.AppStorageQuotaExceededError('write entries')),
- };
-
- const result = await migration.runLegacyAppStorageMigration({
- backend: quotaBound,
- accounts: accountSource(),
- currentAccount: CURRENT_ACCOUNT,
- now: FIXTURE_NOW,
- });
-
- expect(result.status).toBe('failed');
- expect(await backend.get(GLOBAL_SCOPE, 'fluxer:migration:legacy-app-storage')).toBeNull();
- });
-
- test('first touch completes a pending scope write-if-absent with the shared content and none another account owns', async () => {
- const {migration, backendModule} = await loadModules();
- const backend = backendModule.createPersistentStorageBackend(window.indexedDB);
- const request = {
- backend,
- accounts: accountSource(),
- currentAccount: CURRENT_ACCOUNT,
- now: FIXTURE_NOW,
- limits,
- };
- await migration.runLegacyAppStorageMigration(request);
- await backend.set(OTHER_SCOPE, 'Accessibility:motion', '{"userChanged":true}');
-
- const completed = await migration.completePendingLegacyAppStorageScope(request, OTHER_SCOPE);
-
- expect(completed.status).toBe('migrated');
- expect(completed.pendingScopes).toEqual([]);
- const stored = await readBackend(backend);
- expect(stored.get(identity(GLOBAL_SCOPE, 'fluxer:migration:legacy-app-storage'))).toBe(
- completeMarker({status: 'complete', pendingScopes: []}),
- );
- expect(stored.get(identity(OTHER_SCOPE, 'Accessibility:motion'))).toBe('{"userChanged":true}');
- expect(stored.get(identity(OTHER_SCOPE, `Accessibility:showNeko:${OTHER_USER_ID}`))).toBe('false');
- expect(stored.get(identity(OTHER_SCOPE, 'UserSettings:syncedPreferencesLocal'))).toBe(
- window.localStorage.getItem('UserSettings:syncedPreferencesLocal'),
- );
- for (const contentKey of OWNED_CONTENT_STORAGE_KEYS) {
- expect(stored.has(identity(OTHER_SCOPE, contentKey)), contentKey).toBe(false);
- }
- for (const contentKey of SHARED_CONTENT_STORAGE_KEYS) {
- expect(stored.get(identity(OTHER_SCOPE, contentKey)), contentKey).toBe(window.localStorage.getItem(contentKey));
- }
- });
-
- test('completing one pending scope leaves every other pending scope waiting for its own first touch', async () => {
- const {migration, backendModule} = await loadModules();
- const backend = backendModule.createPersistentStorageBackend(window.indexedDB);
- const request = {
- backend,
- accounts: accountSource({qualifiedRecords: [...THREE_KEYED_ACCOUNTS]}),
- currentAccount: CURRENT_ACCOUNT,
- now: FIXTURE_NOW,
- limits,
- };
- const seeded = await migration.runLegacyAppStorageMigration(request);
- expect(seeded.pendingScopes).toEqual([OTHER_SCOPE, THIRD_SCOPE]);
-
- const first = await migration.completePendingLegacyAppStorageScope(request, OTHER_SCOPE);
-
- expect(first.status).toBe('partial');
- expect(first.pendingScopes).toEqual([THIRD_SCOPE]);
- expect((await backend.get(GLOBAL_SCOPE, 'fluxer:migration:legacy-app-storage'))?.value).toBe(
- completeMarker({
- status: 'partial',
- pendingScopes: [THIRD_SCOPE],
- sharedContentScopes: [ACTIVE_SCOPE, OTHER_SCOPE, THIRD_SCOPE],
- }),
- );
-
- const second = await migration.completePendingLegacyAppStorageScope(request, THIRD_SCOPE);
-
- expect(second.status).toBe('migrated');
- expect(second.pendingScopes).toEqual([]);
- expect((await backend.get(THIRD_SCOPE, 'UserSettings:syncedPreferencesLocal'))?.value).toBe(
- window.localStorage.getItem('UserSettings:syncedPreferencesLocal'),
- );
- });
-
- test('completing a scope that is not pending writes nothing', async () => {
- const {migration, backendModule} = await loadModules();
- const backend = backendModule.createPersistentStorageBackend(window.indexedDB);
- const request = {
- backend,
- accounts: accountSource(),
- currentAccount: CURRENT_ACCOUNT,
- now: FIXTURE_NOW,
- };
- await migration.runLegacyAppStorageMigration(request);
- const before = await readBackend(backend);
-
- const completed = await migration.completePendingLegacyAppStorageScope(request, OTHER_SCOPE);
-
- expect(completed).toMatchObject({status: 'skipped', reason: 'scope-not-pending'});
- expect(await readBackend(backend)).toEqual(before);
- });
-});
diff --git a/fluxer_app/src/features/platform/state/LegacyOriginUpgrade.test.ts b/fluxer_app/src/features/platform/state/LegacyOriginUpgrade.test.ts
deleted file mode 100644
index a2ae91c51..000000000
--- a/fluxer_app/src/features/platform/state/LegacyOriginUpgrade.test.ts
+++ /dev/null
@@ -1,681 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- FIXTURE_CURRENT_INSTANCE_KEY,
- FIXTURE_CURRENT_INSTANCE_SNAPSHOT,
- FIXTURE_NOW,
-} from '@app/features/auth/state/__fixtures__/AccountRecordFixtures';
-import {
- createFakeDesktopStore,
- type FakeDesktopStore,
-} from '@app/features/platform/state/__fixtures__/DesktopStoreFixture';
-import {
- expectedGoldenStorageRows,
- GOLDEN_LOCAL_STORAGE_CORPUS,
- goldenStorageRowIdentity,
- NOT_MIGRATED_STORAGE_KEYS,
-} from '@app/features/platform/state/__fixtures__/LegacyStorageFixtures';
-import {installRuntimeBootstrap} from '@app/features/platform/state/__fixtures__/RuntimeBootstrapFixture';
-import type {
- AppStorageFinalizationResult,
- AppStorageSessionAccount,
-} from '@app/features/platform/state/AppStorageBootstrap';
-import {AppStorageKey} from '@app/features/platform/state/AppStorageKeys';
-import {
- APP_STORAGE_INDEXED_DB_NAME,
- APP_STORAGE_OBJECT_STORE,
-} from '@app/features/platform/state/PersistentStorageBackend';
-import {getProtectedIndexedDB} from '@app/features/platform/state/ProtectedWebStorage';
-import type {ElectronAPI} from '@app/types/electron.d';
-import type {DesktopLegacyHarvest, DesktopLegacyHarvestStore} from '@fluxer/desktop_ipc/src/LegacyHarvestContract';
-import {
- DESKTOP_LEGACY_RAW_STORAGE_SEED_MARKER_KEY,
- DESKTOP_LEGACY_RAW_STORAGE_SEED_MARKER_VALUE,
-} from '@fluxer/desktop_ipc/src/LegacyHarvestContract';
-import {
- DESKTOP_LEGACY_AUTHORITY_MARKER_KEY,
- DESKTOP_LEGACY_AUTHORITY_MARKER_VALUE,
- DESKTOP_LEGACY_IMPORT_MARKER_KEY,
- DesktopLegacyImportPhase,
-} from '@fluxer/desktop_ipc/src/StorageContract';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
-
-type BootstrapModule = typeof import('@app/features/platform/state/AppStorageBootstrap');
-type PersistentStorageModule = typeof import('@app/features/platform/state/PersistentStorage');
-
-const LEGACY_ORIGIN = 'https://web.canary.fluxer.app';
-const ACTIVE_USER_ID = '100000000000000002';
-const OTHER_USER_ID = '100000000000000003';
-const ACTIVE_SCOPE = `${FIXTURE_CURRENT_INSTANCE_KEY}::${ACTIVE_USER_ID}`;
-const OTHER_SCOPE = `${FIXTURE_CURRENT_INSTANCE_KEY}::${OTHER_USER_ID}`;
-const UNAUTHENTICATED_SCOPE = 'unauthenticated';
-const GLOBAL_SCOPE = 'global';
-const ALL_ACCOUNT_SCOPES = [UNAUTHENTICATED_SCOPE, ACTIVE_SCOPE, OTHER_SCOPE];
-const SOUND_BYTES = new Uint8Array([7, 11, 13, 17, 19, 23]);
-const ACTIVE_TOKEN = GOLDEN_LOCAL_STORAGE_CORPUS.find((entry) => entry.key === 'token')!.value;
-
-const identity = goldenStorageRowIdentity;
-
-function expectedDesktopEntries(): Map<string, string> {
- return expectedGoldenStorageRows({
- global: GLOBAL_SCOPE,
- everyAccount: ALL_ACCOUNT_SCOPES,
- contentAccount: ACTIVE_SCOPE,
- sharedContent: [ACTIVE_SCOPE, OTHER_SCOPE],
- namedAccount: OTHER_SCOPE,
- });
-}
-
-function goldenCorpusRecord(): Record<string, string> {
- const record: Record<string, string> = {};
- for (const entry of GOLDEN_LOCAL_STORAGE_CORPUS) {
- record[entry.key] = entry.value;
- }
- return record;
-}
-
-function accountRecord(userId: string): Record<string, unknown> {
- return {
- userId,
- token: userId === ACTIVE_USER_ID ? ACTIVE_TOKEN : `token-${userId}`,
- userData: {id: userId, username: `user-${userId}`, discriminator: '0001', avatar: null},
- localStorageData: {userId},
- lastActive: FIXTURE_NOW - 1_000,
- instance: FIXTURE_CURRENT_INSTANCE_SNAPSHOT,
- };
-}
-
-function activeSessionAccount(): AppStorageSessionAccount {
- return {
- accountKey: ACTIVE_SCOPE,
- userId: ACTIVE_USER_ID,
- token: ACTIVE_TOKEN,
- instance: FIXTURE_CURRENT_INSTANCE_SNAPSHOT,
- };
-}
-
-async function startAndFinalize(bootstrap: BootstrapModule): Promise<AppStorageFinalizationResult> {
- const handle = await bootstrap.startAppStorage({scoped: true});
- return await handle.finalizeAfterSessionResolution(activeSessionAccount());
-}
-
-function installedCanaryStores(): ReadonlyArray<DesktopLegacyHarvestStore> {
- return [
- {
- database: 'FluxerAccounts',
- version: 2,
- store: 'accounts',
- records: [
- {key: null, value: accountRecord(ACTIVE_USER_ID)},
- {key: null, value: accountRecord(OTHER_USER_ID)},
- ],
- },
- {
- database: 'FluxerCustomSounds',
- version: 2,
- store: 'customSounds',
- records: [{key: null, value: {soundType: 'message', blob: SOUND_BYTES, edited: true}}],
- },
- {
- database: 'fluxer-theme-library',
- version: 1,
- store: 'themes',
- records: [{key: null, value: {id: 'midnight', name: 'Midnight'}}],
- },
- {
- database: 'FluxerVoiceStats',
- version: 1,
- store: 'stats',
- records: [{key: null, value: {reportId: 'r-1', packetsLost: 3}}],
- },
- ];
-}
-
-function installedCanaryHarvest(overrides: Partial<DesktopLegacyHarvest> = {}): DesktopLegacyHarvest {
- return {
- version: 1,
- origin: LEGACY_ORIGIN,
- capturedAt: FIXTURE_NOW - 10_000,
- localStorage: goldenCorpusRecord(),
- stores: installedCanaryStores(),
- serviceWorkersUnregistered: 1,
- cachesDeleted: 2,
- truncated: [],
- ...overrides,
- };
-}
-
-interface HarvestBridgeCalls {
- readonly calls: Array<string>;
-}
-
-function installUpgradeBridge(
- store: FakeDesktopStore | null,
- harvest: DesktopLegacyHarvest | null,
- journal: HarvestBridgeCalls,
-): void {
- let staged = harvest;
- let replanted = false;
- const api = {
- desktopAccounts: store?.accounts,
- desktopStorage: store?.storage,
- desktopLegacyHarvest:
- harvest === null
- ? undefined
- : {
- read: () => {
- journal.calls.push('read');
- return Promise.resolve(replanted ? null : staged);
- },
- markReplanted: () => {
- journal.calls.push('markReplanted');
- replanted = true;
- return Promise.resolve();
- },
- discard: () => {
- journal.calls.push('discard');
- staged = null;
- return Promise.resolve();
- },
- },
- };
- Object.defineProperty(window, 'electron', {
- value: api as unknown as ElectronAPI,
- configurable: true,
- writable: true,
- });
-}
-
-function seedRawStorageAsPreloadDoes(harvest: DesktopLegacyHarvest): void {
- for (const [key, value] of Object.entries(harvest.localStorage)) {
- window.localStorage.setItem(key, value);
- }
- window.localStorage.setItem(DESKTOP_LEGACY_RAW_STORAGE_SEED_MARKER_KEY, DESKTOP_LEGACY_RAW_STORAGE_SEED_MARKER_VALUE);
-}
-
-async function loadModules(): Promise<{
- readonly bootstrap: BootstrapModule;
- readonly storage: PersistentStorageModule;
-}> {
- vi.resetModules();
- await import('@app/features/platform/state/PersistentStorageBackend');
- await import('@app/features/platform/state/AppStorageBroadcast');
- await import('@app/features/platform/state/PersistentStorageWriteQueue');
- const storage: PersistentStorageModule = await import('@app/features/platform/state/PersistentStorage');
- const bootstrap: BootstrapModule = await import('@app/features/platform/state/AppStorageBootstrap');
- return {bootstrap, storage};
-}
-
-function deleteDatabase(name: string): Promise<void> {
- return new Promise<void>((resolve, reject) => {
- const factory = getProtectedIndexedDB();
- if (factory == null) {
- resolve();
- return;
- }
- const request = factory.deleteDatabase(name);
- request.onsuccess = () => resolve();
- request.onerror = () => reject(request.error ?? new Error(`deleteDatabase ${name} failed`));
- request.onblocked = () => resolve();
- });
-}
-
-function openDatabase(name: string, version: number): Promise<IDBDatabase> {
- return new Promise<IDBDatabase>((resolve, reject) => {
- const request = window.indexedDB.open(name, version);
- request.onsuccess = () => resolve(request.result);
- request.onerror = () => reject(request.error ?? new Error(`open ${name} failed`));
- });
-}
-
-function readAll(database: IDBDatabase, store: string): Promise<Array<unknown>> {
- return new Promise<Array<unknown>>((resolve, reject) => {
- const request = database.transaction(store).objectStore(store).getAll();
- request.onsuccess = () => resolve(request.result);
- request.onerror = () => reject(request.error ?? new Error(`getAll ${store} failed`));
- });
-}
-
-const WEB_FALLBACK_BOOKKEEPING_KEYS: ReadonlySet<string> = new Set(['fluxer:migration:legacy-app-storage']);
-
-function withoutWebFallbackBookkeeping(
- entries: ReadonlyArray<readonly [string, string, string]>,
-): Array<readonly [string, string, string]> {
- return entries.filter(([, key]) => !WEB_FALLBACK_BOOKKEEPING_KEYS.has(key));
-}
-
-function desktopEntryMap(store: FakeDesktopStore): Map<string, string> {
- return new Map(store.snapshot().entries.map(([scope, key, value]) => [identity(scope, key), value]));
-}
-
-function markerOf(store: FakeDesktopStore, key: string): string | null {
- return new Map(store.snapshot().markers).get(key) ?? null;
-}
-
-installRuntimeBootstrap();
-
-beforeEach(async () => {
- Object.defineProperty(navigator, 'locks', {
- value: {request: <T>(_name: string, callback: () => Promise<T>): Promise<T> => callback()},
- configurable: true,
- writable: true,
- });
- window.localStorage.clear();
- Reflect.deleteProperty(window, 'electron');
- for (const name of [
- APP_STORAGE_INDEXED_DB_NAME,
- 'FluxerAccounts',
- 'FluxerCustomSounds',
- 'fluxer-theme-library',
- 'FluxerVoiceStats',
- ]) {
- await deleteDatabase(name);
- }
-});
-
-afterEach(() => {
- Object.defineProperty(navigator, 'locks', {value: null, configurable: true, writable: true});
- Reflect.deleteProperty(window, 'electron');
-});
-
-describe('upgrading an installed Fluxer Canary onto the local app scheme', () => {
- test('the whole golden corpus lands in the desktop store under the scope the migration assigns it', async () => {
- const store = createFakeDesktopStore();
- const harvest = installedCanaryHarvest();
- const journal: HarvestBridgeCalls = {calls: []};
- installUpgradeBridge(store, harvest, journal);
- seedRawStorageAsPreloadDoes(harvest);
- const {bootstrap} = await loadModules();
-
- const result = await startAndFinalize(bootstrap);
-
- expect(result.desktopBackendInstalled).toBe(true);
- expect(result.desktopImport?.status).toBe('imported');
- expect(result.scope).toBe(ACTIVE_SCOPE);
-
- const entries = desktopEntryMap(store);
- const rewritten: Array<string> = [];
- for (const [destination, value] of expectedDesktopEntries()) {
- expect(entries.has(destination), `lost ${destination}`).toBe(true);
- if (entries.get(destination) !== value) {
- rewritten.push(destination);
- }
- }
- expect(rewritten).toEqual([]);
- });
-
- test('no deployed key is dropped and none is invented', async () => {
- const store = createFakeDesktopStore();
- const harvest = installedCanaryHarvest();
- installUpgradeBridge(store, harvest, {calls: []});
- seedRawStorageAsPreloadDoes(harvest);
- const {bootstrap} = await loadModules();
-
- await startAndFinalize(bootstrap);
-
- const migrated = new Set(desktopEntryMap(store).keys());
- const expected = expectedDesktopEntries();
- for (const destination of expected.keys()) {
- expect(migrated.has(destination), `missing ${destination}`).toBe(true);
- }
- for (const key of NOT_MIGRATED_STORAGE_KEYS) {
- for (const scope of [GLOBAL_SCOPE, ...ALL_ACCOUNT_SCOPES]) {
- expect(migrated.has(identity(scope, key)), `invented ${identity(scope, key)}`).toBe(false);
- }
- }
- });
-
- test('both account rows arrive instance-qualified with their tokens intact', async () => {
- const store = createFakeDesktopStore();
- const harvest = installedCanaryHarvest();
- installUpgradeBridge(store, harvest, {calls: []});
- seedRawStorageAsPreloadDoes(harvest);
- const {bootstrap} = await loadModules();
-
- await startAndFinalize(bootstrap);
-
- expect(
- store
- .snapshot()
- .accounts.map(([key]) => key)
- .sort(),
- ).toEqual([ACTIVE_SCOPE, OTHER_SCOPE].sort());
- expect(store.readAccount(ACTIVE_SCOPE)).toMatchObject({userId: ACTIVE_USER_ID, storageKey: ACTIVE_SCOPE});
- expect(store.readAccount(OTHER_SCOPE)).toMatchObject({userId: OTHER_USER_ID, storageKey: OTHER_SCOPE});
- });
-
- test('the live session survives: the pointer, the token and the user id all name the same account', async () => {
- const store = createFakeDesktopStore();
- const harvest = installedCanaryHarvest();
- installUpgradeBridge(store, harvest, {calls: []});
- seedRawStorageAsPreloadDoes(harvest);
- const {bootstrap} = await loadModules();
-
- await startAndFinalize(bootstrap);
-
- const rawToken = harvest.localStorage.token;
- expect(store.readEntry(GLOBAL_SCOPE, AppStorageKey.AUTH_ACCOUNT_KEY)?.value).toBe(ACTIVE_SCOPE);
- expect(store.readAccount(ACTIVE_SCOPE)).toMatchObject({userId: ACTIVE_USER_ID, token: rawToken});
- expect(window.localStorage.getItem('token')).toBe(rawToken);
- expect(window.localStorage.getItem('userId')).toBe(ACTIVE_USER_ID);
- });
-
- test('the raw session keys stay on the new origin, where the preboot still reads them', async () => {
- const store = createFakeDesktopStore();
- const harvest = installedCanaryHarvest();
- installUpgradeBridge(store, harvest, {calls: []});
- seedRawStorageAsPreloadDoes(harvest);
- const {bootstrap} = await loadModules();
-
- await startAndFinalize(bootstrap);
-
- expect(window.localStorage.getItem('userId')).toBe(ACTIVE_USER_ID);
- expect(window.localStorage.getItem('token')).toBe(harvest.localStorage.token);
- });
-
- test('every harvested database is replanted onto the new origin, blobs included', async () => {
- const store = createFakeDesktopStore();
- const harvest = installedCanaryHarvest();
- installUpgradeBridge(store, harvest, {calls: []});
- seedRawStorageAsPreloadDoes(harvest);
- const {bootstrap} = await loadModules();
-
- await startAndFinalize(bootstrap);
-
- const accounts = await openDatabase('FluxerAccounts', 2);
- expect((await readAll(accounts, 'accounts')).length).toBe(2);
- accounts.close();
-
- const sounds = await openDatabase('FluxerCustomSounds', 2);
- const soundRecords = (await readAll(sounds, 'customSounds')) as Array<{blob: unknown; edited: boolean}>;
- sounds.close();
- expect(soundRecords).toHaveLength(1);
- expect(soundRecords[0]?.edited).toBe(true);
- expect(new Uint8Array(soundRecords[0]?.blob as ArrayBufferLike)).toEqual(SOUND_BYTES);
-
- const themes = await openDatabase('fluxer-theme-library', 1);
- expect(await readAll(themes, 'themes')).toEqual([{id: 'midnight', name: 'Midnight'}]);
- themes.close();
-
- const stats = await openDatabase('FluxerVoiceStats', 1);
- expect(await readAll(stats, 'stats')).toEqual([{reportId: 'r-1', packetsLost: 3}]);
- stats.close();
- });
-
- test('the harvest is marked replanted, authority is committed, and only then is it discarded', async () => {
- const store = createFakeDesktopStore();
- const harvest = installedCanaryHarvest();
- const journal: HarvestBridgeCalls = {calls: []};
- installUpgradeBridge(store, harvest, journal);
- seedRawStorageAsPreloadDoes(harvest);
- const {bootstrap} = await loadModules();
-
- await startAndFinalize(bootstrap);
-
- expect(journal.calls.filter((call) => call !== 'read')).toEqual(['markReplanted', 'discard']);
- expect(markerOf(store, DESKTOP_LEGACY_IMPORT_MARKER_KEY)).toContain(DesktopLegacyImportPhase.DONE);
- expect(markerOf(store, DESKTOP_LEGACY_AUTHORITY_MARKER_KEY)).toBe(DESKTOP_LEGACY_AUTHORITY_MARKER_VALUE);
- });
-
- test('writes made after boot land in the desktop store, not the web backend', async () => {
- const store = createFakeDesktopStore();
- const harvest = installedCanaryHarvest();
- installUpgradeBridge(store, harvest, {calls: []});
- seedRawStorageAsPreloadDoes(harvest);
- const {bootstrap, storage} = await loadModules();
-
- await startAndFinalize(bootstrap);
- storage.default.setItem('UserSettings:syncedPreferencesLocal', 'written-after-upgrade');
- await storage.flushAppStorageWrites();
-
- expect(store.readEntry(ACTIVE_SCOPE, 'UserSettings:syncedPreferencesLocal')?.value).toBe('written-after-upgrade');
- });
-});
-
-describe('the second launch after the upgrade', () => {
- test('re-imports nothing and leaves the store byte-identical', async () => {
- const store = createFakeDesktopStore();
- const harvest = installedCanaryHarvest();
- const journal: HarvestBridgeCalls = {calls: []};
- installUpgradeBridge(store, harvest, journal);
- seedRawStorageAsPreloadDoes(harvest);
-
- const first = await loadModules();
- await startAndFinalize(first.bootstrap);
- const afterUpgrade = store.snapshot();
-
- const second = await loadModules();
- const result = await startAndFinalize(second.bootstrap);
-
- expect(result.desktopBackendInstalled).toBe(true);
- expect(result.desktopImport?.status).toBe('already-done');
- expect(result.scope).toBe(ACTIVE_SCOPE);
- expect(store.snapshot().accounts).toEqual(afterUpgrade.accounts);
- expect(store.snapshot().entries).toEqual(afterUpgrade.entries);
- expect(markerOf(store, DESKTOP_LEGACY_IMPORT_MARKER_KEY)).toBe(
- new Map(afterUpgrade.markers).get(DESKTOP_LEGACY_IMPORT_MARKER_KEY),
- );
- expect(markerOf(store, DESKTOP_LEGACY_AUTHORITY_MARKER_KEY)).toBe(DESKTOP_LEGACY_AUTHORITY_MARKER_VALUE);
- expect(journal.calls.filter((call) => call === 'markReplanted')).toHaveLength(1);
- });
-});
-
-describe('later launches after the harvest was replanted', () => {
- function deleteRecord(database: IDBDatabase, store: string, key: IDBValidKey): Promise<void> {
- return new Promise<void>((resolve, reject) => {
- const transaction = database.transaction(store, 'readwrite');
- transaction.objectStore(store).delete(key);
- transaction.oncomplete = () => resolve();
- transaction.onerror = () => reject(transaction.error ?? new Error(`delete from ${store} failed`));
- });
- }
-
- async function startSignedOut(bootstrap: BootstrapModule): Promise<void> {
- const handle = await bootstrap.startAppStorage({scoped: true});
- await handle.finalizeAfterSessionResolution(null);
- }
-
- test('a signed-out install replants once and never restores a record removed since', async () => {
- const store = createFakeDesktopStore();
- const harvest = installedCanaryHarvest();
- const journal: HarvestBridgeCalls = {calls: []};
- installUpgradeBridge(store, harvest, journal);
- seedRawStorageAsPreloadDoes(harvest);
- window.localStorage.removeItem('token');
- window.localStorage.removeItem('userId');
- const first = await loadModules();
- await startSignedOut(first.bootstrap);
- const stats = await openDatabase('FluxerVoiceStats', 1);
- expect(await readAll(stats, 'stats')).toHaveLength(1);
- await deleteRecord(stats, 'stats', 'r-1');
- stats.close();
-
- const second = await loadModules();
- await startSignedOut(second.bootstrap);
-
- const reopened = await openDatabase('FluxerVoiceStats', 1);
- expect(await readAll(reopened, 'stats')).toEqual([]);
- reopened.close();
- expect(journal.calls.filter((call) => call === 'markReplanted')).toHaveLength(1);
- expect(journal.calls).not.toContain('discard');
- });
-});
-
-describe('upgrading an install enrolled in the move to the migrated official domain', () => {
- const MIGRATED_ORIGIN = 'https://canary.fluxer.com';
- const OFFICIAL_INSTANCE_KEY = 'https://web.canary.fluxer.app/api';
- const OFFICIAL_INSTANCE_SNAPSHOT = {
- ...FIXTURE_CURRENT_INSTANCE_SNAPSHOT,
- apiEndpoint: OFFICIAL_INSTANCE_KEY,
- webAppEndpoint: 'https://web.canary.fluxer.app',
- };
- const OFFICIAL_ACTIVE_SCOPE = `${OFFICIAL_INSTANCE_KEY}::${ACTIVE_USER_ID}`;
- const OFFICIAL_OTHER_SCOPE = `${OFFICIAL_INSTANCE_KEY}::${OTHER_USER_ID}`;
-
- function migratedDomainAccount(userId: string): Record<string, unknown> {
- return {
- ...accountRecord(userId),
- instance: {
- apiEndpoint: `${MIGRATED_ORIGIN}/api`,
- webAppEndpoint: MIGRATED_ORIGIN,
- gatewayEndpoint: 'wss://gateway.fluxer.app',
- },
- };
- }
-
- function migratedDomainHarvest(): DesktopLegacyHarvest {
- return installedCanaryHarvest({
- origin: MIGRATED_ORIGIN,
- stores: [
- {
- database: 'FluxerAccounts',
- version: 2,
- store: 'accounts',
- records: [
- {key: null, value: migratedDomainAccount(ACTIVE_USER_ID)},
- {key: null, value: migratedDomainAccount(OTHER_USER_ID)},
- ],
- },
- ],
- });
- }
-
- test('the accounts stored on the migrated domain are imported once, keyed on the official instance', async () => {
- const store = createFakeDesktopStore();
- const harvest = migratedDomainHarvest();
- installUpgradeBridge(store, harvest, {calls: []});
- seedRawStorageAsPreloadDoes(harvest);
- const {bootstrap} = await loadModules();
- const handle = await bootstrap.startAppStorage({scoped: true});
-
- const result = await handle.finalizeAfterSessionResolution({
- accountKey: OFFICIAL_ACTIVE_SCOPE,
- userId: ACTIVE_USER_ID,
- token: ACTIVE_TOKEN,
- instance: OFFICIAL_INSTANCE_SNAPSHOT,
- });
-
- expect(result.desktopImport?.status).toBe('imported');
- expect(result.scope).toBe(OFFICIAL_ACTIVE_SCOPE);
- expect(
- store
- .snapshot()
- .accounts.map(([key]) => key)
- .sort(),
- ).toEqual([OFFICIAL_ACTIVE_SCOPE, OFFICIAL_OTHER_SCOPE].sort());
- expect(store.readAccount(OFFICIAL_ACTIVE_SCOPE)).toMatchObject({
- userId: ACTIVE_USER_ID,
- token: ACTIVE_TOKEN,
- storageKey: OFFICIAL_ACTIVE_SCOPE,
- instance: {apiEndpoint: OFFICIAL_INSTANCE_KEY},
- });
- expect(store.readEntry(GLOBAL_SCOPE, AppStorageKey.AUTH_ACCOUNT_KEY)?.value).toBe(OFFICIAL_ACTIVE_SCOPE);
- expect(markerOf(store, DESKTOP_LEGACY_AUTHORITY_MARKER_KEY)).toBe(DESKTOP_LEGACY_AUTHORITY_MARKER_VALUE);
- });
-});
-
-describe('an upgrade interrupted partway through', () => {
- test('a failed desktop write leaves the web backend serving every value', async () => {
- const store = createFakeDesktopStore();
- const harvest = installedCanaryHarvest();
- installUpgradeBridge(store, harvest, {calls: []});
- seedRawStorageAsPreloadDoes(harvest);
- const {bootstrap, storage} = await loadModules();
- store.failOnce('storage.import');
-
- const result = await startAndFinalize(bootstrap);
-
- expect(result.desktopBackendInstalled).toBe(false);
- expect(result.scope).toBe(ACTIVE_SCOPE);
- expect(storage.default.getItem(AppStorageKey.AUTH_SESSION_USER_ID)).toBe(ACTIVE_USER_ID);
- expect(markerOf(store, DESKTOP_LEGACY_AUTHORITY_MARKER_KEY)).not.toBe(DESKTOP_LEGACY_AUTHORITY_MARKER_VALUE);
- });
-
- test('the next launch converges on exactly the state an uninterrupted upgrade produces', async () => {
- const reference = createFakeDesktopStore();
- const referenceHarvest = installedCanaryHarvest();
- installUpgradeBridge(reference, referenceHarvest, {calls: []});
- seedRawStorageAsPreloadDoes(referenceHarvest);
- const clean = await loadModules();
- await startAndFinalize(clean.bootstrap);
- const expected = reference.snapshot();
-
- window.localStorage.clear();
- for (const name of [
- APP_STORAGE_INDEXED_DB_NAME,
- 'FluxerAccounts',
- 'FluxerCustomSounds',
- 'fluxer-theme-library',
- 'FluxerVoiceStats',
- ]) {
- await deleteDatabase(name);
- }
-
- const store = createFakeDesktopStore();
- const harvest = installedCanaryHarvest();
- installUpgradeBridge(store, harvest, {calls: []});
- seedRawStorageAsPreloadDoes(harvest);
- const interrupted = await loadModules();
- store.failOnce('storage.import');
- await startAndFinalize(interrupted.bootstrap);
-
- const resumed = await loadModules();
- const result = await startAndFinalize(resumed.bootstrap);
-
- expect(result.desktopBackendInstalled).toBe(true);
- expect(store.snapshot().accounts).toEqual(expected.accounts);
- expect(withoutWebFallbackBookkeeping(store.snapshot().entries)).toEqual(
- withoutWebFallbackBookkeeping(expected.entries),
- );
- });
-
- test('work done during the fallback session is carried across, not overwritten by the stale snapshot', async () => {
- const store = createFakeDesktopStore();
- const harvest = installedCanaryHarvest();
- installUpgradeBridge(store, harvest, {calls: []});
- seedRawStorageAsPreloadDoes(harvest);
-
- const interrupted = await loadModules();
- store.failOnce('storage.import');
- const failed = await startAndFinalize(interrupted.bootstrap);
- expect(failed.desktopBackendInstalled).toBe(false);
- expect(markerOf(store, DESKTOP_LEGACY_IMPORT_MARKER_KEY)).toContain(DesktopLegacyImportPhase.ENTRIES);
-
- interrupted.storage.default.setItem('UserSettings:syncedPreferencesLocal', 'written-during-fallback');
- await interrupted.storage.flushAppStorageWrites();
-
- const resumed = await loadModules();
- const result = await startAndFinalize(resumed.bootstrap);
-
- expect(result.desktopBackendInstalled).toBe(true);
- expect(store.readEntry(ACTIVE_SCOPE, 'UserSettings:syncedPreferencesLocal')?.value).toBe('written-during-fallback');
- });
-});
-
-describe('an upgrade with no desktop store at all', () => {
- test('the web backend still carries the whole corpus onto the new origin', async () => {
- const harvest = installedCanaryHarvest();
- installUpgradeBridge(null, harvest, {calls: []});
- seedRawStorageAsPreloadDoes(harvest);
- const {bootstrap, storage} = await loadModules();
-
- const result = await startAndFinalize(bootstrap);
-
- expect(result.desktopBackendInstalled).toBe(false);
- expect(result.scope).toBe(ACTIVE_SCOPE);
- expect(storage.getAppStorageScope()).toBe(ACTIVE_SCOPE);
-
- const accounts = await openDatabase('FluxerAccounts', 2);
- expect((await readAll(accounts, 'accounts')).length).toBe(2);
- accounts.close();
-
- const appStorage = await openDatabase(APP_STORAGE_INDEXED_DB_NAME, 1);
- const rows = (await readAll(appStorage, APP_STORAGE_OBJECT_STORE)) as Array<{scope: string; key: string}>;
- appStorage.close();
- const present = new Set(rows.map((row) => identity(row.scope, row.key)));
- for (const destination of expectedDesktopEntries().keys()) {
- expect(present.has(destination), `missing ${destination}`).toBe(true);
- }
- });
-});
diff --git a/fluxer_app/src/features/platform/state/LegacySessionReconciliation.test.ts b/fluxer_app/src/features/platform/state/LegacySessionReconciliation.test.ts
deleted file mode 100644
index a583bb65a..000000000
--- a/fluxer_app/src/features/platform/state/LegacySessionReconciliation.test.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {FIXTURE_CURRENT_INSTANCE_SNAPSHOT} from '@app/features/auth/state/__fixtures__/AccountRecordFixtures';
-import type {KeyedStoredAccount} from '@app/features/auth/state/AccountStorageContract';
-import {accountStorageKey} from '@app/features/auth/state/AccountStorageKey';
-import {
- type LegacySessionAccountStore,
- LegacySessionReconciliationOutcome,
- reconcileLegacySession,
-} from '@app/features/platform/state/LegacySessionReconciliation';
-import {describe, expect, test} from 'vitest';
-
-const NOW = 1_790_000_000_000;
-const USER_ID = '4242';
-const TOKEN = 'token.4242';
-const STORAGE_KEY = accountStorageKey(USER_ID, FIXTURE_CURRENT_INSTANCE_SNAPSHOT);
-
-function liveSession(): Storage {
- const values = new Map([
- ['userId', USER_ID],
- ['token', TOKEN],
- ]);
- return {
- get length() {
- return values.size;
- },
- clear: () => values.clear(),
- getItem: (key: string) => values.get(key) ?? null,
- key: (index: number) => [...values.keys()][index] ?? null,
- removeItem: (key: string) => void values.delete(key),
- setItem: (key: string, value: string) => void values.set(key, value),
- };
-}
-
-function recordingStore(activeAccountKey: string | null) {
- const calls: Array<string> = [];
- const store: LegacySessionAccountStore = {
- async findAccountByCredentials() {
- calls.push('find');
- return {userId: USER_ID, token: TOKEN, storageKey: STORAGE_KEY} as KeyedStoredAccount;
- },
- async readActiveAccountKey() {
- calls.push('read-active');
- return activeAccountKey;
- },
- async setActiveAccountKey(storageKey, reconciledAt) {
- calls.push(`set-active ${storageKey} ${reconciledAt}`);
- },
- };
- return {store, calls};
-}
-
-function reconcile(store: LegacySessionAccountStore) {
- return reconcileLegacySession({
- store,
- legacyStorage: liveSession(),
- currentAccount: {userId: USER_ID, token: TOKEN, instance: FIXTURE_CURRENT_INSTANCE_SNAPSHOT},
- now: NOW,
- });
-}
-
-describe('reconcileLegacySession', () => {
- test('a warm boot whose live session is already the active account writes nothing', async () => {
- const {store, calls} = recordingStore(STORAGE_KEY);
-
- const result = await reconcile(store);
-
- expect(result).toEqual({
- outcome: LegacySessionReconciliationOutcome.UNCHANGED,
- storageKey: STORAGE_KEY,
- reason: null,
- });
- expect(calls).toEqual(['read-active']);
- });
-
- test('a live session that is not the active account becomes active', async () => {
- const {store, calls} = recordingStore('https://other.example/api::1');
-
- const result = await reconcile(store);
-
- expect(result).toEqual({
- outcome: LegacySessionReconciliationOutcome.UNCHANGED,
- storageKey: STORAGE_KEY,
- reason: null,
- });
- expect(calls).toEqual(['read-active', 'find', `set-active ${STORAGE_KEY} ${NOW}`]);
- });
-});
diff --git a/fluxer_app/src/features/platform/state/LegacySharedContentReview.test.ts b/fluxer_app/src/features/platform/state/LegacySharedContentReview.test.ts
deleted file mode 100644
index 4bedef47b..000000000
--- a/fluxer_app/src/features/platform/state/LegacySharedContentReview.test.ts
+++ /dev/null
@@ -1,130 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {beforeEach, describe, expect, test, vi} from 'vitest';
-
-const REVIEW_KEY = 'fluxer:migration:shared-content-review';
-
-const mocks = vi.hoisted(() => ({
- channels: new Set<string>(),
- unavailableGuilds: new Set<string>(),
- drafts: new Map<string, string>(),
- storage: new Map<string, string>(),
- scope: 'primary.test::200',
- hydration: Promise.resolve(),
- abandonUnreachableLastLocation: vi.fn<() => void>(),
-}));
-
-vi.mock('@app/features/channel/state/Channels', () => ({
- default: {getChannel: (id: string) => (mocks.channels.has(id) ? {id} : undefined)},
-}));
-
-vi.mock('@app/features/guild/state/GuildAvailability', () => ({
- default: {unavailableGuilds: mocks.unavailableGuilds},
-}));
-
-vi.mock('@app/features/messaging/state/MessagingDrafts', () => ({
- default: {
- getAllDrafts: () => [...mocks.drafts.entries()],
- deleteDraft: (channelId: string) => {
- mocks.drafts.delete(channelId);
- },
- },
-}));
-
-vi.mock('@app/features/navigation/utils/ChannelRouteReachability', () => ({
- abandonUnreachableLastLocation: mocks.abandonUnreachableLastLocation,
-}));
-
-vi.mock('@app/features/platform/state/PersistentStorage', () => ({
- default: {
- getItem: (key: string) => mocks.storage.get(key) ?? null,
- setItem: (key: string, value: string) => {
- mocks.storage.set(key, value);
- },
- },
- getAppStorageScope: () => mocks.scope,
-}));
-
-vi.mock('@app/features/platform/utils/MobXPersistence', () => ({
- awaitHydration: () => mocks.hydration,
-}));
-
-import {reviewLegacySharedContent} from '@app/features/platform/state/LegacySharedContentReview';
-
-const SHARED_CHANNEL = '110000000000000001';
-const FOREIGN_DM = '210000000000000001';
-
-beforeEach(() => {
- mocks.channels.clear();
- mocks.unavailableGuilds.clear();
- mocks.drafts.clear();
- mocks.storage.clear();
- mocks.scope = 'primary.test::200';
- mocks.hydration = Promise.resolve();
- mocks.abandonUnreachableLastLocation.mockReset();
- mocks.channels.add(SHARED_CHANNEL);
- mocks.drafts.set(SHARED_CHANNEL, 'for a channel both accounts share');
- mocks.drafts.set(FOREIGN_DM, 'for a conversation only the other account has');
-});
-
-describe('reviewing shared content carried from the legacy client', () => {
- test('a pending account keeps the drafts it can open and drops the ones it cannot', async () => {
- mocks.storage.set(REVIEW_KEY, 'pending');
-
- await reviewLegacySharedContent();
-
- expect([...mocks.drafts.keys()]).toEqual([SHARED_CHANNEL]);
- expect(mocks.abandonUnreachableLastLocation).toHaveBeenCalledTimes(1);
- expect(mocks.storage.get(REVIEW_KEY)).toBe('done');
- });
-
- test('an account that received no legacy content is never reviewed', async () => {
- await reviewLegacySharedContent();
-
- expect([...mocks.drafts.keys()]).toEqual([SHARED_CHANNEL, FOREIGN_DM]);
- expect(mocks.abandonUnreachableLastLocation).not.toHaveBeenCalled();
- expect(mocks.storage.has(REVIEW_KEY)).toBe(false);
- });
-
- test('a reviewed account is never reviewed again', async () => {
- mocks.storage.set(REVIEW_KEY, 'done');
-
- await reviewLegacySharedContent();
-
- expect([...mocks.drafts.keys()]).toEqual([SHARED_CHANNEL, FOREIGN_DM]);
- expect(mocks.abandonUnreachableLastLocation).not.toHaveBeenCalled();
- });
-
- test('the review waits for a later READY while any guild is unavailable', async () => {
- mocks.storage.set(REVIEW_KEY, 'pending');
- mocks.unavailableGuilds.add('120000000000000001');
-
- await reviewLegacySharedContent();
-
- expect([...mocks.drafts.keys()]).toEqual([SHARED_CHANNEL, FOREIGN_DM]);
- expect(mocks.storage.get(REVIEW_KEY)).toBe('pending');
-
- mocks.unavailableGuilds.clear();
- await reviewLegacySharedContent();
-
- expect([...mocks.drafts.keys()]).toEqual([SHARED_CHANNEL]);
- expect(mocks.storage.get(REVIEW_KEY)).toBe('done');
- });
-
- test('a switch to another account while the stores hydrate leaves that account untouched', async () => {
- mocks.storage.set(REVIEW_KEY, 'pending');
- let release: () => void = () => {};
- mocks.hydration = new Promise<void>((resolve) => {
- release = resolve;
- });
-
- const review = reviewLegacySharedContent();
- mocks.scope = 'primary.test::100';
- release();
- await review;
-
- expect([...mocks.drafts.keys()]).toEqual([SHARED_CHANNEL, FOREIGN_DM]);
- expect(mocks.abandonUnreachableLastLocation).not.toHaveBeenCalled();
- expect(mocks.storage.get(REVIEW_KEY)).toBe('pending');
- });
-});
diff --git a/fluxer_app/src/features/platform/state/LegacyStorageContinuity.test.ts b/fluxer_app/src/features/platform/state/LegacyStorageContinuity.test.ts
deleted file mode 100644
index cc9513037..000000000
--- a/fluxer_app/src/features/platform/state/LegacyStorageContinuity.test.ts
+++ /dev/null
@@ -1,410 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- FIXTURE_CURRENT_INSTANCE_KEY,
- FIXTURE_CURRENT_INSTANCE_SNAPSHOT,
- FIXTURE_NOW,
-} from '@app/features/auth/state/__fixtures__/AccountRecordFixtures';
-import {
- createFakeDesktopStore,
- type FakeDesktopStore,
-} from '@app/features/platform/state/__fixtures__/DesktopStoreFixture';
-import {
- CONTENT_STORAGE_KEYS,
- GOLDEN_DEPLOYED_STORAGE_ENTRIES,
- GOLDEN_LOCAL_STORAGE_CORPUS,
- OWNED_CONTENT_STORAGE_KEYS,
- SHARED_CONTENT_STORAGE_KEYS,
-} from '@app/features/platform/state/__fixtures__/LegacyStorageFixtures';
-import {
- readPersistedStoreNames,
- STORES_WITHOUT_DEPLOYED_DATA,
-} from '@app/features/platform/state/__fixtures__/PersistedStoreNames';
-import {installRuntimeBootstrap} from '@app/features/platform/state/__fixtures__/RuntimeBootstrapFixture';
-import type {AppStorageSessionAccount} from '@app/features/platform/state/AppStorageBootstrap';
-import {
- AppStorageKey,
- LEGACY_APP_STORAGE_MIGRATION_MARKER_KEY,
- LEGACY_SHARED_CONTENT_REVIEW_KEY,
- LegacySharedContentReviewState,
-} from '@app/features/platform/state/AppStorageKeys';
-import {APP_STORAGE_INDEXED_DB_NAME} from '@app/features/platform/state/PersistentStorageBackend';
-import {getProtectedIndexedDB} from '@app/features/platform/state/ProtectedWebStorage';
-import type {ElectronAPI} from '@app/types/electron.d';
-import type {DesktopLegacyHarvest} from '@fluxer/desktop_ipc/src/LegacyHarvestContract';
-import {
- DESKTOP_LEGACY_RAW_STORAGE_SEED_MARKER_KEY,
- DESKTOP_LEGACY_RAW_STORAGE_SEED_MARKER_VALUE,
-} from '@fluxer/desktop_ipc/src/LegacyHarvestContract';
-import {makeAutoObservable, runInAction} from 'mobx';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
-
-type PersistentStorageModule = typeof import('@app/features/platform/state/PersistentStorage');
-type PersistenceModule = typeof import('@app/features/platform/utils/MobXPersistence');
-
-interface LoadedClient {
- readonly storage: PersistentStorageModule;
- readonly persistence: PersistenceModule;
- readonly drafts: PersistedDrafts;
- readonly desktopBackendInstalled: boolean;
-}
-
-const ACTIVE_USER_ID = '100000000000000002';
-const OTHER_USER_ID = '100000000000000003';
-const ACTIVE_SCOPE = `${FIXTURE_CURRENT_INSTANCE_KEY}::${ACTIVE_USER_ID}`;
-const OTHER_SCOPE = `${FIXTURE_CURRENT_INSTANCE_KEY}::${OTHER_USER_ID}`;
-const ADDED_SINCE_SCOPE = `${FIXTURE_CURRENT_INSTANCE_KEY}::100000000000000009`;
-const DEPLOYED_DRAFTS: Readonly<Record<string, string>> = {'110000000000000001': 'unsent message text'};
-const GLOBAL_SCOPE = 'global';
-const ACTIVE_TOKEN = GOLDEN_LOCAL_STORAGE_CORPUS.find((entry) => entry.key === 'token')!.value;
-const LOADS_AFTER_THE_UPGRADE = 3;
-
-const OTHER_ACCOUNT_OWNED_VALUES: Readonly<Record<string, string>> = {
- [AppStorageKey.UI_SIDEBAR_WIDTH]: '331',
- 'fluxer:media_player:volume': '0.25',
- 'fluxer_scheduled_maintenance_dismissed:4242': '1',
-};
-
-const ACTIVE_ACCOUNT_STALE_VALUES: Readonly<Record<string, string>> = {
- [AppStorageKey.UI_SIDEBAR_WIDTH]: '205',
-};
-
-const GOLDEN_VALUES: ReadonlyMap<string, string> = new Map(
- GOLDEN_LOCAL_STORAGE_CORPUS.map((entry) => [entry.key, entry.value]),
-);
-
-const DEPLOYED_STORE_NAMES: ReadonlyArray<string> = readPersistedStoreNames().filter(
- (name) => !STORES_WITHOUT_DEPLOYED_DATA.has(name),
-);
-
-class PersistedDrafts {
- drafts: Record<string, string> = {};
- draftSegments: Record<string, unknown> = {};
-
- constructor() {
- makeAutoObservable(this);
- }
-}
-
-function accountRecord(userId: string, ownedValues: Readonly<Record<string, string>>): Record<string, unknown> {
- const snapshot = {userId, token: `token-${userId}`, ...ownedValues};
- return {
- userId,
- token: userId === ACTIVE_USER_ID ? ACTIVE_TOKEN : `token-${userId}`,
- userData: {id: userId, username: `user-${userId}`, discriminator: '0001', avatar: null},
- localStorageData: snapshot,
- managedStorageData: snapshot,
- lastActive: FIXTURE_NOW - 1_000,
- instance: FIXTURE_CURRENT_INSTANCE_SNAPSHOT,
- };
-}
-
-function deployedAccountRecords(): Array<Record<string, unknown>> {
- return [
- accountRecord(ACTIVE_USER_ID, ACTIVE_ACCOUNT_STALE_VALUES),
- accountRecord(OTHER_USER_ID, OTHER_ACCOUNT_OWNED_VALUES),
- ];
-}
-
-function goldenCorpusRecord(): Record<string, string> {
- return Object.fromEntries(GOLDEN_VALUES);
-}
-
-function activeSessionAccount(): AppStorageSessionAccount {
- return {
- accountKey: ACTIVE_SCOPE,
- userId: ACTIVE_USER_ID,
- token: ACTIVE_TOKEN,
- instance: FIXTURE_CURRENT_INSTANCE_SNAPSHOT,
- };
-}
-
-function deleteDatabase(name: string): Promise<void> {
- return new Promise<void>((resolve, reject) => {
- const factory = getProtectedIndexedDB();
- if (factory == null) {
- resolve();
- return;
- }
- const request = factory.deleteDatabase(name);
- request.onsuccess = () => resolve();
- request.onerror = () => reject(request.error ?? new Error(`deleteDatabase ${name} failed`));
- request.onblocked = () => resolve();
- });
-}
-
-function seedDeployedWebAccounts(): Promise<void> {
- return new Promise<void>((resolve, reject) => {
- const request = window.indexedDB.open('FluxerAccounts', 2);
- request.onupgradeneeded = () => {
- request.result.createObjectStore('accounts', {keyPath: 'userId'}).createIndex('lastActive', 'lastActive');
- };
- request.onerror = () => reject(request.error ?? new Error('open FluxerAccounts failed'));
- request.onsuccess = () => {
- const database = request.result;
- const transaction = database.transaction('accounts', 'readwrite');
- for (const record of deployedAccountRecords()) {
- transaction.objectStore('accounts').put(record);
- }
- transaction.oncomplete = () => {
- database.close();
- resolve();
- };
- transaction.onerror = () => reject(transaction.error ?? new Error('seeding FluxerAccounts failed'));
- };
- });
-}
-
-function seedDeployedLocalStorage(): void {
- for (const [key, value] of GOLDEN_VALUES) {
- window.localStorage.setItem(key, value);
- }
- window.localStorage.setItem('userId', ACTIVE_USER_ID);
-}
-
-function installDeployedDesktop(store: FakeDesktopStore): void {
- const harvest: DesktopLegacyHarvest = {
- version: 1,
- origin: 'https://web.canary.fluxer.app',
- capturedAt: FIXTURE_NOW - 10_000,
- localStorage: {...goldenCorpusRecord(), userId: ACTIVE_USER_ID},
- stores: [
- {
- database: 'FluxerAccounts',
- version: 2,
- store: 'accounts',
- records: deployedAccountRecords().map((value) => ({key: null, value})),
- },
- ],
- serviceWorkersUnregistered: 0,
- cachesDeleted: 0,
- truncated: [],
- };
- let staged: DesktopLegacyHarvest | null = harvest;
- let replanted = false;
- const api = {
- desktopAccounts: store.accounts,
- desktopStorage: store.storage,
- desktopLegacyHarvest: {
- read: () => Promise.resolve(replanted ? null : staged),
- markReplanted: () => {
- replanted = true;
- return Promise.resolve();
- },
- discard: () => {
- staged = null;
- return Promise.resolve();
- },
- },
- };
- Object.defineProperty(window, 'electron', {value: api as unknown as ElectronAPI, configurable: true, writable: true});
- for (const [key, value] of Object.entries(harvest.localStorage)) {
- window.localStorage.setItem(key, value);
- }
- window.localStorage.setItem(DESKTOP_LEGACY_RAW_STORAGE_SEED_MARKER_KEY, DESKTOP_LEGACY_RAW_STORAGE_SEED_MARKER_VALUE);
-}
-
-async function loadClient(): Promise<LoadedClient> {
- vi.resetModules();
- const storage: PersistentStorageModule = await import('@app/features/platform/state/PersistentStorage');
- const bootstrap = await import('@app/features/platform/state/AppStorageBootstrap');
- const persistence: PersistenceModule = await import('@app/features/platform/utils/MobXPersistence');
- const handle = await bootstrap.startAppStorage({scoped: true});
- const result = await handle.finalizeAfterSessionResolution(activeSessionAccount());
- expect(result.scope).toBe(ACTIVE_SCOPE);
- const drafts = new PersistedDrafts();
- await persistence.makePersistent(drafts, AppStorageKey.MESSAGING_DRAFTS, ['drafts', 'draftSegments']);
- return {storage, persistence, drafts, desktopBackendInstalled: result.desktopBackendInstalled};
-}
-
-async function unloadClient(client: LoadedClient): Promise<void> {
- client.persistence.flushPendingPersistWrites();
- await client.storage.flushAppStorageWrites();
- client.persistence.stopPersistent(AppStorageKey.MESSAGING_DRAFTS, client.drafts);
-}
-
-function expectActiveAccountState(client: LoadedClient, label: string): void {
- const AppStorage = client.storage.default;
- for (const entry of GOLDEN_DEPLOYED_STORAGE_ENTRIES) {
- if (entry.destination === 'raw' || entry.destination === 'named-account') {
- continue;
- }
- expect(AppStorage.getItem(entry.key), `${label}: ${entry.key}`).toBe(entry.value);
- }
- for (const name of DEPLOYED_STORE_NAMES) {
- expect(AppStorage.getItem(name), `${label}: store ${name}`).toBe(GOLDEN_VALUES.get(name));
- }
- expect(AppStorage.getItem(AppStorageKey.UI_SIDEBAR_WIDTH), label).toBe('286');
- expect(client.drafts.drafts, label).toEqual(DEPLOYED_DRAFTS);
-}
-
-function expectOtherAccountState(client: LoadedClient, label: string): void {
- const AppStorage = client.storage.default;
- for (const entry of GOLDEN_DEPLOYED_STORAGE_ENTRIES) {
- if (entry.destination === 'global' || entry.destination === 'every-account') {
- expect(AppStorage.getItem(entry.key), `${label}: ${entry.key}`).toBe(entry.value);
- }
- if (entry.destination === 'named-account') {
- expect(AppStorage.getItem(entry.key), `${label}: ${entry.key}`).toBe(entry.value);
- }
- }
- for (const key of OWNED_CONTENT_STORAGE_KEYS) {
- expect(AppStorage.getItem(key), `${label}: ${key}`).toBe(OTHER_ACCOUNT_OWNED_VALUES[key] ?? null);
- }
- for (const key of SHARED_CONTENT_STORAGE_KEYS) {
- expect(AppStorage.getItem(key), `${label}: ${key}`).toBe(GOLDEN_VALUES.get(key));
- }
- for (const [key, value] of Object.entries(OTHER_ACCOUNT_OWNED_VALUES)) {
- expect(AppStorage.getItem(key), `${label}: ${key}`).toBe(value);
- }
- expect(client.drafts.drafts, label).toEqual(DEPLOYED_DRAFTS);
-}
-
-function expectNoLegacyContent(client: LoadedClient, label: string): void {
- for (const key of CONTENT_STORAGE_KEYS) {
- expect(client.storage.default.getItem(key), `${label}: ${key}`).toBeNull();
- }
- expect(client.drafts.drafts, label).toEqual({});
-}
-
-async function expectContinuityAcrossLoads(expectDesktopBackend: boolean): Promise<void> {
- for (let load = 1; load <= LOADS_AFTER_THE_UPGRADE; load++) {
- const client = await loadClient();
- expect(client.desktopBackendInstalled, `load ${load}`).toBe(expectDesktopBackend);
- expectActiveAccountState(client, `load ${load}`);
-
- await client.storage.activateAppStorageScope(OTHER_SCOPE);
- expectOtherAccountState(client, `load ${load} after switching account`);
-
- await client.storage.activateAppStorageScope(ADDED_SINCE_SCOPE);
- expectNoLegacyContent(client, `load ${load} in an account added since the upgrade`);
-
- await client.storage.activateAppStorageScope(ACTIVE_SCOPE);
- expectActiveAccountState(client, `load ${load} after switching back`);
- await unloadClient(client);
- }
-}
-
-async function expectSharedContentReviewOnce(): Promise<void> {
- const first = await loadClient();
- expect(first.storage.default.getItem(LEGACY_SHARED_CONTENT_REVIEW_KEY)).toBe(LegacySharedContentReviewState.PENDING);
- first.storage.default.setItem(LEGACY_SHARED_CONTENT_REVIEW_KEY, LegacySharedContentReviewState.DONE);
- await first.storage.activateAppStorageScope(ADDED_SINCE_SCOPE);
- expect(first.storage.default.getItem(LEGACY_SHARED_CONTENT_REVIEW_KEY)).toBeNull();
- await first.storage.activateAppStorageScope(OTHER_SCOPE);
- expect(first.storage.default.getItem(LEGACY_SHARED_CONTENT_REVIEW_KEY)).toBe(LegacySharedContentReviewState.PENDING);
- first.storage.default.setItem(LEGACY_SHARED_CONTENT_REVIEW_KEY, LegacySharedContentReviewState.DONE);
- await unloadClient(first);
-
- const second = await loadClient();
- expect(second.storage.default.getItem(LEGACY_SHARED_CONTENT_REVIEW_KEY)).toBe(LegacySharedContentReviewState.DONE);
- await second.storage.activateAppStorageScope(OTHER_SCOPE);
- expect(second.storage.default.getItem(LEGACY_SHARED_CONTENT_REVIEW_KEY)).toBe(LegacySharedContentReviewState.DONE);
- await second.storage.activateAppStorageScope(ADDED_SINCE_SCOPE);
- expect(second.storage.default.getItem(LEGACY_SHARED_CONTENT_REVIEW_KEY)).toBeNull();
- await unloadClient(second);
-}
-
-installRuntimeBootstrap();
-
-beforeEach(async () => {
- Object.defineProperty(navigator, 'locks', {
- value: {request: <T>(_name: string, callback: () => Promise<T>): Promise<T> => callback()},
- configurable: true,
- writable: true,
- });
- window.localStorage.clear();
- Reflect.deleteProperty(window, 'electron');
- for (const name of [APP_STORAGE_INDEXED_DB_NAME, 'FluxerAccounts']) {
- await deleteDatabase(name);
- }
-});
-
-afterEach(() => {
- Object.defineProperty(navigator, 'locks', {value: null, configurable: true, writable: true});
- Reflect.deleteProperty(window, 'electron');
-});
-
-describe('a deployed profile after the upgrade', () => {
- test('on the web every store reads its own key on each later load and after an account switch', async () => {
- await seedDeployedWebAccounts();
- seedDeployedLocalStorage();
-
- await expectContinuityAcrossLoads(false);
- });
-
- test('on desktop the replanted profile reads the same through the desktop store', async () => {
- const store = createFakeDesktopStore();
- installDeployedDesktop(store);
-
- await expectContinuityAcrossLoads(true);
-
- const rows = new Map(store.snapshot().entries.map(([scope, key, value]) => [`${scope} ${key}`, value]));
- expect(rows.get(`${ACTIVE_SCOPE} ${AppStorageKey.MESSAGING_DRAFTS}`)).toBe(GOLDEN_VALUES.get('Drafts'));
- expect(rows.get(`${OTHER_SCOPE} ${AppStorageKey.MESSAGING_DRAFTS}`)).toBe(GOLDEN_VALUES.get('Drafts'));
- for (const key of SHARED_CONTENT_STORAGE_KEYS) {
- expect(rows.get(`${OTHER_SCOPE} ${key}`), key).toBe(GOLDEN_VALUES.get(key));
- expect(rows.has(`${ADDED_SINCE_SCOPE} ${key}`), key).toBe(false);
- }
- expect(rows.get(`${OTHER_SCOPE} ${AppStorageKey.UI_SIDEBAR_WIDTH}`)).toBe('331');
- expect(rows.has(`${GLOBAL_SCOPE} ${LEGACY_APP_STORAGE_MIGRATION_MARKER_KEY}`)).toBe(true);
- });
-
- test('a value changed after the upgrade is what every later load reads, in the account that changed it', async () => {
- await seedDeployedWebAccounts();
- seedDeployedLocalStorage();
- const first = await loadClient();
- runInAction(() => {
- first.drafts.drafts = {'110000000000000001': 'edited after the upgrade'};
- });
- first.storage.default.setItem(AppStorageKey.UI_SIDEBAR_WIDTH, '300');
- await unloadClient(first);
-
- const second = await loadClient();
-
- expect(second.drafts.drafts).toEqual({'110000000000000001': 'edited after the upgrade'});
- expect(second.storage.default.getItem(AppStorageKey.UI_SIDEBAR_WIDTH)).toBe('300');
- await second.storage.activateAppStorageScope(OTHER_SCOPE);
- expect(second.drafts.drafts).toEqual(DEPLOYED_DRAFTS);
- expect(second.storage.default.getItem(AppStorageKey.UI_SIDEBAR_WIDTH)).toBe('331');
- await unloadClient(second);
- });
-
- test('each stored account keeps its own drafts, location and inbox from its first activation on', async () => {
- await seedDeployedWebAccounts();
- seedDeployedLocalStorage();
- const first = await loadClient();
- await first.storage.activateAppStorageScope(OTHER_SCOPE);
- for (const key of ['Drafts', 'Location', 'Inbox', 'SelectedChannel', 'SelectedGuild']) {
- expect(first.storage.default.getItem(key), key).toBe(GOLDEN_VALUES.get(key));
- }
- runInAction(() => {
- first.drafts.drafts = {'110000000000000001': 'written by the second account'};
- });
- first.storage.default.setItem('Location', '{"lastLocation":"/channels/@me/220000000000000002"}');
- await unloadClient(first);
-
- const second = await loadClient();
-
- expect(second.drafts.drafts).toEqual(DEPLOYED_DRAFTS);
- expect(second.storage.default.getItem('Location')).toBe(GOLDEN_VALUES.get('Location'));
- await second.storage.activateAppStorageScope(OTHER_SCOPE);
- expect(second.drafts.drafts).toEqual({'110000000000000001': 'written by the second account'});
- expect(second.storage.default.getItem('Location')).toBe('{"lastLocation":"/channels/@me/220000000000000002"}');
- await second.storage.activateAppStorageScope(ADDED_SINCE_SCOPE);
- expectNoLegacyContent(second, 'an account added since the upgrade');
- await unloadClient(second);
- });
-
- test('on the web every account that received shared content is reviewed, and only once', async () => {
- await seedDeployedWebAccounts();
- seedDeployedLocalStorage();
- await expectSharedContentReviewOnce();
- });
-
- test('on desktop every account that received shared content is reviewed, and only once', async () => {
- installDeployedDesktop(createFakeDesktopStore());
- await expectSharedContentReviewOnce();
- });
-});
diff --git a/fluxer_app/src/features/platform/state/PersistentStorage.test.ts b/fluxer_app/src/features/platform/state/PersistentStorage.test.ts
deleted file mode 100644
index e63607f79..000000000
--- a/fluxer_app/src/features/platform/state/PersistentStorage.test.ts
+++ /dev/null
@@ -1,1125 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {
- AppStorageBroadcastMessage,
- AppStorageBroadcastOptions,
-} from '@app/features/platform/state/AppStorageBroadcast';
-import {AppStorageKey, LEGACY_APP_STORAGE_MIGRATION_MARKER_KEY} from '@app/features/platform/state/AppStorageKeys';
-import type {AppStorageScopeChangeEvent} from '@app/features/platform/state/PersistentStorage';
-import {
- APP_STORAGE_INDEXED_DB_NAME,
- type AppStorageStamp,
- type AppStorageWrite,
- type PersistentStorageBackend,
- PersistentStorageBackendKind,
-} from '@app/features/platform/state/PersistentStorageBackend';
-import type {
- PersistentStorageWriteQueueOptions,
- PersistentStorageWriteRequest,
-} from '@app/features/platform/state/PersistentStorageWriteQueue';
-import {getProtectedIndexedDB, getProtectedLocalStorage} from '@app/features/platform/state/ProtectedWebStorage';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
-
-type PersistentStorageModule = typeof import('@app/features/platform/state/PersistentStorage');
-type AppStorageBroadcastModule = typeof import('@app/features/platform/state/AppStorageBroadcast');
-type WriteQueueModule = typeof import('@app/features/platform/state/PersistentStorageWriteQueue');
-type BackendModule = typeof import('@app/features/platform/state/PersistentStorageBackend');
-
-interface LoadedModules {
- readonly storage: PersistentStorageModule;
- readonly broadcast: AppStorageBroadcastModule;
- readonly queue: WriteQueueModule;
- readonly backend: PersistentStorageBackend;
-}
-
-const ACCOUNT_A = 'https://one.example/api::100';
-const ACCOUNT_B = 'https://two.example/api::200';
-const GLOBAL_KEY = AppStorageKey.THEME;
-const ACCOUNT_KEY = 'UserSettings:syncedPreferencesLocal';
-const UNMAPPED_KEY = 'fluxer:ui:legacy-pane-size';
-const CONTENT_KEY = 'Drafts';
-const LEGACY_ACCOUNT_KEY = 'Notification';
-const LEGACY_GLOBAL_KEY = 'VoiceSettings';
-const SHARED_PANE_KEY = 'compact_voice_call_heights';
-
-function rawStorage(): Storage {
- const storage = getProtectedLocalStorage();
- if (storage == null) {
- throw new Error('localStorage is unavailable in the test environment');
- }
- return storage;
-}
-
-function deleteAppStorageDatabase(): Promise<void> {
- return new Promise<void>((resolve, reject) => {
- const factory = getProtectedIndexedDB();
- if (factory == null) {
- resolve();
- return;
- }
- const request = factory.deleteDatabase(APP_STORAGE_INDEXED_DB_NAME);
- request.onsuccess = () => resolve();
- request.onerror = () => reject(request.error ?? new Error('deleteDatabase failed'));
- });
-}
-
-async function loadModules(): Promise<LoadedModules> {
- vi.resetModules();
- const backendModule: BackendModule = await import('@app/features/platform/state/PersistentStorageBackend');
- const broadcast: AppStorageBroadcastModule = await import('@app/features/platform/state/AppStorageBroadcast');
- const queue: WriteQueueModule = await import('@app/features/platform/state/PersistentStorageWriteQueue');
- const storage: PersistentStorageModule = await import('@app/features/platform/state/PersistentStorage');
- return {storage, broadcast, queue, backend: backendModule.getPersistentStorageBackend()};
-}
-
-async function loadScopedStorage(): Promise<LoadedModules> {
- const modules = await loadModules();
- await modules.storage.initializeAppStorage({scoped: true});
- return modules;
-}
-
-async function waitFor(condition: () => boolean, label: string): Promise<void> {
- for (let attempt = 0; attempt < 200; attempt++) {
- if (condition()) {
- return;
- }
- await new Promise((resolve) => setTimeout(resolve, 5));
- }
- throw new Error(`timed out waiting for ${label}`);
-}
-
-function deferred<T>(): {promise: Promise<T>; resolve: (value: T) => void} {
- let resolve: (value: T) => void = () => undefined;
- const promise = new Promise<T>((settle) => {
- resolve = settle;
- });
- return {promise, resolve};
-}
-
-beforeEach(() => {
- Object.defineProperty(globalThis.navigator, 'locks', {
- value: {request: <T>(_name: string, callback: () => Promise<T>): Promise<T> => callback()},
- configurable: true,
- });
-});
-
-afterEach(async () => {
- vi.restoreAllMocks();
- Object.defineProperty(globalThis.navigator, 'locks', {value: null, configurable: true});
- rawStorage().clear();
- await deleteAppStorageDatabase();
-});
-
-describe('before initialization', () => {
- test('reads and writes go to raw localStorage, which is what AppLogger does at module init', async () => {
- const modules = await loadModules();
- rawStorage().setItem('debugLoggingEnabled', 'true');
- expect(modules.storage.default.getItem('debugLoggingEnabled')).toBe('true');
- modules.storage.default.setItem(GLOBAL_KEY, 'pre-boot');
- expect(rawStorage().getItem(GLOBAL_KEY)).toBe('pre-boot');
- await expect(modules.storage.flushAppStorageWrites()).resolves.toBeUndefined();
- expect(modules.storage.getAppStorageScope()).toBe(modules.storage.UNAUTHENTICATED_APP_STORAGE_SCOPE);
- });
-
- test('a value written before the scoped backend engages is still served afterwards', async () => {
- const modules = await loadModules();
- modules.storage.default.setItem(GLOBAL_KEY, 'pre-boot');
- await modules.storage.initializeAppStorage({scoped: true});
- expect(modules.storage.default.getItem(GLOBAL_KEY)).toBe('pre-boot');
- await modules.storage.flushAppStorageWrites();
- expect((await modules.backend.load(modules.storage.GLOBAL_APP_STORAGE_SCOPE)).get(GLOBAL_KEY)?.value).toBe(
- 'pre-boot',
- );
- });
-});
-
-describe('legacy localStorage behaviour is unchanged while the scoped backend is disabled', () => {
- let modules: LoadedModules;
-
- beforeEach(async () => {
- modules = await loadModules();
- await modules.storage.initializeAppStorage({scoped: false});
- });
-
- test('reads and writes go straight through to raw localStorage', () => {
- const AppStorage = modules.storage.default;
- AppStorage.setItem(ACCOUNT_KEY, 'value');
- expect(rawStorage().getItem(ACCOUNT_KEY)).toBe('value');
- rawStorage().setItem('WrittenOutsideAppStorage', 'raw');
- expect(AppStorage.getItem('WrittenOutsideAppStorage')).toBe('raw');
- expect(AppStorage.keys()).toContain('WrittenOutsideAppStorage');
- AppStorage.removeItem(ACCOUNT_KEY);
- expect(rawStorage().getItem(ACCOUNT_KEY)).toBeNull();
- });
-
- test('resetAppStorage and resetActiveAccountScope keep the deployed preserve-only-drafts semantics', async () => {
- const AppStorage = modules.storage.default;
- AppStorage.setItem(CONTENT_KEY, 'draft');
- AppStorage.setItem(GLOBAL_KEY, 'theme');
- await modules.storage.resetActiveAccountScope(modules.storage.PRESERVED_RESET_STORAGE_KEYS);
- expect(AppStorage.getItem(CONTENT_KEY)).toBe('draft');
- expect(AppStorage.getItem(GLOBAL_KEY)).toBeNull();
- await modules.storage.resetAppStorage([]);
- expect(AppStorage.keys()).toHaveLength(0);
- });
-
- test('deleteAppStorageScope falls back to the deployed logout wipe', async () => {
- const AppStorage = modules.storage.default;
- AppStorage.setItem(GLOBAL_KEY, 'theme');
- await modules.storage.deleteAppStorageScope(ACCOUNT_A);
- expect(AppStorage.getItem(GLOBAL_KEY)).toBeNull();
- });
-
- test('scope activation records the scope without moving any value', async () => {
- const AppStorage = modules.storage.default;
- AppStorage.setItem(ACCOUNT_KEY, 'value');
- expect(modules.storage.getAppStorageScope()).toBe(modules.storage.UNAUTHENTICATED_APP_STORAGE_SCOPE);
- await modules.storage.activateAppStorageScope(ACCOUNT_A);
- expect(modules.storage.getAppStorageScope()).toBe(ACCOUNT_A);
- expect(AppStorage.getItem(ACCOUNT_KEY)).toBe('value');
- expect(modules.storage.mutationsBlocked()).toBe(false);
- });
-
- test('another tab writing localStorage still arrives as an external change', () => {
- const AppStorage = modules.storage.default;
- const observed: Array<string | null> = [];
- const unsubscribe = AppStorage.subscribe((event) => observed.push(event.key), {source: 'external'});
- window.dispatchEvent(
- new StorageEvent('storage', {
- key: GLOBAL_KEY,
- oldValue: null,
- newValue: 'from-another-tab',
- storageArea: rawStorage(),
- }),
- );
- unsubscribe();
- expect(observed).toContain(GLOBAL_KEY);
- });
-});
-
-describe('scoped storage', () => {
- let modules: LoadedModules;
-
- beforeEach(async () => {
- modules = await loadScopedStorage();
- });
-
- test('an account scope hides the other account while the global scope stays shared', async () => {
- const AppStorage = modules.storage.default;
- await modules.storage.activateAppStorageScope(ACCOUNT_A);
- AppStorage.setItem(GLOBAL_KEY, 'shared-theme');
- AppStorage.setItem(ACCOUNT_KEY, 'a-value');
- await modules.storage.flushAppStorageWrites();
-
- await modules.storage.activateAppStorageScope(ACCOUNT_B);
- expect(AppStorage.getItem(GLOBAL_KEY)).toBe('shared-theme');
- expect(AppStorage.getItem(ACCOUNT_KEY)).toBeNull();
- AppStorage.setItem(ACCOUNT_KEY, 'b-value');
- await modules.storage.flushAppStorageWrites();
-
- await modules.storage.activateAppStorageScope(ACCOUNT_A);
- expect(AppStorage.getItem(ACCOUNT_KEY)).toBe('a-value');
- expect(rawStorage().getItem(ACCOUNT_KEY)).toBeNull();
-
- expect((await modules.backend.load(ACCOUNT_A)).get(ACCOUNT_KEY)?.value).toBe('a-value');
- expect((await modules.backend.load(ACCOUNT_B)).get(ACCOUNT_KEY)?.value).toBe('b-value');
- expect((await modules.backend.load(modules.storage.GLOBAL_APP_STORAGE_SCOPE)).get(GLOBAL_KEY)?.value).toBe(
- 'shared-theme',
- );
- });
-
- test('the keybind store is shared by every account, so a new account keeps push-to-talk', async () => {
- const AppStorage = modules.storage.default;
- await modules.storage.activateAppStorageScope(ACCOUNT_A);
- AppStorage.setItem('Keybind', '{"transmitMode":"push_to_talk"}');
- await modules.storage.flushAppStorageWrites();
-
- await modules.storage.activateAppStorageScope(ACCOUNT_B);
- expect(AppStorage.getItem('Keybind')).toBe('{"transmitMode":"push_to_talk"}');
- expect((await modules.backend.load(ACCOUNT_A)).has('Keybind')).toBe(false);
- });
-
- test('a write left in flight when the scope changes lands in the scope that made it', async () => {
- const AppStorage = modules.storage.default;
- await modules.storage.activateAppStorageScope(ACCOUNT_A);
- AppStorage.setItem(ACCOUNT_KEY, 'a-value');
- await modules.storage.activateAppStorageScope(ACCOUNT_B);
-
- expect((await modules.backend.load(ACCOUNT_A)).get(ACCOUNT_KEY)?.value).toBe('a-value');
- expect((await modules.backend.load(ACCOUNT_B)).has(ACCOUNT_KEY)).toBe(false);
- expect(AppStorage.getItem(ACCOUNT_KEY)).toBeNull();
- });
-
- test('mutations are blocked while the cache is being swapped', async () => {
- const AppStorage = modules.storage.default;
- const gate = deferred<void>();
- const load = modules.backend.load.bind(modules.backend);
- vi.spyOn(modules.backend, 'load').mockImplementation(async (scope) => {
- await gate.promise;
- return load(scope);
- });
- const activation = modules.storage.activateAppStorageScope(ACCOUNT_A);
- await waitFor(() => modules.storage.mutationsBlocked(), 'the cache swap to block mutations');
- expect(() => AppStorage.setItem(ACCOUNT_KEY, 'blocked')).toThrow(/lifecycle transition/);
- gate.resolve();
- await activation;
- expect(modules.storage.mutationsBlocked()).toBe(false);
- });
-
- test('a scope change notifies the before and after listeners and republishes every key', async () => {
- const AppStorage = modules.storage.default;
- const order: Array<string> = [];
- const beforeEvents: Array<AppStorageScopeChangeEvent> = [];
- const stopBefore = modules.storage.onBeforeAppStorageScopeChange((event) => {
- beforeEvents.push(event);
- order.push('before');
- });
- const stopAfter = modules.storage.subscribeAppStorageScope(() => {
- order.push('after');
- });
- const republished: Array<string | null> = [];
- const stopSubscription = AppStorage.subscribe((event) => republished.push(event.key), {
- key: ACCOUNT_KEY,
- source: 'external',
- });
-
- await modules.storage.activateAppStorageScope(ACCOUNT_A);
- stopBefore();
- stopAfter();
- stopSubscription();
-
- expect(order).toEqual(['before', 'after']);
- expect(beforeEvents).toEqual([
- {previousScope: modules.storage.UNAUTHENTICATED_APP_STORAGE_SCOPE, nextScope: ACCOUNT_A},
- ]);
- expect(republished).toEqual([null]);
- });
-
- test('a throwing scope listener never fails the activation', async () => {
- const stop = modules.storage.subscribeAppStorageScope(() => {
- throw new Error('listener exploded');
- });
- await expect(modules.storage.activateAppStorageScope(ACCOUNT_A)).resolves.toBeUndefined();
- stop();
- expect(modules.storage.getAppStorageScope()).toBe(ACCOUNT_A);
- });
-
- test('a legacy mobx store name registered as global stays shared across accounts', async () => {
- const AppStorage = modules.storage.default;
- await modules.storage.activateAppStorageScope(ACCOUNT_A);
- AppStorage.setItem('Theme', '{"type":"dark"}');
- await modules.storage.flushAppStorageWrites();
- await modules.storage.activateAppStorageScope(ACCOUNT_B);
- expect(AppStorage.getItem('Theme')).toBe('{"type":"dark"}');
- expect((await modules.backend.load(modules.storage.GLOBAL_APP_STORAGE_SCOPE)).get('Theme')?.value).toBe(
- '{"type":"dark"}',
- );
- expect((await modules.backend.load(ACCOUNT_A)).has('Theme')).toBe(false);
- });
-
- test('a legacy mobx store name registered as account scope is not shared', async () => {
- const AppStorage = modules.storage.default;
- await modules.storage.activateAppStorageScope(ACCOUNT_A);
- AppStorage.setItem('SelectedGuild', '{"guildId":"1"}');
- await modules.storage.flushAppStorageWrites();
- await modules.storage.activateAppStorageScope(ACCOUNT_B);
- expect(AppStorage.getItem('SelectedGuild')).toBeNull();
- });
-
- test('a failing backend never throws out of the lifecycle and the legacy corpus keeps serving reads', async () => {
- rawStorage().setItem(UNMAPPED_KEY, 'legacy-value');
- vi.spyOn(modules.backend, 'load').mockRejectedValue(new Error('backend unavailable'));
- await expect(modules.storage.activateAppStorageScope(ACCOUNT_A)).resolves.toBeUndefined();
- expect(modules.storage.default.getItem(UNMAPPED_KEY)).toBe('legacy-value');
- });
-});
-
-describe('read-through to the legacy corpus', () => {
- let modules: LoadedModules;
-
- beforeEach(async () => {
- modules = await loadScopedStorage();
- await modules.storage.activateAppStorageScope(ACCOUNT_A);
- });
-
- test('an unmapped legacy key is served and promoted into the active scope', async () => {
- rawStorage().setItem(UNMAPPED_KEY, 'legacy-value');
- expect(modules.storage.default.getItem(UNMAPPED_KEY)).toBe('legacy-value');
- await modules.storage.flushAppStorageWrites();
- expect((await modules.backend.load(ACCOUNT_A)).get(UNMAPPED_KEY)?.value).toBe('legacy-value');
- expect(rawStorage().getItem(UNMAPPED_KEY)).toBe('legacy-value');
- });
-
- test('the promotion is write-if-absent and never restamps a row the user already owns', async () => {
- await modules.backend.set(ACCOUNT_A, UNMAPPED_KEY, 'already-scoped');
- const before = (await modules.backend.get(ACCOUNT_A, UNMAPPED_KEY)) as {
- value: string;
- updatedAt: AppStorageStamp;
- };
- rawStorage().setItem(UNMAPPED_KEY, 'legacy-value');
- modules.storage.default.getItem(UNMAPPED_KEY);
- await modules.storage.flushAppStorageWrites();
- const after = await modules.backend.get(ACCOUNT_A, UNMAPPED_KEY);
- expect(after?.value).toBe('already-scoped');
- expect(after?.updatedAt).toEqual(before.updatedAt);
- });
-
- test('content keys are served but never durably copied into a foreign scope', async () => {
- rawStorage().setItem(CONTENT_KEY, '{"shared":true}');
- expect(modules.storage.default.getItem(CONTENT_KEY)).toBe('{"shared":true}');
- await modules.storage.flushAppStorageWrites();
- expect((await modules.backend.load(ACCOUNT_A)).has(CONTENT_KEY)).toBe(false);
- });
-
- test('content keys stop reading through once the legacy migration has committed', async () => {
- await modules.backend.set(
- modules.storage.GLOBAL_APP_STORAGE_SCOPE,
- LEGACY_APP_STORAGE_MIGRATION_MARKER_KEY,
- '{"version":1}',
- );
- rawStorage().setItem(CONTENT_KEY, '{"shared":true}');
- await modules.storage.activateAppStorageScope(ACCOUNT_B);
- expect(modules.storage.default.getItem(CONTENT_KEY)).toBeNull();
- await modules.storage.flushAppStorageWrites();
- expect((await modules.backend.load(ACCOUNT_B)).has(CONTENT_KEY)).toBe(false);
- });
-
- test('token and userId stay in raw localStorage and never enter the scoped backend', async () => {
- const AppStorage = modules.storage.default;
- AppStorage.setItem(AppStorageKey.AUTH_SESSION_TOKEN, 'secret');
- AppStorage.setItem(AppStorageKey.AUTH_SESSION_USER_ID, '4242');
- await modules.storage.flushAppStorageWrites();
- expect(rawStorage().getItem(AppStorageKey.AUTH_SESSION_TOKEN)).toBe('secret');
- expect(AppStorage.getItem(AppStorageKey.AUTH_SESSION_USER_ID)).toBe('4242');
- expect(AppStorage.keys()).toContain(AppStorageKey.AUTH_SESSION_TOKEN);
- for (const scope of [modules.storage.GLOBAL_APP_STORAGE_SCOPE, ACCOUNT_A]) {
- const entries = await modules.backend.load(scope);
- expect(entries.has(AppStorageKey.AUTH_SESSION_TOKEN)).toBe(false);
- expect(entries.has(AppStorageKey.AUTH_SESSION_USER_ID)).toBe(false);
- }
- });
-});
-
-describe('the synchronous raw mirror closes the asynchronous write loss window', () => {
- let modules: LoadedModules;
-
- beforeEach(async () => {
- modules = await loadScopedStorage();
- await modules.storage.activateAppStorageScope(ACCOUNT_A);
- });
-
- test('a draft is durable before the queue has drained, under a scope-qualified name', () => {
- modules.storage.default.setItem(CONTENT_KEY, '{"draft":"hello"}');
- expect(rawStorage().getItem(`fluxer:app-storage-mirror:${ACCOUNT_A}::${CONTENT_KEY}`)).toBe('{"draft":"hello"}');
- expect(rawStorage().getItem(CONTENT_KEY)).toBeNull();
- });
-
- test('a write lost between the mirror and the backend is replayed on the next activation', async () => {
- modules.storage.default.setItem(CONTENT_KEY, '{"draft":"hello"}');
- await modules.storage.flushAppStorageWrites();
- await modules.backend.delete(ACCOUNT_A, CONTENT_KEY);
-
- await modules.storage.activateAppStorageScope(ACCOUNT_B);
- expect(modules.storage.default.getItem(CONTENT_KEY)).toBeNull();
-
- await modules.storage.activateAppStorageScope(ACCOUNT_A);
- expect(modules.storage.default.getItem(CONTENT_KEY)).toBe('{"draft":"hello"}');
- await modules.storage.flushAppStorageWrites();
- expect((await modules.backend.load(ACCOUNT_A)).get(CONTENT_KEY)?.value).toBe('{"draft":"hello"}');
- });
-
- test('removing a mirrored key removes its mirror', () => {
- modules.storage.default.setItem(CONTENT_KEY, '{"draft":"hello"}');
- modules.storage.default.removeItem(CONTENT_KEY);
- expect(rawStorage().getItem(`fluxer:app-storage-mirror:${ACCOUNT_A}::${CONTENT_KEY}`)).toBeNull();
- });
-});
-
-describe('scoped wipe semantics', () => {
- let modules: LoadedModules;
-
- beforeEach(async () => {
- modules = await loadScopedStorage();
- await modules.storage.activateAppStorageScope(ACCOUNT_A);
- modules.storage.default.setItem(GLOBAL_KEY, 'shared-theme');
- modules.storage.default.setItem(ACCOUNT_KEY, 'a-value');
- modules.storage.default.setItem(CONTENT_KEY, 'draft');
- await modules.storage.flushAppStorageWrites();
- });
-
- test('deleting the active scope leaves the global scope intact', async () => {
- await modules.storage.deleteAppStorageScope(ACCOUNT_A);
- expect(modules.storage.default.getItem(GLOBAL_KEY)).toBe('shared-theme');
- expect(modules.storage.default.getItem(ACCOUNT_KEY)).toBeNull();
- expect((await modules.backend.load(ACCOUNT_A)).size).toBe(0);
- expect((await modules.backend.load(modules.storage.GLOBAL_APP_STORAGE_SCOPE)).size).toBeGreaterThan(0);
- });
-
- test('resetting the active account scope keeps the preserved keys and the global scope', async () => {
- await modules.storage.resetActiveAccountScope(modules.storage.PRESERVED_RESET_STORAGE_KEYS);
- expect(modules.storage.default.getItem(CONTENT_KEY)).toBe('draft');
- expect(modules.storage.default.getItem(ACCOUNT_KEY)).toBeNull();
- expect(modules.storage.default.getItem(GLOBAL_KEY)).toBe('shared-theme');
- expect((await modules.backend.load(ACCOUNT_A)).has(ACCOUNT_KEY)).toBe(false);
- });
-
- test('resetting the active account scope stops the read-through from resurrecting the legacy value', async () => {
- rawStorage().setItem(LEGACY_ACCOUNT_KEY, 'account-a-notifications');
- rawStorage().setItem(CONTENT_KEY, 'raw-draft');
- expect(modules.storage.default.getItem(LEGACY_ACCOUNT_KEY)).toBe('account-a-notifications');
-
- await modules.storage.resetActiveAccountScope(modules.storage.PRESERVED_RESET_STORAGE_KEYS);
-
- expect(modules.storage.default.getItem(LEGACY_ACCOUNT_KEY)).toBeNull();
- expect(modules.storage.default.getItem(CONTENT_KEY)).toBe('draft');
- expect(rawStorage().getItem(CONTENT_KEY)).toBe('raw-draft');
- });
-
- test('resetting the active account scope leaves the shared legacy corpus for other scopes to migrate', async () => {
- rawStorage().setItem(LEGACY_ACCOUNT_KEY, 'account-a-notifications');
-
- await modules.storage.resetActiveAccountScope(modules.storage.PRESERVED_RESET_STORAGE_KEYS);
-
- expect(rawStorage().getItem(LEGACY_ACCOUNT_KEY)).toBe('account-a-notifications');
- });
-
- test('a later write to a reset legacy key wins over the tombstone', async () => {
- rawStorage().setItem(LEGACY_ACCOUNT_KEY, 'account-a-notifications');
- await modules.storage.resetActiveAccountScope(modules.storage.PRESERVED_RESET_STORAGE_KEYS);
-
- modules.storage.default.setItem(LEGACY_ACCOUNT_KEY, 'fresh');
-
- expect(modules.storage.default.getItem(LEGACY_ACCOUNT_KEY)).toBe('fresh');
- });
-
- test('a reload rebuilds the tombstones instead of resurrecting the legacy value', async () => {
- rawStorage().setItem(LEGACY_ACCOUNT_KEY, 'account-a-notifications');
- await modules.storage.resetActiveAccountScope(modules.storage.PRESERVED_RESET_STORAGE_KEYS);
-
- const reloaded = await loadScopedStorage();
- await reloaded.storage.activateAppStorageScope(ACCOUNT_A);
-
- expect(reloaded.storage.default.getItem(LEGACY_ACCOUNT_KEY)).toBeNull();
- expect(reloaded.storage.default.keys()).not.toContain(AppStorageKey.ACCOUNT_RESET_KEPT_KEYS);
- expect(rawStorage().getItem(LEGACY_ACCOUNT_KEY)).toBe('account-a-notifications');
- });
-
- test('switching to another account and back does not resurrect the legacy value', async () => {
- rawStorage().setItem(LEGACY_ACCOUNT_KEY, 'account-a-notifications');
- await modules.storage.resetActiveAccountScope(modules.storage.PRESERVED_RESET_STORAGE_KEYS);
-
- await modules.storage.activateAppStorageScope(ACCOUNT_B);
- expect(modules.storage.default.getItem(LEGACY_ACCOUNT_KEY)).toBe('account-a-notifications');
- await modules.storage.activateAppStorageScope(ACCOUNT_A);
-
- expect(modules.storage.default.getItem(LEGACY_ACCOUNT_KEY)).toBeNull();
- });
-
- test('resetting the active account scope leaves the global legacy corpus alone', async () => {
- rawStorage().setItem(LEGACY_GLOBAL_KEY, 'shared-voice-settings');
- await modules.storage.resetActiveAccountScope(modules.storage.PRESERVED_RESET_STORAGE_KEYS);
- expect(rawStorage().getItem(LEGACY_GLOBAL_KEY)).toBe('shared-voice-settings');
- expect(modules.storage.default.getItem(LEGACY_GLOBAL_KEY)).toBe('shared-voice-settings');
- });
-
- test('resetting app storage clears every scope except the preserved keys', async () => {
- await modules.storage.resetAppStorage(modules.storage.PRESERVED_RESET_STORAGE_KEYS);
- expect(modules.storage.default.getItem(GLOBAL_KEY)).toBeNull();
- expect(modules.storage.default.getItem(ACCOUNT_KEY)).toBeNull();
- expect(modules.storage.default.getItem(CONTENT_KEY)).toBe('draft');
- expect((await modules.backend.load(modules.storage.GLOBAL_APP_STORAGE_SCOPE)).has(GLOBAL_KEY)).toBe(false);
- });
-});
-
-describe('removing a key that is still in the legacy corpus', () => {
- let modules: LoadedModules;
-
- beforeEach(async () => {
- modules = await loadScopedStorage();
- await modules.storage.activateAppStorageScope(ACCOUNT_A);
- });
-
- test('the read-through does not resurrect a removed value', () => {
- rawStorage().setItem(SHARED_PANE_KEY, '240');
- expect(modules.storage.default.getItem(SHARED_PANE_KEY)).toBe('240');
-
- modules.storage.default.removeItem(SHARED_PANE_KEY);
-
- expect(modules.storage.default.getItem(SHARED_PANE_KEY)).toBeNull();
- });
-
- test('removing a key with no raw shadow leaves no tombstone to persist', async () => {
- modules.storage.default.setItem(SHARED_PANE_KEY, '240');
- await modules.storage.flushAppStorageWrites();
- expect(rawStorage().getItem(SHARED_PANE_KEY)).toBeNull();
-
- modules.storage.default.removeItem(SHARED_PANE_KEY);
- await modules.storage.flushAppStorageWrites();
-
- expect(modules.storage.default.getItem(SHARED_PANE_KEY)).toBeNull();
- const globalEntries = await modules.backend.load(modules.storage.GLOBAL_APP_STORAGE_SCOPE);
- expect(globalEntries.has(AppStorageKey.DELETED_KEYS)).toBe(false);
- });
-
- test('a reload keeps the removal instead of promoting the legacy value back', async () => {
- rawStorage().setItem(SHARED_PANE_KEY, '240');
- modules.storage.default.removeItem(SHARED_PANE_KEY);
- await modules.storage.flushAppStorageWrites();
-
- const reloaded = await loadScopedStorage();
- await reloaded.storage.activateAppStorageScope(ACCOUNT_A);
-
- expect(reloaded.storage.default.getItem(SHARED_PANE_KEY)).toBeNull();
- expect(reloaded.storage.default.keys()).not.toContain(AppStorageKey.DELETED_KEYS);
- expect(rawStorage().getItem(SHARED_PANE_KEY)).toBe('240');
- await reloaded.storage.flushAppStorageWrites();
- const globalEntries = await reloaded.backend.load(reloaded.storage.GLOBAL_APP_STORAGE_SCOPE);
- expect(globalEntries.has(SHARED_PANE_KEY)).toBe(false);
- });
-
- test('a later write wins over the removal and survives a reload', async () => {
- rawStorage().setItem(SHARED_PANE_KEY, '240');
- modules.storage.default.removeItem(SHARED_PANE_KEY);
- modules.storage.default.setItem(SHARED_PANE_KEY, '320');
- await modules.storage.flushAppStorageWrites();
-
- const reloaded = await loadScopedStorage();
- await reloaded.storage.activateAppStorageScope(ACCOUNT_A);
-
- expect(reloaded.storage.default.getItem(SHARED_PANE_KEY)).toBe('320');
- });
-
- test('an account removal survives a switch away and back without following the other account', async () => {
- rawStorage().setItem(LEGACY_ACCOUNT_KEY, 'account-a-notifications');
- modules.storage.default.removeItem(LEGACY_ACCOUNT_KEY);
- await modules.storage.flushAppStorageWrites();
-
- await modules.storage.activateAppStorageScope(ACCOUNT_B);
- expect(modules.storage.default.getItem(LEGACY_ACCOUNT_KEY)).toBe('account-a-notifications');
-
- await modules.storage.activateAppStorageScope(ACCOUNT_A);
- expect(modules.storage.default.getItem(LEGACY_ACCOUNT_KEY)).toBeNull();
- });
-});
-
-const SENTINEL_KEY = 'fluxer:test:cross-tab-sentinel';
-
-describe('cross-tab synchronisation', () => {
- let modules: LoadedModules;
- const openChannels: Array<{close: () => void}> = [];
-
- beforeEach(async () => {
- modules = await loadScopedStorage();
- await modules.storage.activateAppStorageScope(ACCOUNT_A);
- });
-
- afterEach(() => {
- for (const channel of openChannels.splice(0)) {
- channel.close();
- }
- });
-
- test('a commit in this tab is published on the shared channel', async () => {
- const received: Array<{scope: string; key: string; generation: number}> = [];
- const options: AppStorageBroadcastOptions = {
- onCommit: (scope, key, generation) => received.push({scope, key, generation}),
- onScopeCleared: () => undefined,
- onReset: () => undefined,
- };
- const otherTab = new modules.broadcast.AppStorageBroadcast(options);
- openChannels.push(otherTab);
- otherTab.open();
-
- modules.storage.default.setItem(ACCOUNT_KEY, 'from-tab-a');
- await modules.storage.flushAppStorageWrites();
- await waitFor(() => received.length > 0, 'the commit to reach the other tab');
-
- expect(received[0]?.scope).toBe(ACCOUNT_A);
- expect(received[0]?.key).toBe(ACCOUNT_KEY);
- expect(received[0]?.generation).toBeGreaterThan(0);
- });
-
- test('a commit from another tab arrives as an external change', async () => {
- const observed: Array<{key: string | null; newValue: string | null; source: string}> = [];
- const unsubscribe = modules.storage.default.subscribe(
- (event) => observed.push({key: event.key, newValue: event.newValue, source: event.source}),
- {source: 'external'},
- );
- const otherTab = new modules.broadcast.AppStorageBroadcast({
- onCommit: () => undefined,
- onScopeCleared: () => undefined,
- onReset: () => undefined,
- });
- openChannels.push(otherTab);
- otherTab.open();
-
- await modules.backend.set(ACCOUNT_A, ACCOUNT_KEY, 'written-by-tab-b');
- otherTab.publishCommit(ACCOUNT_A, ACCOUNT_KEY, 7);
- await waitFor(() => observed.length > 0, 'the external change to arrive');
- unsubscribe();
-
- expect(observed[0]).toEqual({key: ACCOUNT_KEY, newValue: 'written-by-tab-b', source: 'external'});
- expect(modules.storage.default.getItem(ACCOUNT_KEY)).toBe('written-by-tab-b');
- });
-
- test('a scope clear from another tab reloads the whole cache', async () => {
- modules.storage.default.setItem(ACCOUNT_KEY, 'a-value');
- await modules.storage.flushAppStorageWrites();
- const otherTab = new modules.broadcast.AppStorageBroadcast({
- onCommit: () => undefined,
- onScopeCleared: () => undefined,
- onReset: () => undefined,
- });
- openChannels.push(otherTab);
- otherTab.open();
-
- await modules.backend.clearAllForScope(ACCOUNT_A);
- otherTab.publishScopeCleared(ACCOUNT_A);
- await waitFor(() => modules.storage.default.getItem(ACCOUNT_KEY) === null, 'the cache to drop the cleared scope');
- });
-
- test('a deletion committed by another tab stops this tab resurrecting the legacy value', async () => {
- rawStorage().setItem(SHARED_PANE_KEY, '240');
-
- const otherTab = new modules.broadcast.AppStorageBroadcast({
- onCommit: () => undefined,
- onScopeCleared: () => undefined,
- onReset: () => undefined,
- });
- openChannels.push(otherTab);
- otherTab.open();
-
- await modules.backend.set(
- modules.storage.GLOBAL_APP_STORAGE_SCOPE,
- AppStorageKey.DELETED_KEYS,
- JSON.stringify([SHARED_PANE_KEY]),
- );
- otherTab.publishCommit(modules.storage.GLOBAL_APP_STORAGE_SCOPE, AppStorageKey.DELETED_KEYS, 1);
-
- await modules.backend.set(modules.storage.GLOBAL_APP_STORAGE_SCOPE, SENTINEL_KEY, 'adopted');
- otherTab.publishCommit(modules.storage.GLOBAL_APP_STORAGE_SCOPE, SENTINEL_KEY, 1);
- await waitFor(
- () => modules.storage.default.getItem(SENTINEL_KEY) === 'adopted',
- 'the other tab commits to be applied in order',
- );
-
- expect(modules.storage.default.getItem(SHARED_PANE_KEY)).toBeNull();
- expect(rawStorage().getItem(SHARED_PANE_KEY)).toBe('240');
- });
-
- test('a scope clear from another tab does not resurrect a value the account reset tombstoned', async () => {
- rawStorage().setItem(LEGACY_ACCOUNT_KEY, 'account-a-notifications');
- expect(modules.storage.default.getItem(LEGACY_ACCOUNT_KEY)).toBe('account-a-notifications');
- await modules.storage.resetActiveAccountScope(modules.storage.PRESERVED_RESET_STORAGE_KEYS);
- const otherTab = new modules.broadcast.AppStorageBroadcast({
- onCommit: () => undefined,
- onScopeCleared: () => undefined,
- onReset: () => undefined,
- });
- openChannels.push(otherTab);
- otherTab.open();
- let reloaded = false;
- const unsubscribe = modules.storage.default.subscribe(
- (event) => {
- reloaded = reloaded || event.key === null;
- },
- {source: 'external'},
- );
-
- otherTab.publishScopeCleared(ACCOUNT_A);
- await waitFor(() => reloaded, 'the reload to settle');
- unsubscribe();
-
- expect(modules.storage.default.getItem(LEGACY_ACCOUNT_KEY)).toBeNull();
- expect(rawStorage().getItem(LEGACY_ACCOUNT_KEY)).toBe('account-a-notifications');
- });
-
- test('a local write made while a scope clear reloads the cache is not clobbered', async () => {
- modules.storage.default.setItem(ACCOUNT_KEY, 'a-value');
- await modules.storage.flushAppStorageWrites();
- const loadGate = deferred<void>();
- const writeGate = deferred<void>();
- const realLoad = modules.backend.load.bind(modules.backend);
- const loadSpy = vi.spyOn(modules.backend, 'load').mockImplementation(async (scope: string) => {
- const loaded = await realLoad(scope);
- await loadGate.promise;
- return loaded;
- });
- vi.spyOn(modules.backend, 'setMany').mockImplementation(() => writeGate.promise);
- let reloaded = false;
- const unsubscribe = modules.storage.default.subscribe(
- (event) => {
- reloaded = reloaded || event.key === null;
- },
- {source: 'external'},
- );
- const otherTab = new modules.broadcast.AppStorageBroadcast({
- onCommit: () => undefined,
- onScopeCleared: () => undefined,
- onReset: () => undefined,
- });
- openChannels.push(otherTab);
- otherTab.open();
-
- await modules.backend.clearAllForScope(ACCOUNT_A);
- otherTab.publishScopeCleared(ACCOUNT_A);
- await waitFor(() => loadSpy.mock.calls.length > 0, 'the reload to reach the backend');
- modules.storage.default.setItem(ACCOUNT_KEY, 'written-during-reload');
- loadGate.resolve();
- await waitFor(() => reloaded, 'the reload to settle');
- unsubscribe();
-
- expect(modules.storage.default.getItem(ACCOUNT_KEY)).toBe('written-during-reload');
- writeGate.resolve();
- await modules.storage.flushAppStorageWrites();
- });
-
- test('a local removal made while a scope clear reloads the cache is not resurrected', async () => {
- modules.storage.default.setItem(ACCOUNT_KEY, 'a-value');
- await modules.storage.flushAppStorageWrites();
- const loadGate = deferred<void>();
- const deleteGate = deferred<void>();
- const realLoad = modules.backend.load.bind(modules.backend);
- const loadSpy = vi.spyOn(modules.backend, 'load').mockImplementation(async (scope: string) => {
- const loaded = await realLoad(scope);
- await loadGate.promise;
- return loaded;
- });
- vi.spyOn(modules.backend, 'delete').mockImplementation(() => deleteGate.promise);
- let reloaded = false;
- const unsubscribe = modules.storage.default.subscribe(
- (event) => {
- reloaded = reloaded || event.key === null;
- },
- {source: 'external'},
- );
- const otherTab = new modules.broadcast.AppStorageBroadcast({
- onCommit: () => undefined,
- onScopeCleared: () => undefined,
- onReset: () => undefined,
- });
- openChannels.push(otherTab);
- otherTab.open();
-
- otherTab.publishScopeCleared(ACCOUNT_A);
- await waitFor(() => loadSpy.mock.calls.length > 0, 'the reload to reach the backend');
- modules.storage.default.removeItem(ACCOUNT_KEY);
- expect(modules.storage.default.getItem(ACCOUNT_KEY)).toBeNull();
- loadGate.resolve();
- await waitFor(() => reloaded, 'the reload to settle');
- unsubscribe();
-
- expect(modules.storage.default.getItem(ACCOUNT_KEY)).toBeNull();
- deleteGate.resolve();
- await modules.storage.flushAppStorageWrites();
- });
-
- test('the channel and lock names are shared by every participant', () => {
- expect(modules.broadcast.APP_STORAGE_BROADCAST_CHANNEL_NAME).toBe('fluxer:app-storage');
- expect(modules.broadcast.APP_STORAGE_SCOPE_LOCK_NAME).toBe('fluxer:app-storage:scope');
- expect(modules.broadcast.APP_STORAGE_MIGRATION_LOCK_NAME).toBe('fluxer:app-storage:migration');
- expect(modules.broadcast.AppStorageBroadcastKind.COMMIT).toBe('commit');
- });
-
- test('a malformed or self-authored message is ignored', async () => {
- const received: Array<string> = [];
- const listener = new modules.broadcast.AppStorageBroadcast({
- onCommit: (_scope, key) => received.push(key),
- onScopeCleared: () => undefined,
- onReset: () => undefined,
- });
- openChannels.push(listener);
- listener.open();
- const rawChannel = new BroadcastChannel(modules.broadcast.APP_STORAGE_BROADCAST_CHANNEL_NAME);
- openChannels.push(rawChannel);
- const accepted: AppStorageBroadcastMessage = {
- clientId: 'other',
- kind: modules.broadcast.AppStorageBroadcastKind.COMMIT,
- scope: ACCOUNT_A,
- key: 'accepted',
- generation: 1,
- };
- rawChannel.postMessage({...accepted, kind: 'nonsense', key: 'k'});
- rawChannel.postMessage(accepted);
- await waitFor(() => received.length > 0, 'the well-formed message to arrive');
- expect(received).toEqual(['accepted']);
- });
-});
-
-describe('insecure contexts', () => {
- test('storage loads and a scope activates without crypto.randomUUID or Web Locks', async () => {
- Object.defineProperty(globalThis.crypto, 'randomUUID', {value: undefined, configurable: true});
- Object.defineProperty(globalThis.navigator, 'locks', {value: null, configurable: true});
- try {
- const modules = await loadScopedStorage();
- await modules.storage.activateAppStorageScope(ACCOUNT_A);
- expect(modules.storage.getAppStorageScope()).toBe(ACCOUNT_A);
- } finally {
- Reflect.deleteProperty(globalThis.crypto, 'randomUUID');
- }
- });
-});
-
-describe('unusable IndexedDB', () => {
- const throwingFactory = {
- open: () => {
- throw new DOMException('denied', 'SecurityError');
- },
- } as unknown as IDBFactory;
-
- test('a backend whose database cannot open keeps working in memory', async () => {
- vi.spyOn(console, 'warn').mockImplementation(() => undefined);
- const backendModule: BackendModule = await import('@app/features/platform/state/PersistentStorageBackend');
- const backend = backendModule.createPersistentStorageBackend(throwingFactory);
-
- await backend.set(ACCOUNT_A, ACCOUNT_KEY, 'kept');
-
- expect((await backend.get(ACCOUNT_A, ACCOUNT_KEY))?.value).toBe('kept');
- expect(backend.kind).toBe(PersistentStorageBackendKind.MEMORY);
- });
-
- test('scope activation still switches scopes when the database cannot open', async () => {
- vi.spyOn(console, 'warn').mockImplementation(() => undefined);
- vi.resetModules();
- const backendModule: BackendModule = await import('@app/features/platform/state/PersistentStorageBackend');
- backendModule.installPersistentStorageBackend(backendModule.createPersistentStorageBackend(throwingFactory));
- const storage: PersistentStorageModule = await import('@app/features/platform/state/PersistentStorage');
- await storage.initializeAppStorage({scoped: true});
-
- await storage.activateAppStorageScope(ACCOUNT_A);
- storage.default.setItem(ACCOUNT_KEY, 'a-value');
- await storage.activateAppStorageScope(ACCOUNT_B);
-
- expect(storage.getAppStorageScope()).toBe(ACCOUNT_B);
- expect(storage.default.getItem(ACCOUNT_KEY)).toBeNull();
- await storage.activateAppStorageScope(ACCOUNT_A);
- expect(storage.default.getItem(ACCOUNT_KEY)).toBe('a-value');
- });
-});
-
-describe('web lock serialisation', () => {
- let modules: LoadedModules;
-
- beforeEach(async () => {
- modules = await loadModules();
- });
-
- test('the operation runs once without a lock when the lock manager is unavailable', async () => {
- Object.defineProperty(globalThis.navigator, 'locks', {value: null, configurable: true});
- let ran = 0;
- await expect(
- modules.broadcast.withAppStorageLock(modules.broadcast.APP_STORAGE_MIGRATION_LOCK_NAME, async () => {
- ran += 1;
- return 'unlocked';
- }),
- ).resolves.toBe('unlocked');
- expect(ran).toBe(1);
- });
-
- test('the operation is rejected before it runs when a present lock manager fails', async () => {
- Object.defineProperty(globalThis.navigator, 'locks', {
- value: {request: () => Promise.reject(new Error('lock refused'))},
- configurable: true,
- });
- let ran = false;
- await expect(
- modules.broadcast.withAppStorageLock(modules.broadcast.APP_STORAGE_MIGRATION_LOCK_NAME, async () => {
- ran = true;
- }),
- ).rejects.toBeInstanceOf(modules.broadcast.AppStorageLockUnavailableError);
- expect(ran).toBe(false);
- });
-
- test('a present lock manager serialises the operation exactly once', async () => {
- const calls: Array<string> = [];
- const locks = {
- request: async <T>(name: string, callback: () => Promise<T>): Promise<T> => {
- calls.push(name);
- return callback();
- },
- };
- Object.defineProperty(globalThis.navigator, 'locks', {value: locks, configurable: true});
- try {
- let ran = 0;
- const result = await modules.broadcast.withAppStorageLock(
- modules.broadcast.APP_STORAGE_SCOPE_LOCK_NAME,
- async () => {
- ran += 1;
- return 'held';
- },
- );
- expect(result).toBe('held');
- expect(ran).toBe(1);
- expect(calls).toEqual([modules.broadcast.APP_STORAGE_SCOPE_LOCK_NAME]);
- } finally {
- Object.defineProperty(globalThis.navigator, 'locks', {value: null, configurable: true});
- }
- });
-
- test('an operation that throws under the lock is not retried', async () => {
- const locks = {
- request: <T>(_name: string, callback: () => Promise<T>): Promise<T> => callback(),
- };
- Object.defineProperty(globalThis.navigator, 'locks', {value: locks, configurable: true});
- try {
- let ran = 0;
- await expect(
- modules.broadcast.withAppStorageLock(modules.broadcast.APP_STORAGE_SCOPE_LOCK_NAME, async () => {
- ran += 1;
- throw new Error('operation failed');
- }),
- ).rejects.toThrow('operation failed');
- expect(ran).toBe(1);
- } finally {
- Object.defineProperty(globalThis.navigator, 'locks', {value: null, configurable: true});
- }
- });
-});
-
-describe('the write queue generation guard', () => {
- interface StubBackend {
- readonly backend: PersistentStorageBackend;
- readonly writes: Array<AppStorageWrite>;
- gate: {promise: Promise<void>; resolve: () => void} | null;
- gateEntered: boolean;
- }
-
- function createStubBackend(): StubBackend {
- const stub: StubBackend = {
- writes: [],
- gate: null,
- gateEntered: false,
- backend: {
- kind: PersistentStorageBackendKind.MEMORY,
- load: () => Promise.resolve(new Map()),
- get: () => Promise.resolve(null),
- set: () => Promise.resolve(),
- delete: () => Promise.resolve(),
- clearAllForScope: () => Promise.resolve(),
- clearAllExcept: () => Promise.resolve(),
- setMany: async (writes) => {
- const gate = stub.gate;
- if (gate != null) {
- stub.gate = null;
- stub.gateEntered = true;
- await gate.promise;
- }
- stub.writes.push(...writes);
- },
- },
- };
- return stub;
- }
-
- async function holdFirstBatch(stub: StubBackend): Promise<() => void> {
- const gate = deferred<void>();
- stub.gate = gate;
- stub.gateEntered = false;
- return () => gate.resolve();
- }
-
- test('a stale in-flight write never reports a value a newer write has replaced', async () => {
- const modules = await loadModules();
- const stub = createStubBackend();
- const committed: Array<{key: string; value: string | null; generation: number}> = [];
- const queue = new modules.queue.PersistentStorageWriteQueue({
- resolveBackend: () => stub.backend,
- onCommitted: (write, generation) => committed.push({key: write.key, value: write.value, generation}),
- onFailed: () => undefined,
- });
-
- const release = await holdFirstBatch(stub);
- queue.enqueue([{scope: ACCOUNT_A, key: 'k', value: '1'}]);
- await waitFor(() => stub.gateEntered, 'the first batch to reach the backend');
- queue.enqueue([{scope: ACCOUNT_A, key: 'k', value: '2'}]);
- expect(queue.generation(ACCOUNT_A, 'k')).toBe(2);
- release();
- await queue.flush();
-
- expect(stub.writes.map((write) => write.value)).toEqual(['1', '2']);
- expect(committed).toEqual([{key: 'k', value: '2', generation: 2}]);
- });
-
- test('a delayed write from one scope never lands in another scope', async () => {
- const modules = await loadModules();
- const stub = createStubBackend();
- const queue = new modules.queue.PersistentStorageWriteQueue({
- resolveBackend: () => stub.backend,
- onCommitted: () => undefined,
- onFailed: () => undefined,
- });
-
- const release = await holdFirstBatch(stub);
- queue.enqueue([{scope: ACCOUNT_A, key: 'k', value: 'a'}]);
- await waitFor(() => stub.gateEntered, 'the first batch to reach the backend');
- queue.enqueue([{scope: ACCOUNT_B, key: 'k', value: 'b'}]);
- release();
- await queue.flush();
-
- expect(stub.writes).toEqual([
- {scope: ACCOUNT_A, key: 'k', value: 'a'},
- {scope: ACCOUNT_B, key: 'k', value: 'b'},
- ]);
- expect(modules.queue.persistentStorageWriteIdentity(ACCOUNT_A, 'k')).not.toBe(
- modules.queue.persistentStorageWriteIdentity(ACCOUNT_B, 'k'),
- );
- });
-
- test('a failed write is remembered so an identical retry is not swallowed', async () => {
- const modules = await loadModules();
- const failures: Array<string> = [];
- const options: PersistentStorageWriteQueueOptions = {
- resolveBackend: () => {
- throw new Error('backend unavailable');
- },
- onCommitted: () => undefined,
- onFailed: (write) => failures.push(write.key),
- };
- const queue = new modules.queue.PersistentStorageWriteQueue(options);
- queue.enqueue([{scope: ACCOUNT_A, key: 'k', value: '1'}]);
- await queue.flush();
- expect(failures).toEqual(['k']);
- expect(queue.hasFailure(ACCOUNT_A, 'k')).toBe(true);
- });
-
- test('a batch larger than the drain size is committed in order across batches', async () => {
- const modules = await loadModules();
- const stub = createStubBackend();
- const queue = new modules.queue.PersistentStorageWriteQueue({
- resolveBackend: () => stub.backend,
- onCommitted: () => undefined,
- onFailed: () => undefined,
- });
- const total = modules.queue.APP_STORAGE_WRITE_BATCH_SIZE + 17;
- const requests: Array<PersistentStorageWriteRequest> = [];
- for (let index = 0; index < total; index++) {
- requests.push({scope: ACCOUNT_A, key: `k${index}`, value: String(index)});
- }
- queue.enqueue(requests);
- await queue.flush();
- expect(stub.writes).toHaveLength(total);
- expect(stub.writes[0]?.key).toBe('k0');
- expect(stub.writes[total - 1]?.key).toBe(`k${total - 1}`);
- });
-
- test('invalidating a scope drops its pending writes and retires their generations', async () => {
- const modules = await loadModules();
- const stub = createStubBackend();
- const queue = new modules.queue.PersistentStorageWriteQueue({
- resolveBackend: () => stub.backend,
- onCommitted: () => undefined,
- onFailed: () => undefined,
- });
- const release = await holdFirstBatch(stub);
- queue.enqueue([{scope: ACCOUNT_A, key: 'first', value: '1'}]);
- await waitFor(() => stub.gateEntered, 'the first batch to reach the backend');
- queue.enqueue([{scope: ACCOUNT_A, key: 'second', value: '2'}]);
- const generationBefore = queue.generation(ACCOUNT_A, 'second');
- queue.invalidateScope(ACCOUNT_A);
- release();
- await queue.flush();
- expect(queue.generation(ACCOUNT_A, 'second')).toBeGreaterThan(generationBefore);
- expect(stub.writes.map((write) => write.key)).toEqual(['first']);
- });
-});
diff --git a/fluxer_app/src/features/platform/state/__fixtures__/DesktopStoreFixture.ts b/fluxer_app/src/features/platform/state/__fixtures__/DesktopStoreFixture.ts
deleted file mode 100644
index 82b457e29..000000000
--- a/fluxer_app/src/features/platform/state/__fixtures__/DesktopStoreFixture.ts
+++ /dev/null
@@ -1,324 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {
- DesktopAccountImportRequest,
- DesktopAccountRecord,
- DesktopAccountStorageAPI,
- DesktopStoreJSONObject,
- DesktopStoreSkippedRecord,
-} from '@fluxer/desktop_ipc/src/AccountContract';
-import type {
- DesktopStorageAPI,
- DesktopStorageEntry,
- DesktopStorageImportRequest,
- DesktopStorageWrite,
- DesktopStoreStatus,
-} from '@fluxer/desktop_ipc/src/StorageContract';
-
-export const FAKE_DESKTOP_STORE_AVAILABLE: DesktopStoreStatus = Object.freeze({
- available: true,
- authorityExpected: false,
- schemaVersion: 1,
- quarantined: false,
- quarantineReason: null,
- unavailableReason: null,
-});
-
-export interface FakeDesktopStoreSnapshot {
- readonly accounts: ReadonlyArray<readonly [string, string]>;
- readonly entries: ReadonlyArray<readonly [string, string, string]>;
- readonly markers: ReadonlyArray<readonly [string, string]>;
-}
-
-export interface FakeDesktopStore {
- readonly accounts: DesktopAccountStorageAPI;
- readonly storage: DesktopStorageAPI;
- failOnce(operation: string): void;
- refuseNext(key: string, reason: string): void;
- setStatus(status: DesktopStoreStatus): void;
- seedAccount(storageKey: string, record: DesktopStoreJSONObject): void;
- seedEntry(scope: string, key: string, value: string, updatedAt: number): void;
- readEntry(scope: string, key: string): DesktopStorageEntry | null;
- readAccount(storageKey: string): DesktopStoreJSONObject | null;
- snapshot(): FakeDesktopStoreSnapshot;
-}
-
-export class FakeDesktopStoreFailure extends Error {
- public constructor(operation: string) {
- super(`Injected desktop store failure: ${operation}`);
- this.name = 'FakeDesktopStoreFailure';
- }
-}
-
-function desktopStoreValuesEqual(left: unknown, right: unknown): boolean {
- if (Object.is(left, right)) {
- return true;
- }
- if (Array.isArray(left) || Array.isArray(right)) {
- return (
- Array.isArray(left) &&
- Array.isArray(right) &&
- left.length === right.length &&
- left.every((entry, index) => desktopStoreValuesEqual(entry, right[index]))
- );
- }
- if (left === null || right === null || typeof left !== 'object' || typeof right !== 'object') {
- return false;
- }
- const leftEntries = Object.entries(left);
- const rightRecord = right as Record<string, unknown>;
- return (
- leftEntries.length === Object.keys(rightRecord).length &&
- leftEntries.every(
- ([key, value]) => Object.hasOwn(rightRecord, key) && desktopStoreValuesEqual(value, rightRecord[key]),
- )
- );
-}
-
-export function createFakeDesktopStore(options?: {readonly status?: DesktopStoreStatus}): FakeDesktopStore {
- const accountRows = new Map<string, DesktopStoreJSONObject>();
- const refusals = new Map<string, string>();
- const takeRefusals = (keys: ReadonlyArray<string>): Array<DesktopStoreSkippedRecord> => {
- const skipped: Array<DesktopStoreSkippedRecord> = [];
- for (const key of keys) {
- const reason = refusals.get(key);
- if (reason === undefined) continue;
- refusals.delete(key);
- skipped.push({key, reason});
- }
- return skipped;
- };
- const entryRows = new Map<string, Map<string, DesktopStorageEntry>>();
- const markers = new Map<string, string>();
- const failures = new Set<string>();
- let status = options?.status ?? FAKE_DESKTOP_STORE_AVAILABLE;
- let stamp = 0;
-
- const nextStamp = (): number => {
- const now = Date.now();
- stamp = now > stamp ? now : stamp + 1;
- return stamp;
- };
-
- const observe = (value: number): void => {
- stamp = value > stamp ? value : stamp;
- };
-
- const gate = (operation: string): void => {
- if (failures.delete(operation)) {
- throw new FakeDesktopStoreFailure(operation);
- }
- };
-
- const scopeOf = (scope: string): Map<string, DesktopStorageEntry> => {
- let entries = entryRows.get(scope);
- if (entries == null) {
- entries = new Map<string, DesktopStorageEntry>();
- entryRows.set(scope, entries);
- }
- return entries;
- };
-
- const writeEntry = ({scope, key, value, ifAbsent}: DesktopStorageWrite): void => {
- const entries = scopeOf(scope);
- if (ifAbsent === true && entries.has(key)) {
- return;
- }
- entries.set(key, {key, value, updatedAt: nextStamp()});
- };
-
- const accounts: DesktopAccountStorageAPI = {
- getAll: async () => {
- gate('accounts.getAll');
- return [...accountRows].map(([storageKey, record]) => ({storageKey, record}));
- },
-
- get: async (storageKey) => {
- gate('accounts.get');
- const record = accountRows.get(storageKey);
- return record == null ? null : {storageKey, record};
- },
-
- upsert: async (account: DesktopAccountRecord) => {
- gate('accounts.upsert');
- accountRows.set(account.storageKey, account.record);
- },
-
- compareAndSwap: async ({expected, replacement}) => {
- gate('accounts.compareAndSwap');
- const current = accountRows.get(expected.storageKey);
- if (
- current === undefined ||
- replacement.storageKey !== expected.storageKey ||
- !desktopStoreValuesEqual(current, expected.record)
- ) {
- return false;
- }
- accountRows.set(replacement.storageKey, replacement.record);
- return true;
- },
-
- delete: async (storageKey) => {
- gate('accounts.delete');
- accountRows.delete(storageKey);
- },
-
- import: async (request: DesktopAccountImportRequest) => {
- gate('accounts.import');
- const skipped = takeRefusals(request.records.map((record) => record.storageKey));
- const refused = new Set(skipped.map((record) => record.key));
- for (const record of request.records) {
- if (refused.has(record.storageKey)) continue;
- accountRows.set(record.storageKey, record.record);
- }
- if (request.marker != null) {
- markers.set(request.marker.key, request.marker.value);
- }
- return {imported: request.records.length - skipped.length, skipped, unusableInstances: []};
- },
-
- prune: async (request) => {
- gate('accounts.prune');
- if (!request.listIsAuthoritative) {
- return {pruned: [], refusedReason: 'the known account list was not authoritative'};
- }
- const known = new Set(request.knownStorageKeys);
- const pruned: Array<string> = [];
- for (const storageKey of [...accountRows.keys()]) {
- if (known.has(storageKey)) {
- continue;
- }
- accountRows.delete(storageKey);
- entryRows.delete(storageKey);
- pruned.push(storageKey);
- }
- return {pruned, refusedReason: null};
- },
- };
-
- const storage: DesktopStorageAPI = {
- getStatus: async () => {
- gate('storage.getStatus');
- return status;
- },
-
- load: async (scope) => {
- gate('storage.load');
- return [...(entryRows.get(scope)?.values() ?? [])];
- },
-
- get: async (scope, key) => {
- gate('storage.get');
- return entryRows.get(scope)?.get(key) ?? null;
- },
-
- set: async (scope, key, value) => {
- gate('storage.set');
- writeEntry({scope, key, value});
- },
-
- delete: async (scope, key) => {
- gate('storage.delete');
- entryRows.get(scope)?.delete(key);
- },
-
- clearAllForScope: async (scope) => {
- gate('storage.clearAllForScope');
- entryRows.delete(scope);
- },
-
- clearAllExcept: async (keysToKeep) => {
- gate('storage.clearAllExcept');
- const keep = new Set(keysToKeep);
- for (const entries of entryRows.values()) {
- for (const key of [...entries.keys()]) {
- if (!keep.has(key)) {
- entries.delete(key);
- }
- }
- }
- },
-
- setMany: async (writes) => {
- gate('storage.setMany');
- for (const write of writes) {
- writeEntry(write);
- }
- },
-
- import: async (request: DesktopStorageImportRequest) => {
- gate('storage.import');
- const skipped = takeRefusals(request.entries.map((entry) => entry.key));
- const refused = new Set(skipped.map((entry) => entry.key));
- for (const entry of request.entries) {
- if (refused.has(entry.key)) continue;
- observe(entry.updatedAt);
- scopeOf(entry.scope).set(entry.key, {key: entry.key, value: entry.value, updatedAt: entry.updatedAt});
- }
- if (request.marker != null) {
- markers.set(request.marker.key, request.marker.value);
- }
- return {imported: request.entries.length - skipped.length, skipped};
- },
-
- getMarker: async (key) => {
- gate('storage.getMarker');
- return markers.get(key) ?? null;
- },
-
- setMarker: async (key, value) => {
- gate('storage.setMarker');
- markers.set(key, value);
- },
- };
-
- return {
- accounts,
- storage,
-
- refuseNext(key, reason) {
- refusals.set(key, reason);
- },
-
- failOnce(operation) {
- failures.add(operation);
- },
-
- setStatus(next) {
- status = next;
- },
-
- seedAccount(storageKey, record) {
- accountRows.set(storageKey, record);
- },
-
- seedEntry(scope, key, value, updatedAt) {
- observe(updatedAt);
- scopeOf(scope).set(key, {key, value, updatedAt});
- },
-
- readEntry(scope, key) {
- return entryRows.get(scope)?.get(key) ?? null;
- },
-
- readAccount(storageKey) {
- return accountRows.get(storageKey) ?? null;
- },
-
- snapshot() {
- const entries: Array<readonly [string, string, string]> = [];
- for (const [scope, scoped] of entryRows) {
- for (const entry of scoped.values()) {
- entries.push([scope, entry.key, entry.value]);
- }
- }
- return {
- accounts: [...accountRows]
- .map(([storageKey, record]) => [storageKey, JSON.stringify(record)] as const)
- .sort((left, right) => (left[0] < right[0] ? -1 : 1)),
- entries: entries.sort((left, right) => (`${left[0]} ${left[1]}` < `${right[0]} ${right[1]}` ? -1 : 1)),
- markers: [...markers].sort((left, right) => (left[0] < right[0] ? -1 : 1)),
- };
- },
- };
-}
diff --git a/fluxer_app/src/features/platform/state/__fixtures__/LegacyStorageFixtures.ts b/fluxer_app/src/features/platform/state/__fixtures__/LegacyStorageFixtures.ts
deleted file mode 100644
index f36ab0aad..000000000
--- a/fluxer_app/src/features/platform/state/__fixtures__/LegacyStorageFixtures.ts
+++ /dev/null
@@ -1,806 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-type GoldenStorageDestination =
- | 'raw'
- | 'global'
- | 'every-account'
- | 'content-account'
- | 'shared-content'
- | 'named-account';
-
-interface GoldenStorageEntry {
- readonly key: string;
- readonly value: string;
- readonly kind: 'session' | 'mobx-persist' | 'plain' | 'accessibility' | 'unknown';
- readonly destination: GoldenStorageDestination;
- readonly source: string;
-}
-
-const GOLDEN_ACCOUNT_USER_ID = '100000000000000002';
-const GOLDEN_OTHER_ACCOUNT_USER_ID = '100000000000000003';
-const GOLDEN_MAINTENANCE_ID = '9876543210';
-
-function mobxPersistBlob(properties: Record<string, unknown>, version = 1): string {
- return JSON.stringify({...properties, __mps__: {version}});
-}
-
-const SESSION_ENTRIES: ReadonlyArray<GoldenStorageEntry> = [
- {
- key: 'token',
- value: 'ODAwMDAwMDAwMDAwMDAwMDAx.aBcDeF.notARealTokenValue00000000000',
- kind: 'session',
- destination: 'raw',
- source: 'features/platform/state/auth_session/AuthSessionStorage.ts:4',
- },
- {
- key: 'userId',
- value: GOLDEN_ACCOUNT_USER_ID,
- kind: 'session',
- destination: 'raw',
- source: 'features/platform/state/auth_session/AuthSessionStorage.ts:5',
- },
- {
- key: 'runtimeConfig',
- value: '{"legacy":true}',
- kind: 'session',
- destination: 'raw',
- source: 'features/auth/state/AccountStorage.ts:67 (MANAGED_KEY_EXACT, nothing writes it)',
- },
- {
- key: 'AccountManager',
- value: '{"legacy":true}',
- kind: 'session',
- destination: 'raw',
- source: 'features/auth/state/AccountStorage.ts:67 (MANAGED_KEY_EXACT, nothing writes it)',
- },
-];
-
-const MOBX_PERSIST_ENTRIES: ReadonlyArray<GoldenStorageEntry> = [
- {
- key: 'Theme',
- value: mobxPersistBlob({syncAcrossDevices: true, localTheme: 'dark', serverTheme: 'dark'}),
- kind: 'mobx-persist',
- destination: 'global',
- source: 'features/theme/state/Theme.ts:193',
- },
- {
- key: 'Drafts',
- value: mobxPersistBlob({drafts: {'110000000000000001': 'unsent message text'}, draftSegments: {}}),
- kind: 'mobx-persist',
- destination: 'shared-content',
- source: 'features/messaging/state/MessagingDrafts.ts:61',
- },
- {
- key: 'SelectedGuild',
- value: mobxPersistBlob({lastSelectedGuildId: '120000000000000001'}),
- kind: 'mobx-persist',
- destination: 'shared-content',
- source: 'features/navigation/state/SelectedGuild.ts:23',
- },
- {
- key: 'SelectedChannel',
- value: mobxPersistBlob({selectedChannelIds: {}, recentlyVisitedChannels: []}),
- kind: 'mobx-persist',
- destination: 'shared-content',
- source: 'features/navigation/state/SelectedChannel.ts:50',
- },
- {
- key: 'VoiceSettings',
- value: mobxPersistBlob({inputDeviceId: 'default', outputVolume: 100, noiseSuppression: 'standard'}),
- kind: 'mobx-persist',
- destination: 'global',
- source: 'features/voice/state/VoiceSettings.ts:426',
- },
- {
- key: 'LocalVoiceState',
- value: mobxPersistBlob({persistedSelfMute: true, persistedSelfDeaf: false, noiseSuppressionEnabled: true}),
- kind: 'mobx-persist',
- destination: 'global',
- source: 'features/voice/state/LocalVoiceState.ts:248',
- },
- {
- key: 'VoiceSessionRestore',
- value: mobxPersistBlob({snapshot: {userId: GOLDEN_ACCOUNT_USER_ID, channelId: '110000000000000009'}}),
- kind: 'mobx-persist',
- destination: 'global',
- source: 'features/voice/state/VoiceSessionRestore.ts:30',
- },
- {
- key: 'Notification',
- value: mobxPersistBlob({
- browserNotificationsEnabled: true,
- unreadMessageBadgeEnabled: true,
- ttsNotificationMode: 'never',
- }),
- kind: 'mobx-persist',
- destination: 'every-account',
- source: 'features/ui/state/Notification.ts:180',
- },
- {
- key: 'Inbox',
- value: mobxPersistBlob({
- selectedTab: 'unreads',
- hasAutoOpenedBookmarksPopoutForFirstSave: true,
- skipMarkAllAsReadConfirmation: false,
- }),
- kind: 'mobx-persist',
- destination: 'shared-content',
- source: 'features/inbox/state/Inbox.ts:22',
- },
- {
- key: 'Location',
- value: mobxPersistBlob({lastLocation: '/channels/@me', lastMobileLayoutState: null}),
- kind: 'mobx-persist',
- destination: 'shared-content',
- source: 'features/ui/state/Location.ts:22',
- },
- {
- key: 'GuildFolderExpanded',
- value: mobxPersistBlob({expandedFolderIds: [1]}),
- kind: 'mobx-persist',
- destination: 'every-account',
- source: 'features/guild/state/GuildFolderExpanded.ts:15',
- },
- {
- key: 'SearchHistory',
- value: mobxPersistBlob({entriesByChannel: {'110000000000000001': ['from:me']}}),
- kind: 'mobx-persist',
- destination: 'shared-content',
- source: 'features/search/state/SearchHistory.ts:18',
- },
- {
- key: 'ChannelFrecencyLocal',
- value: mobxPersistBlob({localUseLog: {}}),
- kind: 'mobx-persist',
- destination: 'shared-content',
- source: 'features/channel/state/ChannelFrecency.ts:206',
- },
- {
- key: 'GuildMatureContentAgreeLocal',
- value: mobxPersistBlob({localAgreedChannelIds: ['110000000000000001']}),
- kind: 'mobx-persist',
- destination: 'shared-content',
- source: 'features/guild/state/GuildMatureContentAgree.ts:116',
- },
- {
- key: 'ThreadPanelWidth',
- value: mobxPersistBlob({width: 420}),
- kind: 'mobx-persist',
- destination: 'shared-content',
- source: 'features/threads/state/ThreadPanelWidth.ts:30',
- },
- {
- key: 'SearchEngine',
- value: mobxPersistBlob({engines: [{id: 'ddg', name: 'DuckDuckGo'}]}, 2),
- kind: 'mobx-persist',
- destination: 'every-account',
- source: 'features/search/state/SearchEngine.ts:62',
- },
- {
- key: 'ReverseImageSearch',
- value: mobxPersistBlob({engines: [{id: 'google', name: 'Google Lens'}]}, 2),
- kind: 'mobx-persist',
- destination: 'every-account',
- source: 'features/search/state/ReverseImageSearch.ts:71',
- },
- {
- key: 'Slowmode',
- value: mobxPersistBlob({lastSendTimestamps: {}, cooldownExpiresAt: {}}),
- kind: 'mobx-persist',
- destination: 'every-account',
- source: 'features/slowmode/state/Slowmode.ts:50',
- },
- {
- key: 'Translation',
- value: mobxPersistBlob({engines: [{id: 'deepl'}]}),
- kind: 'mobx-persist',
- destination: 'every-account',
- source: 'features/messaging/state/Translation.ts:77',
- },
- {
- key: 'Keybind',
- value: mobxPersistBlob(
- {
- customKeybinds: {},
- transmitMode: 'voice_activity',
- pushToTalkReleaseDelay: 200,
- syncAcrossDevices: false,
- disableBuiltinKeybinds: false,
- },
- 5,
- ),
- kind: 'mobx-persist',
- destination: 'global',
- source: 'features/input/state/InputKeybind.ts:107,287,1001',
- },
- {
- key: 'ParticipantVolume',
- value: mobxPersistBlob({volumes: {'130000000000000001': 140}, localMutes: {}}),
- kind: 'mobx-persist',
- destination: 'global',
- source: 'features/voice/state/ParticipantVolume.ts:90',
- },
- {
- key: 'StreamAudioPrefs',
- value: mobxPersistBlob({entries: {'130000000000000001': {volume: 80}}}),
- kind: 'mobx-persist',
- destination: 'global',
- source: 'features/voice/state/StreamAudioPrefs.ts:45',
- },
- {
- key: 'EntranceSoundListenerPrefs',
- value: mobxPersistBlob({volumes: {'130000000000000001': 50}, localMutes: {}}),
- kind: 'mobx-persist',
- destination: 'global',
- source: 'features/voice/state/EntranceSoundListenerPrefs.ts:27',
- },
- {
- key: 'NewDeviceMonitoring',
- value: mobxPersistBlob({knownDeviceIds: ['device-a'], ignoredDeviceIds: [], suppressAlerts: false}),
- kind: 'mobx-persist',
- destination: 'global',
- source: 'features/auth/state/NewDeviceMonitoring.tsx:94',
- },
- {
- key: 'AudioVolume',
- value: mobxPersistBlob({volume: 75, isMuted: false}),
- kind: 'mobx-persist',
- destination: 'global',
- source: 'features/voice/state/AudioVolume.ts:19',
- },
- {
- key: 'VideoVolume',
- value: mobxPersistBlob({volume: 60, isMuted: true}),
- kind: 'mobx-persist',
- destination: 'global',
- source: 'features/voice/state/VideoVolume.ts:19',
- },
- {
- key: 'MobileLayout',
- value: mobxPersistBlob({navExpanded: false, chatExpanded: true}),
- kind: 'mobx-persist',
- destination: 'global',
- source: 'features/ui/state/MobileLayout.ts:31',
- },
- {
- key: 'MacPermissions',
- value: mobxPersistBlob({decisions: {microphone: 'granted'}, setupCompleted: true}),
- kind: 'mobx-persist',
- destination: 'global',
- source: 'features/permissions/system/state/MacPermissions.ts:58',
- },
- {
- key: 'DeveloperMode',
- value: mobxPersistBlob({manuallyEnabled: true}),
- kind: 'mobx-persist',
- destination: 'global',
- source: 'features/devtools/state/DeveloperMode.ts:22',
- },
- {
- key: 'DeveloperOptions',
- value: mobxPersistBlob({showVoiceDebugOverlay: true}),
- kind: 'mobx-persist',
- destination: 'global',
- source: 'features/devtools/state/DeveloperOptions.ts:193',
- },
- {
- key: 'StreamerMode',
- value: mobxPersistBlob({
- manualEnabled: false,
- autoEnable: true,
- hidePersonalInformation: true,
- hideInviteLinks: true,
- disableSounds: false,
- disableNotifications: false,
- nagbarDismissed: true,
- }),
- kind: 'mobx-persist',
- destination: 'global',
- source: 'features/streamer_mode/state/StreamerMode.ts:9,50',
- },
-];
-
-const PLAIN_ENTRIES: ReadonlyArray<GoldenStorageEntry> = [
- {
- key: 'theme',
- value: 'dark',
- kind: 'plain',
- destination: 'global',
- source: 'features/theme/state/Theme.ts:25',
- },
- {
- key: 'locale',
- value: 'sv',
- kind: 'plain',
- destination: 'global',
- source: 'app/I18n.ts:156',
- },
- {
- key: 'debugLoggingEnabled',
- value: 'true',
- kind: 'plain',
- destination: 'global',
- source: 'features/platform/utils/AppLogger.ts:41',
- },
- {
- key: 'SkeletonLayoutMemory',
- value: JSON.stringify({version: 9, updatedAt: 1_755_000_000_000, accountFingerprint: 'abc123'}),
- kind: 'plain',
- destination: 'global',
- source: 'features/app/components/skeleton/SkeletonLayoutMemory.ts:16',
- },
- {
- key: 'MessageEdit',
- value: JSON.stringify({'110000000000000001': 'half-finished edit'}),
- kind: 'plain',
- destination: 'shared-content',
- source: 'features/messaging/state/MessageEdit.ts:7',
- },
- {
- key: 'ChannelFrecencyThreadGuilds',
- value: JSON.stringify(['110000000000000002']),
- kind: 'plain',
- destination: 'shared-content',
- source: 'features/channel/state/ChannelFrecency.ts:42',
- },
- {
- key: 'TrustedDomain',
- value: JSON.stringify(['example.com']),
- kind: 'plain',
- destination: 'shared-content',
- source: 'features/trusted_domain/state/TrustedDomain.ts:17',
- },
- {
- key: 'SoftwareEncoderWarning_neverShowAgain',
- value: 'true',
- kind: 'plain',
- destination: 'global',
- source: 'features/voice/state/SoftwareEncoderWarning.ts:8',
- },
- {
- key: 'pip_corner',
- value: 'bottom-right',
- kind: 'plain',
- destination: 'global',
- source: 'features/ui/state/PiP.ts:21',
- },
- {
- key: 'pip_width',
- value: '480',
- kind: 'plain',
- destination: 'global',
- source: 'features/ui/state/PiP.ts:22',
- },
- {
- key: 'incoming_call_overlay_position',
- value: JSON.stringify({x: 24, y: 96}),
- kind: 'plain',
- destination: 'global',
- source: 'features/voice/components/IncomingCallOverlayConstants.ts:5',
- },
- {
- key: 'compact_voice_call_heights',
- value: JSON.stringify({defaultHeight: 220, heightsByKey: {}, expandedByKey: {}}),
- kind: 'plain',
- destination: 'global',
- source: 'features/voice/state/CompactVoiceCallHeight.ts:12',
- },
- {
- key: 'member_list_default_hidden_channel_overrides',
- value: JSON.stringify({'110000000000000001': true}),
- kind: 'plain',
- destination: 'shared-content',
- source: 'features/member/state/MemberList.ts:10',
- },
- {
- key: 'AdvancedSettings:unreadBadgeCustomizationEnabled',
- value: 'true',
- kind: 'plain',
- destination: 'every-account',
- source: 'features/user/state/AdvancedSettings.ts:6',
- },
- {
- key: 'AdvancedSettings:keepAttachmentsOnEmptyMessageEdit',
- value: 'true',
- kind: 'plain',
- destination: 'every-account',
- source: 'features/user/state/AdvancedSettings.ts:7',
- },
- {
- key: 'AdvancedSettings:expressionCloneShortcutsEnabled',
- value: 'true',
- kind: 'plain',
- destination: 'every-account',
- source: 'features/user/state/AdvancedSettings.ts:8',
- },
- {
- key: 'UserSettings:syncedPreferencesLocal',
- value: 'CgYIARICEAE=',
- kind: 'plain',
- destination: 'every-account',
- source: 'features/user/state/UserSettings.ts:115',
- },
- {
- key: 'UserSettings:syncedPreferencesWire',
- value: 'CgYIARICEAE=',
- kind: 'plain',
- destination: 'raw',
- source: 'features/user/state/UserSettings.ts:116',
- },
- {
- key: 'UserSettings:syncedPreferencesDirtyFields',
- value: JSON.stringify(['theme']),
- kind: 'plain',
- destination: 'raw',
- source: 'features/user/state/UserSettings.ts:114',
- },
- {
- key: 'UserSettings:syncedPreferencesRecentAck',
- value: JSON.stringify({theme: 1_755_000_000_000}),
- kind: 'plain',
- destination: 'raw',
- source: 'features/user/state/UserSettings.ts:117',
- },
- {
- key: 'ThemeStudio:section',
- value: 'library',
- kind: 'plain',
- destination: 'global',
- source: 'features/theme_studio/state/ThemeStudioState.ts:8',
- },
- {
- key: 'ThemeStudio:expandedGroups',
- value: JSON.stringify(['colors']),
- kind: 'plain',
- destination: 'global',
- source: 'features/theme_studio/state/ThemeStudioState.ts:9',
- },
- {
- key: 'ThemeStudio:librarySplit',
- value: '320',
- kind: 'plain',
- destination: 'global',
- source: 'features/theme_studio/sections/LibrarySection.tsx:405',
- },
- {
- key: 'fluxer.lastPushEndpoint',
- value: 'https://fcm.googleapis.com/fcm/send/abc123',
- kind: 'plain',
- destination: 'global',
- source: 'features/platform/push/PushSubscriptionService.ts:19',
- },
- {
- key: 'fluxer:media:volume',
- value: '0.8',
- kind: 'plain',
- destination: 'global',
- source: 'features/voice/components/media_player/hooks/useMediaPlayer.ts:9',
- },
- {
- key: 'fluxer:media:muted',
- value: 'false',
- kind: 'plain',
- destination: 'global',
- source: 'features/voice/components/media_player/hooks/useMediaPlayer.ts:10',
- },
- {
- key: 'fluxer:media:playbackRate',
- value: '1.25',
- kind: 'plain',
- destination: 'global',
- source: 'features/voice/components/media_player/hooks/useMediaPlayer.ts:11',
- },
- {
- key: 'fluxer:media_player:volume',
- value: '0.6',
- kind: 'plain',
- destination: 'content-account',
- source: 'features/voice/components/media_player/utils/MediaConstants.ts:15',
- },
- {
- key: 'fluxer:media_player:muted',
- value: 'true',
- kind: 'plain',
- destination: 'content-account',
- source: 'features/voice/components/media_player/utils/MediaConstants.ts:16',
- },
- {
- key: 'fluxer:media_player:playback-rate',
- value: '2',
- kind: 'plain',
- destination: 'global',
- source: 'features/voice/components/media_player/utils/MediaConstants.ts:17',
- },
- {
- key: 'fluxer:media_caps:v2',
- value: JSON.stringify({av1: false, h265: true}),
- kind: 'plain',
- destination: 'global',
- source: 'features/voice/utils/MediaCapabilities.ts:19',
- },
- {
- key: 'fluxer:ui:sidebar-width',
- value: '286',
- kind: 'plain',
- destination: 'content-account',
- source: 'features/ui/state/SidebarWidth.ts:7',
- },
- {
- key: 'fluxer:ui:channel-pins-popout-size',
- value: '{"width":480,"height":620}',
- kind: 'plain',
- destination: 'content-account',
- source: 'features/channel/components/popouts/ChannelPinsPopout.tsx:74',
- },
- {
- key: 'fluxer:media:playbackRates',
- value: '{"audio":1.25,"video":1.5}',
- kind: 'plain',
- destination: 'content-account',
- source: 'features/voice/components/media_player/hooks/useMediaPlayer.ts:16',
- },
- {
- key: 'Keybind:globalDefaultMigration:v1',
- value: '1',
- kind: 'plain',
- destination: 'global',
- source: 'features/input/state/InputKeybind.ts:208',
- },
- {
- key: 'Keybind:builtinDisableMarkerMigration:v1',
- value: '1',
- kind: 'plain',
- destination: 'global',
- source: 'features/input/state/InputKeybind.ts:209',
- },
- {
- key: 'fluxer:ui:expression-picker-size',
- value: JSON.stringify({width: 420, height: 480}),
- kind: 'plain',
- destination: 'content-account',
- source: 'features/expressions/components/popouts/ExpressionPickerPopout.tsx:220',
- },
- {
- key: 'fluxer:ui:inbox-popout-size',
- value: JSON.stringify({width: 500, height: 640}),
- kind: 'plain',
- destination: 'content-account',
- source: 'features/messaging/components/popouts/InboxPopout.tsx:95',
- },
- {
- key: `fluxer_scheduled_maintenance_dismissed:${GOLDEN_MAINTENANCE_ID}`,
- value: '1',
- kind: 'plain',
- destination: 'content-account',
- source: 'features/app/components/layout/app_layout/ScheduledMaintenanceDismissal.ts:8',
- },
- {
- key: `fluxer_scheduled_maintenance_dismissed:${GOLDEN_MAINTENANCE_ID}:in_progress`,
- value: '1',
- kind: 'plain',
- destination: 'content-account',
- source: 'features/app/components/layout/app_layout/ScheduledMaintenanceDismissal.ts:12',
- },
-];
-
-const ACCESSIBILITY_ENTRIES: ReadonlyArray<GoldenStorageEntry> = [
- {
- key: 'Accessibility',
- value: JSON.stringify({zoomLevel: 1.25, reducedMotionOverride: null}),
- kind: 'accessibility',
- destination: 'every-account',
- source: 'features/accessibility/state/Accessibility.ts:34',
- },
- {
- key: 'Accessibility:zoomLevel',
- value: '1.25',
- kind: 'accessibility',
- destination: 'every-account',
- source: 'features/accessibility/state/Accessibility.ts:35',
- },
- {
- key: 'Accessibility:customThemeCss',
- value: JSON.stringify(':root { --flx-accent: #ff00aa; }'),
- kind: 'accessibility',
- destination: 'every-account',
- source: 'features/accessibility/state/Accessibility.ts:36',
- },
- {
- key: 'Accessibility:customThemeCssSyncAcrossDevices',
- value: 'false',
- kind: 'accessibility',
- destination: 'every-account',
- source: 'features/accessibility/state/Accessibility.ts:42',
- },
- {
- key: 'Accessibility:motion',
- value: JSON.stringify({syncReducedMotionWithSystem: false, reducedMotionOverride: true}),
- kind: 'accessibility',
- destination: 'every-account',
- source: 'features/accessibility/state/Accessibility.ts:37',
- },
- {
- key: 'Accessibility:videoSeekPreviewThumbnails',
- value: 'false',
- kind: 'accessibility',
- destination: 'every-account',
- source: 'features/accessibility/state/Accessibility.ts:41',
- },
- {
- key: 'Accessibility:showNeko',
- value: 'true',
- kind: 'accessibility',
- destination: 'every-account',
- source: 'features/accessibility/state/Accessibility.ts:38',
- },
- {
- key: `Accessibility:showNeko:${GOLDEN_OTHER_ACCOUNT_USER_ID}`,
- value: 'false',
- kind: 'accessibility',
- destination: 'named-account',
- source: 'features/accessibility/state/Accessibility.ts:43',
- },
- {
- key: 'Accessibility:keepNekoStill',
- value: 'false',
- kind: 'accessibility',
- destination: 'every-account',
- source: 'features/accessibility/state/Accessibility.ts:39',
- },
- {
- key: `Accessibility:keepNekoStill:${GOLDEN_OTHER_ACCOUNT_USER_ID}`,
- value: 'true',
- kind: 'accessibility',
- destination: 'named-account',
- source: 'features/accessibility/state/Accessibility.ts:44',
- },
- {
- key: 'Accessibility:pinNekoToTextarea',
- value: 'true',
- kind: 'accessibility',
- destination: 'every-account',
- source: 'features/accessibility/state/Accessibility.ts:40',
- },
- {
- key: `Accessibility:pinNekoToTextarea:${GOLDEN_OTHER_ACCOUNT_USER_ID}`,
- value: 'false',
- kind: 'accessibility',
- destination: 'named-account',
- source: 'features/accessibility/state/Accessibility.ts:45',
- },
-];
-
-export const GOLDEN_UNKNOWN_STORAGE_ENTRIES: ReadonlyArray<GoldenStorageEntry> = [
- {
- key: 'LegacyExperiment:cohort',
- value: 'control',
- kind: 'unknown',
- destination: 'global',
- source: 'no writer in this tree, retired build residue',
- },
- {
- key: 'fluxer:experimental:unshipped-toggle',
- value: 'on',
- kind: 'unknown',
- destination: 'global',
- source: 'no writer in this tree. It matches MANAGED_KEY_PREFIXES, so the deployed swap moves it today',
- },
- {
- key: 'mobx-legacy-orphan-store',
- value: '{"__mps__":{"version":1}}',
- kind: 'unknown',
- destination: 'global',
- source: 'no writer in this tree, matches MANAGED_KEY_PREFIXES',
- },
- {
- key: 'persist:orphaned-widget-state',
- value: '{}',
- kind: 'unknown',
- destination: 'global',
- source: 'no writer in this tree, matches MANAGED_KEY_PREFIXES',
- },
- {
- key: '__vendor_extension_probe__',
- value: '1',
- kind: 'unknown',
- destination: 'global',
- source: 'no writer in this tree, third-party residue on the same origin',
- },
-];
-
-export const GOLDEN_DEPLOYED_STORAGE_ENTRIES: ReadonlyArray<GoldenStorageEntry> = [
- ...SESSION_ENTRIES,
- ...MOBX_PERSIST_ENTRIES,
- ...PLAIN_ENTRIES,
- ...ACCESSIBILITY_ENTRIES,
-];
-
-export const GOLDEN_LOCAL_STORAGE_CORPUS: ReadonlyArray<GoldenStorageEntry> = [
- ...GOLDEN_DEPLOYED_STORAGE_ENTRIES,
- ...GOLDEN_UNKNOWN_STORAGE_ENTRIES,
-];
-
-export const OWNED_CONTENT_STORAGE_KEYS: ReadonlyArray<string> = GOLDEN_DEPLOYED_STORAGE_ENTRIES.filter(
- (entry) => entry.destination === 'content-account',
-).map((entry) => entry.key);
-
-export const SHARED_CONTENT_STORAGE_KEYS: ReadonlyArray<string> = GOLDEN_DEPLOYED_STORAGE_ENTRIES.filter(
- (entry) => entry.destination === 'shared-content',
-).map((entry) => entry.key);
-
-export const CONTENT_STORAGE_KEYS: ReadonlyArray<string> = [
- ...OWNED_CONTENT_STORAGE_KEYS,
- ...SHARED_CONTENT_STORAGE_KEYS,
-];
-
-export const NOT_MIGRATED_STORAGE_KEYS = [
- 'UserSettings:syncedPreferencesWire',
- 'UserSettings:syncedPreferencesDirtyFields',
- 'UserSettings:syncedPreferencesRecentAck',
-] as const;
-
-export interface GoldenStorageScopes {
- readonly global: string;
- readonly everyAccount: ReadonlyArray<string>;
- readonly contentAccount: string | null;
- readonly sharedContent: ReadonlyArray<string>;
- readonly namedAccount: string;
-}
-
-function goldenDestinationScopes(entry: GoldenStorageEntry, scopes: GoldenStorageScopes): ReadonlyArray<string> {
- switch (entry.destination) {
- case 'raw':
- return [];
- case 'global':
- return [scopes.global];
- case 'every-account':
- return scopes.everyAccount;
- case 'content-account':
- return scopes.contentAccount === null ? [] : [scopes.contentAccount];
- case 'shared-content':
- return scopes.sharedContent;
- case 'named-account':
- return [scopes.namedAccount];
- }
-}
-
-export function goldenStorageRowIdentity(scope: string, key: string): string {
- return `${scope} ${key}`;
-}
-
-export function expectedGoldenStorageRows(scopes: GoldenStorageScopes): Map<string, string> {
- const rows = new Map<string, string>();
- for (const entry of GOLDEN_LOCAL_STORAGE_CORPUS) {
- for (const scope of goldenDestinationScopes(entry, scopes)) {
- rows.set(goldenStorageRowIdentity(scope, entry.key), entry.value);
- }
- }
- rows.set(
- goldenStorageRowIdentity(scopes.global, 'fluxer:migration:unclassified-legacy-keys'),
- JSON.stringify(GOLDEN_UNKNOWN_STORAGE_ENTRIES.map((entry) => entry.key).sort()),
- );
- return rows;
-}
-
-export const DEPLOYED_MANAGED_KEY_PREFIXES = ['mobx', 'mobx-persist', 'persist', 'fluxer'] as const;
-
-export function seedGoldenLocalStorage(storage: Storage): void {
- for (const entry of GOLDEN_LOCAL_STORAGE_CORPUS) {
- storage.setItem(entry.key, entry.value);
- }
-}
-
-export function readGoldenLocalStorageSnapshot(storage: Storage): Record<string, string> {
- const snapshot: Record<string, string> = {};
- for (let index = 0; index < storage.length; index++) {
- const key = storage.key(index);
- if (key == null) {
- continue;
- }
- const value = storage.getItem(key);
- if (value != null) {
- snapshot[key] = value;
- }
- }
- return snapshot;
-}
diff --git a/fluxer_app/src/features/platform/state/__fixtures__/PersistedStoreNames.ts b/fluxer_app/src/features/platform/state/__fixtures__/PersistedStoreNames.ts
deleted file mode 100644
index 836dad8d7..000000000
--- a/fluxer_app/src/features/platform/state/__fixtures__/PersistedStoreNames.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {readdirSync, readFileSync, statSync} from 'node:fs';
-import {dirname, join, resolve} from 'node:path';
-import {fileURLToPath} from 'node:url';
-import {AppStorageKey} from '@app/features/platform/state/AppStorageKeys';
-
-const SOURCE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../../../..');
-const EXCLUDED_PATH_PATTERN = /node_modules|\.test\.|__fixtures__/;
-const PERSISTED_STORE_PATTERN = /makePersistent\(\s*this,\s*([A-Za-z_.']+)/g;
-
-function collectSourceFiles(directory: string): Array<string> {
- const files: Array<string> = [];
- for (const name of readdirSync(directory)) {
- const path = join(directory, name);
- if (EXCLUDED_PATH_PATTERN.test(path)) {
- continue;
- }
- if (statSync(path).isDirectory()) {
- files.push(...collectSourceFiles(path));
- } else if (name.endsWith('.ts') || name.endsWith('.tsx')) {
- files.push(path);
- }
- }
- return files;
-}
-
-function resolveStoreName(expression: string, source: string): string {
- if (expression.startsWith("'")) {
- return expression.slice(1, -1);
- }
- const value = expression.startsWith('AppStorageKey.')
- ? (AppStorageKey as Record<string, string>)[expression.slice('AppStorageKey.'.length)]
- : new RegExp(`const ${expression} = '([^']+)'`).exec(source)?.[1];
- if (value === undefined) {
- throw new Error(`makePersistent is called with an unresolvable store name: ${expression}`);
- }
- return value;
-}
-
-export const STORES_WITHOUT_DEPLOYED_DATA: ReadonlySet<string> = new Set(['SourceMaps', 'WindowsFont']);
-
-export function readPersistedStoreNames(): Array<string> {
- const names = new Set<string>();
- for (const path of collectSourceFiles(SOURCE_ROOT)) {
- const source = readFileSync(path, 'utf8');
- for (const match of source.matchAll(PERSISTED_STORE_PATTERN)) {
- names.add(resolveStoreName(match[1]!, source));
- }
- }
- return [...names].sort();
-}
diff --git a/fluxer_app/src/features/platform/state/__fixtures__/RuntimeBootstrapFixture.ts b/fluxer_app/src/features/platform/state/__fixtures__/RuntimeBootstrapFixture.ts
deleted file mode 100644
index 245f51447..000000000
--- a/fluxer_app/src/features/platform/state/__fixtures__/RuntimeBootstrapFixture.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {runtimeSnapshotFromDiscovery} from '@app/features/app/state/InstanceSnapshotStore';
-import RuntimeConfig from '@app/features/app/state/RuntimeConfig';
-import {parseInstanceDiscoveryDocument} from '@fluxer/instance_bootstrap/src/Discovery';
-import type {
- InstanceAgePolicy,
- InstanceAppPublic,
- InstanceDiscoveryResponse,
-} from '@fluxer/instance_bootstrap/src/Types';
-
-const BOOTSTRAP_API_ENDPOINT = 'https://fluxer.app/api';
-
-export const BOOTSTRAP_APP_PUBLIC: InstanceAppPublic = {
- branding: {
- product_name: 'Fluxer',
- icon_url: null,
- symbol_url: null,
- logo_url: null,
- wordmark_url: null,
- favicon_url: null,
- theme_color: null,
- status_page_url: null,
- status_page_incident_history_url: null,
- premium_product_name: 'Plutonium',
- premium_info_url: null,
- },
- setup: {configured: true, admin_url: null},
- legal: {terms_url: null, privacy_url: null, guidelines_url: null},
- registration: {collect_date_of_birth: true},
-};
-
-export function instanceDiscoveryFixture(
- apiEndpoint: string,
- agePolicy?: InstanceAgePolicy,
-): InstanceDiscoveryResponse {
- return {
- ...(agePolicy ? {age_policy: agePolicy} : {}),
- api_code_version: 9,
- endpoints: {
- api: apiEndpoint,
- api_client: apiEndpoint,
- api_public: apiEndpoint,
- gateway: 'wss://gateway.fluxer.app',
- media: 'https://media.fluxer.app',
- static_cdn: 'https://cdn.fluxer.app',
- marketing: 'https://fluxer.app',
- admin: 'https://admin.fluxer.app',
- invite: 'https://flux.gg',
- gift: 'https://flux.gift',
- webapp: 'https://fluxer.app',
- upload_relay: 'https://upload.fluxer.app',
- },
- captcha: {provider: 'none'},
- features: {
- voice_enabled: true,
- stripe_enabled: false,
- self_hosted: false,
- presigned_attachment_uploads: true,
- emails_enabled: true,
- premium_enabled: false,
- stripe_serviceable: false,
- phone_verification_enabled: false,
- },
- gif: {provider: 'tenor', display_name: 'Tenor', attribution_required: true},
- sso: {enabled: false, enforced: false, display_name: null, redirect_uri: ''},
- registration: {mode: 'open', admin_registration_urls_enabled: true},
- community: {
- single_community: false,
- single_community_guild_id: null,
- direct_messages_disabled: false,
- guild_create_access: true,
- },
- services: {gif_enabled: true, youtube_enabled: false, bluesky_enabled: false},
- limits: {version: 1, traitDefinitions: [], rules: []},
- push: {public_vapid_key: null},
- app_public: BOOTSTRAP_APP_PUBLIC,
- };
-}
-
-export function installRuntimeBootstrap(apiEndpoint: string = BOOTSTRAP_API_ENDPOINT): void {
- RuntimeConfig.applySnapshot(
- runtimeSnapshotFromDiscovery(parseInstanceDiscoveryDocument(instanceDiscoveryFixture(apiEndpoint))),
- );
-}
diff --git a/fluxer_app/src/features/platform/state/auth_session/AuthSessionStoredAccountResolver.test.ts b/fluxer_app/src/features/platform/state/auth_session/AuthSessionStoredAccountResolver.test.ts
deleted file mode 100644
index 9406770c6..000000000
--- a/fluxer_app/src/features/platform/state/auth_session/AuthSessionStoredAccountResolver.test.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {RuntimeConfigSnapshot} from '@app/features/app/state/RuntimeConfig';
-import {
- FIXTURE_CURRENT_INSTANCE_SNAPSHOT,
- FIXTURE_NOW,
-} from '@app/features/auth/state/__fixtures__/AccountRecordFixtures';
-import type {QualifiedStoredAccount} from '@app/features/auth/state/AccountStorageContract';
-import type {
- ReadyStoredAccountEntry,
- StoredAccountInventory,
- StoredAccountRuntimeRecoveryCandidate,
-} from '@app/features/auth/state/StoredAccountInventoryContract';
-import {
- AuthSessionStoredAccountResolver,
- type AuthSessionStoredAccountResolverStorage,
- StoredAccountNotFoundError,
-} from '@app/features/platform/state/auth_session/AuthSessionStoredAccountResolver';
-import {describe, expect, it} from 'vitest';
-
-const PRIMARY_INSTANCE_KEY = 'https://fluxer.app/api';
-const FOREIGN_INSTANCE_KEY = 'https://self.hosted.example/api';
-
-function instanceSnapshot(apiEndpoint: string): RuntimeConfigSnapshot {
- return {...FIXTURE_CURRENT_INSTANCE_SNAPSHOT, apiEndpoint, apiPublicEndpoint: apiEndpoint};
-}
-
-function accountKeyOf(instanceKey: string, userId: string): string {
- return `${instanceKey}::${userId}`;
-}
-
-function qualifiedRecord(instanceKey: string, userId: string): QualifiedStoredAccount {
- return {
- userId,
- token: `token.${instanceKey}.${userId}`,
- presenceIntent: null,
- localStorageData: {},
- managedStorageData: {},
- lastActive: FIXTURE_NOW,
- instance: instanceSnapshot(instanceKey),
- storageKey: accountKeyOf(instanceKey, userId),
- };
-}
-
-function readyEntry(instanceKey: string, userId: string): ReadyStoredAccountEntry {
- return {kind: 'ready', record: qualifiedRecord(instanceKey, userId), revision: {kind: 'stored-account-revision'}};
-}
-
-function recoveryCandidate(instanceKey: string, userId: string): StoredAccountRuntimeRecoveryCandidate {
- const record = qualifiedRecord(instanceKey, userId);
- return {
- kind: 'runtime-recovery',
- data: record,
- storageKey: record.storageKey,
- instanceKey,
- revision: {kind: 'stored-account-revision'},
- };
-}
-
-function inventory(overrides: Partial<StoredAccountInventory> = {}): StoredAccountInventory {
- return {
- source: 'idb',
- readyEntries: [],
- runtimeRecoveryCandidates: [],
- unqualifiedRecords: [],
- unavailableRecords: [],
- ...overrides,
- };
-}
-
-function createResolver(stored: StoredAccountInventory): AuthSessionStoredAccountResolver {
- const accountStorage: AuthSessionStoredAccountResolverStorage = {
- getAccountInventory: async () => stored,
- replaceInventoryEntry: async () => {
- throw new Error('replaceInventoryEntry must not be reached');
- },
- };
- return new AuthSessionStoredAccountResolver({
- accountStorage,
- resolveRuntimeEndpoint: async () => {
- throw new Error('resolveRuntimeEndpoint must not be reached');
- },
- });
-}
-
-describe('AuthSessionStoredAccountResolver prepareAccount', () => {
- it('prepares the record stored under the exact key it was handed', async () => {
- const resolver = createResolver(inventory({readyEntries: [readyEntry(PRIMARY_INSTANCE_KEY, '1')]}));
-
- const record = await resolver.prepareAccount(accountKeyOf(PRIMARY_INSTANCE_KEY, '1'));
-
- expect(record.storageKey).toBe(accountKeyOf(PRIMARY_INSTANCE_KEY, '1'));
- expect(record.token).toBe(`token.${PRIMARY_INSTANCE_KEY}.1`);
- });
-
- it('refuses a key for one instance when only the same user on another instance is stored', async () => {
- const resolver = createResolver(inventory({readyEntries: [readyEntry(PRIMARY_INSTANCE_KEY, '1')]}));
-
- await expect(resolver.prepareAccount(accountKeyOf(FOREIGN_INSTANCE_KEY, '1'))).rejects.toBeInstanceOf(
- StoredAccountNotFoundError,
- );
- });
-
- it('refuses a key for one instance when the same user is only awaiting runtime recovery elsewhere', async () => {
- const resolver = createResolver(
- inventory({runtimeRecoveryCandidates: [recoveryCandidate(PRIMARY_INSTANCE_KEY, '1')]}),
- );
-
- await expect(resolver.prepareAccount(accountKeyOf(FOREIGN_INSTANCE_KEY, '1'))).rejects.toBeInstanceOf(
- StoredAccountNotFoundError,
- );
- });
-
- it('refuses a key naming a user that is stored on no instance', async () => {
- const resolver = createResolver(inventory({readyEntries: [readyEntry(PRIMARY_INSTANCE_KEY, '1')]}));
-
- await expect(resolver.prepareAccount(accountKeyOf(PRIMARY_INSTANCE_KEY, '2'))).rejects.toBeInstanceOf(
- StoredAccountNotFoundError,
- );
- });
-});