A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
test(app): remove account storage, access and auth helper tests
Hampus9b5f7d59b8fa
diff --git a/fluxer_app/src/features/auth/AccountDisplayUtils.test.ts b/fluxer_app/src/features/auth/AccountDisplayUtils.test.tsdeleted file mode 100644index 3f19d4653..000000000--- a/fluxer_app/src/features/auth/AccountDisplayUtils.test.ts+++ /dev/null@@ -1,92 +0,0 @@-// @vitest-environment happy-dom-// SPDX-License-Identifier: AGPL-3.0-or-later--import {FIXTURE_CURRENT_INSTANCE_SNAPSHOT} from '@app/features/auth/state/__fixtures__/AccountRecordFixtures';-import {installHarnessBootstrap} from '@app/features/auth/state/__fixtures__/AccountSwitchHarness';-import type {Account} from '@app/features/platform/state/AuthSession';-import {describe, expect, test, vi} from 'vitest';--vi.mock('@lingui/core/macro', () => {- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};-});--vi.mock('@app/features/channel/state/Channels', () => ({default: {getChannel: () => null}}));-vi.mock('@app/features/member/state/GuildMembers', () => ({default: {getMember: () => null}}));-vi.mock('@app/features/navigation/state/SelectedGuild', () => ({default: {selectedGuildId: null}}));-vi.mock('@app/features/relationship/state/Relationships', () => ({default: {getRelationship: () => null}}));--installHarnessBootstrap();--const {runtimeInstanceKey} = await import('@app/features/app/state/InstanceSnapshotStore');--const {- getAccountDisplayLabels,- resolveAccountInstanceDomain,- resolveAccountInstanceLabel,- resolveSnapshotInstanceDomain,- resolveSnapshotInstanceKey,-} = await import('@app/features/auth/AccountDisplayUtils');--const SNAPSHOT = FIXTURE_CURRENT_INSTANCE_SNAPSHOT;--function accountWith(instance: Account['instance']): Account {- return {- storageKey: 'https://fluxer.app/api::100000000000000001',- userId: '100000000000000001',- token: 'token',- lastActive: 0,- isValid: true,- instance,- };-}--const UNUSABLE_SNAPSHOTS: ReadonlyArray<readonly [string, Account['instance']]> = [- ['instance undefined', undefined],- ['blank endpoints', {...SNAPSHOT, apiEndpoint: '', webAppEndpoint: ''}],- ['blank webAppEndpoint', {...SNAPSHOT, webAppEndpoint: ''}],- ['unparsable endpoints', {...SNAPSHOT, apiEndpoint: 'not a url', webAppEndpoint: 'not a url'}],- ['userinfo and query in apiEndpoint', {...SNAPSHOT, apiEndpoint: 'https://o:[email protected]/api?tenant=1'}],- ['endpoints missing entirely', {} as unknown as NonNullable<Account['instance']>],-];--describe('display helpers are total', () => {- for (const [label, instance] of UNUSABLE_SNAPSHOTS) {- test(`${label} never throws and never white-screens a tile`, () => {- const account = accountWith(instance);- expect(() => resolveSnapshotInstanceKey(instance)).not.toThrow();- expect(() => resolveSnapshotInstanceDomain(instance)).not.toThrow();- expect(() => resolveAccountInstanceDomain(account)).not.toThrow();- expect(() => resolveAccountInstanceLabel(account)).not.toThrow();- expect(() => getAccountDisplayLabels(account)).not.toThrow();- });- }-- test('instance undefined resolves to null everywhere', () => {- expect(resolveSnapshotInstanceKey(undefined)).toBeNull();- expect(resolveSnapshotInstanceDomain(undefined)).toBeNull();- expect(resolveAccountInstanceDomain(accountWith(undefined))).toBeNull();- });-- test('a blank webAppEndpoint resolves to a null domain', () => {- expect(resolveSnapshotInstanceDomain({...SNAPSHOT, webAppEndpoint: ''})).toBeNull();- expect(resolveAccountInstanceDomain(accountWith({...SNAPSHOT, webAppEndpoint: ''}))).toBeNull();- });-- test('an unparsable endpoint resolves to null', () => {- expect(resolveSnapshotInstanceKey({...SNAPSHOT, apiEndpoint: 'not a url'})).toBeNull();- expect(resolveSnapshotInstanceDomain({...SNAPSHOT, webAppEndpoint: 'not a url'})).toBeNull();- });-});--describe('instance key derivation', () => {- test('uses the one exported runtimeInstanceKey', () => {- expect(resolveSnapshotInstanceKey(SNAPSHOT)).toBe(runtimeInstanceKey(SNAPSHOT));- });-- test('a trailing slash and mixed case never orphan an account', () => {- const pathed = {...SNAPSHOT, apiEndpoint: 'HTTPS://Self.Hosted.Example/fluxer/api/'};- expect(resolveSnapshotInstanceKey(pathed)).toBe('https://self.hosted.example/fluxer/api');- expect(resolveSnapshotInstanceKey(pathed)).toBe(runtimeInstanceKey(pathed));- });-});diff --git a/fluxer_app/src/features/auth/InstanceBranding.test.ts b/fluxer_app/src/features/auth/InstanceBranding.test.tsdeleted file mode 100644index 0f3f71bf8..000000000--- a/fluxer_app/src/features/auth/InstanceBranding.test.ts+++ /dev/null@@ -1,49 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import type {RuntimeConfigSnapshot} from '@app/features/app/state/RuntimeConfigSnapshot';-import {resolveInstanceAssetUrl} from '@app/features/auth/InstanceBranding';-import {describe, expect, test} from 'vitest';--type Branding = RuntimeConfigSnapshot['appPublic']['branding'];--function snapshot(branding: Partial<Branding>, origin = 'https://chat.example.org') {- return {- apiEndpoint: `${origin}/api`,- apiPublicEndpoint: `${origin}/api`,- mediaEndpoint: `${origin}/media`,- staticCdnEndpoint: origin,- webAppEndpoint: origin,- appPublic: {- branding: {- product_name: 'Example Chat',- 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: 'Premium',- premium_info_url: null,- ...branding,- },- setup: {configured: true, admin_url: null},- legal: {terms_url: null, privacy_url: null, guidelines_url: null},- registration: {collect_date_of_birth: false},- },- };-}--describe('instance branding', () => {- test('only accepts assets served by the instance itself', () => {- const s = snapshot({});- expect(resolveInstanceAssetUrl(s, '/media/branding/icon.png')).toBe(- 'https://chat.example.org/media/branding/icon.png',- );- expect(resolveInstanceAssetUrl(s, 'https://tracker.example.net/icon.png')).toBeNull();- expect(resolveInstanceAssetUrl(s, 'javascript:alert(1)')).toBeNull();- expect(resolveInstanceAssetUrl(s, 'https://user:[email protected]/icon.png')).toBeNull();- expect(resolveInstanceAssetUrl(s, 'http://chat.example.org/icon.png')).toBeNull();- });-});diff --git a/fluxer_app/src/features/auth/altcha/CaptchaInterceptor.test.ts b/fluxer_app/src/features/auth/altcha/CaptchaInterceptor.test.tsdeleted file mode 100644index 9875eb491..000000000--- a/fluxer_app/src/features/auth/altcha/CaptchaInterceptor.test.ts+++ /dev/null@@ -1,195 +0,0 @@-// @vitest-environment happy-dom-// SPDX-License-Identifier: AGPL-3.0-or-later--import {- HARNESS_API_ENDPOINT,- installHarnessBootstrap,-} from '@app/features/auth/state/__fixtures__/AccountSwitchHarness';-import type {MessageDescriptor} from '@lingui/core';-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';--vi.mock('@lingui/core/macro', () => ({msg: (descriptor: MessageDescriptor) => descriptor}));--vi.mock('@app/features/ui/commands/ToastCommands', () => ({- createToast: () => 'toast',- destroyToast: () => undefined,-}));--const solveAltchaChallenge = vi.fn(async (challenge: {signature: string}) => `solved:${challenge.signature}`);--vi.mock('@app/features/auth/altcha/AltchaSolver', () => ({- readAltchaChallenge: (body: unknown) => {- const record = body as {captcha_provider?: string; altcha_challenge?: unknown};- return record.captcha_provider === 'altcha' ? (record.altcha_challenge ?? null) : null;- },- solveAltchaChallenge: (challenge: {signature: string}) => solveAltchaChallenge(challenge),-}));--interface SentRequest {- url: string;- headers: Record<string, string>;-}--const replies: Array<{status: number; body: unknown}> = [];-const sent: Array<SentRequest> = [];--class StubXMLHttpRequest extends EventTarget {- readonly upload = new EventTarget();- private readonly headers: Record<string, string> = {};- private url = '';- status = 200;- statusText = 'OK';- responseText = '';- response: unknown = '';- responseType = '';- timeout = 0;-- open(_method: string, url: string): void {- this.url = url;- }-- setRequestHeader(name: string, value: string): void {- this.headers[name.toLowerCase()] = value;- }-- getAllResponseHeaders(): string {- return 'content-type: application/json\r\n';- }-- abort(): void {- this.dispatchEvent(new Event('abort'));- this.dispatchEvent(new Event('loadend'));- }-- send(): void {- sent.push({url: this.url, headers: {...this.headers}});- const reply = replies.shift() ?? {status: 200, body: {}};- this.status = reply.status;- this.statusText = reply.status >= 200 && reply.status < 300 ? 'OK' : 'Error';- this.responseText = JSON.stringify(reply.body);- this.response = this.responseText;- queueMicrotask(() => {- this.dispatchEvent(new Event('load'));- this.dispatchEvent(new Event('loadend'));- });- }-}--installHarnessBootstrap();--await import('@app/features/auth/altcha/CaptchaInterceptor');-const {instanceRequest, instanceRequestWithinAccountTransition} = await import(- '@app/features/platform/transport/InstanceHTTP'-);-const {AccountScopedWork, AccountScopedWorkTransitionReason} = await import(- '@app/features/platform/state/AccountScopedWork'-);-const {isAccountTransitionAbortError} = await import('@app/features/platform/state/AccountTransitionAbort');-const {http} = await import('@app/features/platform/transport/RestTransport');--const FOREIGN_TARGET = {- instanceKey: 'https://foreign.test/api',- apiEndpoint: 'https://foreign.test/api',- apiVersion: 1,-};--function captchaRequired(signature: string) {- return {- status: 400,- body: {- code: 'CAPTCHA_REQUIRED',- captcha_provider: 'altcha',- altcha_challenge: {parameters: {}, signature},- },- };-}--beforeEach(() => {- vi.stubGlobal('XMLHttpRequest', StubXMLHttpRequest);- replies.length = 0;- sent.length = 0;- solveAltchaChallenge.mockClear();- http.configure({baseUrl: `${window.location.origin}/api`, apiVersion: 1});- http.installAuth(() => 'active-account-token');-});--afterEach(() => {- vi.unstubAllGlobals();- http.installAuth(() => null);-});--describe('CaptchaInterceptor on instance-targeted requests', () => {- test('solves and retries against the targeted instance, not the active runtime', async () => {- expect(http.matchesConfiguredRouting(HARNESS_API_ENDPOINT, FOREIGN_TARGET.apiVersion)).toBe(false);- replies.push(captchaRequired('foreign-challenge'), {status: 200, body: {token: 'session'}});-- const reply = await instanceRequest<{token: string}>({- method: 'POST',- path: '/auth/register',- target: FOREIGN_TARGET,- body: {username: 'someone'},- });-- expect(reply.body).toEqual({token: 'session'});- expect(solveAltchaChallenge).toHaveBeenCalledWith({parameters: {}, signature: 'foreign-challenge'});- expect(sent.map((request) => request.url)).toEqual([- 'https://foreign.test/api/v1/auth/register',- 'https://foreign.test/api/v1/auth/register',- ]);- expect(http.hasAuthorization()).toBe(true);- expect(sent[0].headers.authorization).toBeUndefined();- expect(sent[0].headers['x-captcha-token']).toBeUndefined();- expect(sent[1].headers['x-captcha-token']).toBe('solved:foreign-challenge');- expect(sent[1].headers['x-captcha-type']).toBeUndefined();- expect(sent[1].headers.authorization).toBeUndefined();- });-- test('a second challenge from the targeted instance is solved once more on the same instance', async () => {- replies.push(captchaRequired('first'), captchaRequired('second'), {status: 200, body: {}});-- await instanceRequest({method: 'POST', path: '/auth/login', target: FOREIGN_TARGET, body: {}, auth: 'none'});-- expect(solveAltchaChallenge.mock.calls.map(([challenge]) => challenge.signature)).toEqual(['first', 'second']);- expect(sent.map((request) => request.url)).toEqual([- 'https://foreign.test/api/v1/auth/login',- 'https://foreign.test/api/v1/auth/login',- 'https://foreign.test/api/v1/auth/login',- ]);- expect(sent[2].headers['x-captcha-token']).toBe('solved:second');- });-});--describe('InstanceHTTP during account transitions', () => {- test('logout sends its targeted request while ordinary work stays suspended', async () => {- await AccountScopedWork.runSuspended(AccountScopedWorkTransitionReason.LOGOUT, async (suspension) => {- const rejected = await instanceRequest({method: 'GET', path: '/users/@me', target: FOREIGN_TARGET}).catch(- (error: unknown) => error,- );- expect(isAccountTransitionAbortError(rejected)).toBe(true);- expect(sent).toHaveLength(0);- const reply = await instanceRequestWithinAccountTransition(- {method: 'POST', path: '/auth/logout', target: FOREIGN_TARGET, body: {}},- suspension,- );- expect(reply.status).toBe(200);- expect(sent.map((request) => request.url)).toEqual(['https://foreign.test/api/v1/auth/logout']);- expect(sent[0].headers.authorization).toBeUndefined();- expect(AccountScopedWork.isSuspended).toBe(true);- });- expect(AccountScopedWork.isSuspended).toBe(false);- });-- test('a released transition lease cannot send a request', async () => {- const suspension = await AccountScopedWork.runSuspended(- AccountScopedWorkTransitionReason.LOGOUT,- async (lease) => lease,- );- expect(() =>- instanceRequestWithinAccountTransition(- {method: 'POST', path: '/auth/logout', target: FOREIGN_TARGET},- suspension,- ),- ).toThrow('Account scoped work suspension is no longer active');- expect(sent).toHaveLength(0);- });-});diff --git a/fluxer_app/src/features/auth/components/pages/oauth_authorize_page/hooks/useOptOutSelection.test.tsx b/fluxer_app/src/features/auth/components/pages/oauth_authorize_page/hooks/useOptOutSelection.test.tsxdeleted file mode 100644index dba099a83..000000000--- a/fluxer_app/src/features/auth/components/pages/oauth_authorize_page/hooks/useOptOutSelection.test.tsx+++ /dev/null@@ -1,63 +0,0 @@-// @vitest-environment happy-dom-// SPDX-License-Identifier: AGPL-3.0-or-later--import {useOptOutSelection} from '@app/features/auth/components/pages/oauth_authorize_page/hooks/useOptOutSelection';-import {useScopeSelection} from '@app/features/auth/components/pages/oauth_authorize_page/hooks/useScopeSelection';-import {act} from 'react';-import {createRoot, type Root} from 'react-dom/client';-import {afterEach, beforeEach, describe, expect, it} from 'vitest';--let root: Root;-let node: HTMLDivElement;-let scopes: ReturnType<typeof useScopeSelection>;-let selection: ReturnType<typeof useOptOutSelection>;-const neverLocked = () => false;-const lockedEmail = (key: string) => key === 'email';-const requested = ['bot', 'identify', 'email'];-function Probe({locked = neverLocked}: {locked?: (key: string) => boolean}) {- scopes = useScopeSelection(requested);- selection = useOptOutSelection(requested, locked);- return null;-}-beforeEach(async () => {- node = document.createElement('div');- document.body.append(node);- root = createRoot(node);- (globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;- await act(async () => root.render(<Probe data-flx="auth.oauth-authorize-page.use-opt-out-selection-test.probe" />));-});-afterEach(async () => {- await act(async () => root.unmount());- node.remove();-});-describe('OAuth opt-out consent guards', () => {- it('cannot deselect the required bot scope, while optional scope choices reach the wire string', async () => {- await act(async () => {- scopes.toggle('bot');- scopes.toggle('email');- });- expect(scopes.isLocked('bot')).toBe(true);- expect(scopes.selected.has('bot')).toBe(true);- expect(scopes.selected.has('email')).toBe(false);- expect(scopes.toScopeString()).toBe('bot identify');- expect(scopes.adjusted).toBe(true);- });- it('restores a newly locked item even when an older opt-out override exists', async () => {- await act(async () => selection.toggle('email'));- expect(selection.selected.has('email')).toBe(false);- await act(async () =>- root.render(- <Probe locked={lockedEmail} data-flx="auth.oauth-authorize-page.use-opt-out-selection-test.probe--2" />,- ),- );- expect(selection.selected.has('email')).toBe(true);- await act(async () => selection.toggle('email'));- expect(selection.selected.has('email')).toBe(true);- });- it('lets optional scopes return to their requested default', async () => {- await act(async () => scopes.toggle('email'));- await act(async () => scopes.toggle('email'));- expect(scopes.selected).toEqual(new Set(requested));- expect(scopes.adjusted).toBe(false);- });-});diff --git a/fluxer_app/src/features/auth/flow/NetworkBlockCopy.test.ts b/fluxer_app/src/features/auth/flow/NetworkBlockCopy.test.tsdeleted file mode 100644index 6e69b8c75..000000000--- a/fluxer_app/src/features/auth/flow/NetworkBlockCopy.test.ts+++ /dev/null@@ -1,23 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {ERROR_I18N_MESSAGES} from '@fluxer/errors/src/i18n/ErrorI18nMessages';-import {describe, expect, test, vi} from 'vitest';--vi.mock('@lingui/core/macro', () => ({msg: (descriptor: unknown) => descriptor}));--const {NETWORK_BLOCK_LEAD_DESCRIPTOR, NETWORK_BLOCK_LEAD_WITH_REASON_DESCRIPTOR, SHARED_NETWORK_DESCRIPTOR} =- await import('@app/features/auth/AuthMessageDescriptors');--function asErrorCatalogText(descriptor: unknown): string {- return (descriptor as {message: string}).message.replaceAll('{productName}', '{product_name}');-}--describe('network block copy matches the error catalog', () => {- test.each(['permissions.global_ip_banned', 'permissions.global_ip_temporarily_banned'] as const)('%s', (key) => {- const message = ERROR_I18N_MESSAGES[key];- expect(message).toContain(- `{reason, select, shown {${asErrorCatalogText(NETWORK_BLOCK_LEAD_WITH_REASON_DESCRIPTOR)}} other {${asErrorCatalogText(NETWORK_BLOCK_LEAD_DESCRIPTOR)}}}`,- );- expect(message).toContain(` ${asErrorCatalogText(SHARED_NETWORK_DESCRIPTOR)}{appealEmail, select,`);- });-});diff --git a/fluxer_app/src/features/auth/flow/RegisterFormFields.test.ts b/fluxer_app/src/features/auth/flow/RegisterFormFields.test.tsdeleted file mode 100644index 75f596045..000000000--- a/fluxer_app/src/features/auth/flow/RegisterFormFields.test.ts+++ /dev/null@@ -1,61 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import type {RuntimeConfigSnapshot} from '@app/features/app/state/InstanceSnapshotStore';-import {- credentialRegisterFields,- linkRegisterFields,- readRegistrationUrlCode,-} from '@app/features/auth/flow/RegisterFormFields';-import {AccountIdentityModes} from '@fluxer/constants/src/AccountIdentityConstants';-import type {InstanceRegistration} from '@fluxer/schema/src/domains/instance/InstanceSchemas';-import {describe, expect, it} from 'vitest';--function snapshot(usernameSignIn: boolean, mode: InstanceRegistration['mode']): RuntimeConfigSnapshot {- return {- features: {account_identity: usernameSignIn ? AccountIdentityModes.USERNAME : AccountIdentityModes.EMAIL},- registration: {mode, admin_registration_urls_enabled: false},- } as RuntimeConfigSnapshot;-}--const EMAIL_CREDENTIALS = {- showEmail: true,- showPassword: true,- showPasswordConfirmation: true,- showUsernameValidation: true,- requireUsername: false,-};-const USERNAME_CREDENTIALS = {- showEmail: false,- showPassword: true,- showPasswordConfirmation: true,- showUsernameValidation: true,- requireUsername: true,-};--describe('register form fields', () => {- it('asks for credentials on the full register form in both sign-in modes', () => {- expect(credentialRegisterFields(false)).toEqual(EMAIL_CREDENTIALS);- expect(credentialRegisterFields(true)).toEqual(USERNAME_CREDENTIALS);- });-- it('keeps link sign-ups minimal only where the account can sign in right away', () => {- expect(linkRegisterFields(snapshot(false, 'open'), undefined)).toEqual({showUsername: false});- expect(linkRegisterFields(snapshot(false, 'closed'), undefined)).toEqual({showUsername: false});- expect(linkRegisterFields(snapshot(false, 'approval'), undefined)).toEqual(EMAIL_CREDENTIALS);- });-- it('asks for credentials on link sign-ups through a registration URL, which can require approval', () => {- const code = readRegistrationUrlCode(new URLSearchParams('?registration_url=%20abc%20'));- expect(code).toBe('abc');- for (const mode of ['open', 'approval', 'closed'] as const) {- expect(linkRegisterFields(snapshot(false, mode), code)).toEqual(EMAIL_CREDENTIALS);- }- expect(readRegistrationUrlCode(new URLSearchParams('?registration_url=%20'))).toBeUndefined();- });-- it('always asks for a username and password on link sign-ups of a username instance', () => {- for (const mode of ['open', 'approval', 'closed'] as const) {- expect(linkRegisterFields(snapshot(true, mode), undefined)).toEqual(USERNAME_CREDENTIALS);- }- });-});diff --git a/fluxer_app/src/features/auth/flow/instance_selector/InstanceDirectoryStorage.test.ts b/fluxer_app/src/features/auth/flow/instance_selector/InstanceDirectoryStorage.test.tsdeleted file mode 100644index 733a693a5..000000000--- a/fluxer_app/src/features/auth/flow/instance_selector/InstanceDirectoryStorage.test.ts+++ /dev/null@@ -1,27 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {resolveInstanceLabel} from '@app/features/auth/flow/instance_selector/InstanceDirectoryStorage';-import {isOfficialInstanceHost} from '@fluxer/instance_bootstrap/src/OfficialInstance';-import {describe, expect, test} from 'vitest';--describe('resolveInstanceLabel', () => {- test('a self-hosted instance that reports the official product name is labelled by its host', () => {- expect(resolveInstanceLabel('Fluxer', 'http://localhost:48090')).toBe('localhost:48090');- expect(resolveInstanceLabel(' fluxer ', 'chat.example.com/fluxer')).toBe('chat.example.com');- });-});--describe('isOfficialInstanceHost', () => {- test('an official API endpoint with a path is official', () => {- expect(isOfficialInstanceHost('https://web.canary.fluxer.app/api')).toBe(true);- expect(isOfficialInstanceHost('https://canary.fluxer.com/api/')).toBe(true);- expect(isOfficialInstanceHost('https://web.fluxer.app')).toBe(true);- });-- test('other hosts are not official whatever the path', () => {- expect(isOfficialInstanceHost('http://localhost:48090/api')).toBe(false);- expect(isOfficialInstanceHost('https://fluxer.app.example.com/api')).toBe(false);- expect(isOfficialInstanceHost('https://example.com/web.fluxer.app')).toBe(false);- expect(isOfficialInstanceHost('https://web.fluxer.app/api?x=1')).toBe(false);- });-});diff --git a/fluxer_app/src/features/auth/state/AccountAccess.test.ts b/fluxer_app/src/features/auth/state/AccountAccess.test.tsdeleted file mode 100644index c63d39f5a..000000000--- a/fluxer_app/src/features/auth/state/AccountAccess.test.ts+++ /dev/null@@ -1,354 +0,0 @@-// @vitest-environment happy-dom-// SPDX-License-Identifier: AGPL-3.0-or-later--import {- HARNESS_API_ENDPOINT,- installHarnessBootstrap,- resetScriptedTransport,- ScriptedXMLHttpRequest,- scriptedReplies,- scriptedRequestTokens,- scriptedRequestUrls,- serverErrorReply,- unauthorizedReply,- userMeReply,-} from '@app/features/auth/state/__fixtures__/AccountSwitchHarness';-import {instanceDiscoveryFixture} from '@app/features/platform/state/__fixtures__/RuntimeBootstrapFixture';-import type {MessageDescriptor} from '@lingui/core';-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';--vi.mock('@lingui/core/macro', () => ({msg: (descriptor: MessageDescriptor) => descriptor}));--vi.mock('@app/features/gateway/transport/GatewaySessionPool', () => ({- default: {- foregroundConnection: {- startSession: () => undefined,- logout: () => 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}}));--vi.mock('@app/features/user/state/UserSettings', () => ({- default: {handleAccountTransition: () => undefined},-}));--installHarnessBootstrap();--const {AccountAccess, AccountAccessDecision, AccountAccessPhase} = await import(- '@app/features/auth/state/AccountAccess'-);-const {default: accountStorage} = await import('@app/features/auth/state/AccountStorage');-const {default: RuntimeConfig} = await import('@app/features/app/state/RuntimeConfig');-const {default: SessionManager} = await import('@app/features/platform/state/AuthSession');-const {resetAppStorage} = await import('@app/features/platform/state/PersistentStorage');--const ACCOUNT = {userId: '300', token: 'token-c'};-const ACCOUNT_KEY = `${HARNESS_API_ENDPOINT}::${ACCOUNT.userId}`;-const FOREIGN_ACCOUNT_KEY = `https://foreign.test/api::${ACCOUNT.userId}`;-const RUNTIME = RuntimeConfig.getSnapshot();--function createAccess() {- return new AccountAccess();-}--beforeEach(async () => {- vi.stubGlobal('XMLHttpRequest', ScriptedXMLHttpRequest);- vi.stubGlobal(- 'fetch',- vi.fn(- async () =>- new Response(JSON.stringify(instanceDiscoveryFixture(HARNESS_API_ENDPOINT)), {- status: 200,- headers: {'content-type': 'application/json'},- }),- ),- );- await SessionManager.reset();- await resetAppStorage([]);- await accountStorage.deleteAccount(ACCOUNT_KEY);- await SessionManager.initialize();- scriptedReplies.push(userMeReply(ACCOUNT.userId));- await SessionManager.login({token: ACCOUNT.token, userId: ACCOUNT.userId, runtimeSnapshot: RUNTIME});- resetScriptedTransport();-});--afterEach(() => {- vi.unstubAllGlobals();- vi.useRealTimers();- resetScriptedTransport();-});--describe('AccountAccess phase machine', () => {- test('a healthy account is allowed and may start a gateway', async () => {- const access = createAccess();- scriptedReplies.push(userMeReply(ACCOUNT.userId));- await expect(access.ensureAccountChecked(ACCOUNT_KEY)).resolves.toBe(AccountAccessDecision.ALLOWED);- expect(access.getPhase(ACCOUNT_KEY)).toBe(AccountAccessPhase.ALLOWED);- expect(scriptedRequestTokens).toEqual([ACCOUNT.token]);- expect(scriptedRequestUrls[0]?.startsWith(HARNESS_API_ENDPOINT)).toBe(true);- expect(scriptedRequestUrls[0]?.endsWith('/users/@me')).toBe(true);- });-- test('a required action blocks the gateway and is reported as action required', async () => {- const access = createAccess();- scriptedReplies.push(userMeReply(ACCOUNT.userId, ['REQUIRE_VERIFIED_EMAIL']));- await expect(access.ensureAccountChecked(ACCOUNT_KEY)).resolves.toBe(AccountAccessDecision.ACTION_REQUIRED);- expect(access.getPhase(ACCOUNT_KEY)).toBe(AccountAccessPhase.ACTION_REQUIRED);- });-- test('a server that omits required_actions entirely is treated as allowed', async () => {- const access = createAccess();- scriptedReplies.push({status: 200, body: {id: ACCOUNT.userId, username: 'legacy'}});- await expect(access.ensureAccountChecked(ACCOUNT_KEY)).resolves.toBe(AccountAccessDecision.ALLOWED);- expect(access.getPhase(ACCOUNT_KEY)).toBe(AccountAccessPhase.ALLOWED);- });-- test('an unauthorized response invalidates the account and forgets the record', async () => {- const access = createAccess();- scriptedReplies.push(unauthorizedReply());- await expect(access.ensureAccountChecked(ACCOUNT_KEY)).resolves.toBe(AccountAccessDecision.INVALID);- expect(access.getPhase(ACCOUNT_KEY)).toBe(AccountAccessPhase.UNKNOWN);- expect(SessionManager.accounts[0]?.isValid).toBe(false);- });-- test('a mismatched user id invalidates the stored account identity', async () => {- const access = createAccess();- scriptedReplies.push(userMeReply('999'));- await expect(access.ensureAccountChecked(ACCOUNT_KEY)).resolves.toBe(AccountAccessDecision.INVALID);- expect(access.getPhase(ACCOUNT_KEY)).toBe(AccountAccessPhase.UNKNOWN);- expect(SessionManager.accounts[0]?.isValid).toBe(false);- });-- test('an unreachable instance backs off exponentially instead of retrying immediately', async () => {- vi.useFakeTimers();- const access = createAccess();- scriptedReplies.push(serverErrorReply(), serverErrorReply(), serverErrorReply());-- await access.ensureAccountChecked(ACCOUNT_KEY, {force: true, resetFailures: false});- expect(access.getRetryEligibleAt(ACCOUNT_KEY) - Date.now()).toBe(10_000);-- await access.ensureAccountChecked(ACCOUNT_KEY, {force: true, resetFailures: false});- expect(access.getRetryEligibleAt(ACCOUNT_KEY) - Date.now()).toBe(20_000);-- await access.ensureAccountChecked(ACCOUNT_KEY, {force: true, resetFailures: false});- expect(access.getRetryEligibleAt(ACCOUNT_KEY) - Date.now()).toBe(40_000);-- expect(access.getPhase(ACCOUNT_KEY)).toBe(AccountAccessPhase.UNAVAILABLE);- });-- test('a repeated check reuses the decision recorded for the same token', async () => {- const access = createAccess();- scriptedReplies.push(userMeReply(ACCOUNT.userId));- await access.ensureAccountChecked(ACCOUNT_KEY);- await access.ensureAccountChecked(ACCOUNT_KEY);- expect(scriptedRequestTokens).toHaveLength(1);- });-- test('concurrent checks for one token share a single request', async () => {- const access = createAccess();- scriptedReplies.push(userMeReply(ACCOUNT.userId));- const [first, second] = await Promise.all([- access.ensureAccountChecked(ACCOUNT_KEY),- access.ensureAccountChecked(ACCOUNT_KEY),- ]);- expect(first).toBe(AccountAccessDecision.ALLOWED);- expect(second).toBe(AccountAccessDecision.ALLOWED);- expect(scriptedRequestTokens).toHaveLength(1);- });-- test('a re-login under a new token discards the previous decision', async () => {- const access = createAccess();- scriptedReplies.push(userMeReply(ACCOUNT.userId));- await access.ensureAccountChecked(ACCOUNT_KEY);- await SessionManager.login({token: 'rotated-token', userId: ACCOUNT.userId, runtimeSnapshot: RUNTIME});- scriptedReplies.push(userMeReply(ACCOUNT.userId));- await access.ensureAccountChecked(ACCOUNT_KEY);- expect(scriptedRequestTokens).toEqual([ACCOUNT.token, 'rotated-token']);- });-- test('a gateway ready signal clears a recovered restriction', async () => {- const access = createAccess();- scriptedReplies.push(userMeReply(ACCOUNT.userId, ['REQUIRE_VERIFIED_EMAIL']));- await access.ensureAccountChecked(ACCOUNT_KEY);- scriptedReplies.push(userMeReply(ACCOUNT.userId));- await access.ensureAccountChecked(ACCOUNT_KEY, {force: true});- expect(access.getPhase(ACCOUNT_KEY)).toBe(AccountAccessPhase.GATEWAY_STARTING);- access.markGatewayReady(ACCOUNT_KEY);- expect(access.getPhase(ACCOUNT_KEY)).toBe(AccountAccessPhase.ALLOWED);- });-- test('a gateway ready signal clears an unavailable record, so unavailable is not terminal', async () => {- const access = createAccess();- scriptedReplies.push(userMeReply(ACCOUNT.userId));- await access.ensureAccountChecked(ACCOUNT_KEY);- access.markGatewayUnavailable(ACCOUNT_KEY, new Error('gateway ready timed out'));- expect(access.getPhase(ACCOUNT_KEY)).toBe(AccountAccessPhase.UNAVAILABLE);- access.markGatewayReady(ACCOUNT_KEY);- expect(access.getPhase(ACCOUNT_KEY)).toBe(AccountAccessPhase.ALLOWED);- expect(access.getUnavailabilityCause(ACCOUNT_KEY).name).toBe('AccountAccessUnrecordedUnavailabilityError');- expect(access.getCheckedUser(ACCOUNT_KEY)).not.toBeNull();- });-- test('a gateway ready timeout never downgrades a restricted account out of its required action', async () => {- const access = createAccess();- scriptedReplies.push(userMeReply(ACCOUNT.userId, ['REQUIRE_VERIFIED_EMAIL']));- await access.ensureAccountChecked(ACCOUNT_KEY);- const retryEligibleAt = access.getRetryEligibleAt(ACCOUNT_KEY);-- access.markGatewayUnavailable(ACCOUNT_KEY, new Error('gateway ready timed out'));-- expect(access.getPhase(ACCOUNT_KEY)).toBe(AccountAccessPhase.ACTION_REQUIRED);- expect(access.getRetryEligibleAt(ACCOUNT_KEY)).toBe(retryEligibleAt);-- access.markGatewayReady(ACCOUNT_KEY);-- expect(access.getPhase(ACCOUNT_KEY)).toBe(AccountAccessPhase.ACTION_REQUIRED);- await expect(access.ensureAccountChecked(ACCOUNT_KEY)).resolves.toBe(AccountAccessDecision.ACTION_REQUIRED);- });-- test('a gateway ready signal on a never-checked account forces a real check instead of pinning it allowed', async () => {- const access = createAccess();- access.markGatewayUnavailable(ACCOUNT_KEY, new Error('gateway ready timed out'));- access.markGatewayReady(ACCOUNT_KEY);- expect(access.getPhase(ACCOUNT_KEY)).toBe(AccountAccessPhase.UNKNOWN);- expect(access.getCheckedUser(ACCOUNT_KEY)).toBeNull();-- scriptedReplies.push(userMeReply(ACCOUNT.userId));- await expect(access.ensureAccountChecked(ACCOUNT_KEY)).resolves.toBe(AccountAccessDecision.ALLOWED);- expect(scriptedRequestTokens).toEqual([ACCOUNT.token]);- expect(access.getCheckedUser(ACCOUNT_KEY)).not.toBeNull();- });-- test('an unavailable decision is reused only until its own retry deadline passes', async () => {- vi.useFakeTimers();- const access = createAccess();- access.markGatewayUnavailable(ACCOUNT_KEY, new Error('gateway refused the session'));- expect(access.getPhase(ACCOUNT_KEY)).toBe(AccountAccessPhase.UNAVAILABLE);-- await expect(access.ensureAccountChecked(ACCOUNT_KEY)).resolves.toBe(AccountAccessDecision.UNAVAILABLE);- expect(scriptedRequestTokens).toHaveLength(0);-- vi.advanceTimersByTime(access.getRetryEligibleAt(ACCOUNT_KEY) - Date.now() + 1);- scriptedReplies.push(userMeReply(ACCOUNT.userId));-- await expect(access.ensureAccountChecked(ACCOUNT_KEY)).resolves.toBe(AccountAccessDecision.ALLOWED);- expect(scriptedRequestTokens).toEqual([ACCOUNT.token]);- expect(access.getPhase(ACCOUNT_KEY)).toBe(AccountAccessPhase.ALLOWED);- });-- test('a stale unavailable decision keeps its backoff instead of restarting it', async () => {- vi.useFakeTimers();- const access = createAccess();- access.markGatewayUnavailable(ACCOUNT_KEY, new Error('gateway refused the session'));- const firstRetryAt = access.getRetryEligibleAt(ACCOUNT_KEY);-- vi.advanceTimersByTime(firstRetryAt - Date.now() + 1);- scriptedReplies.push(serverErrorReply());- await expect(access.ensureAccountChecked(ACCOUNT_KEY)).resolves.toBe(AccountAccessDecision.UNAVAILABLE);-- expect(access.getRetryEligibleAt(ACCOUNT_KEY) - Date.now()).toBeGreaterThan(firstRetryAt - Date.now());- });-- test('forgetting an account drops its record', async () => {- const access = createAccess();- scriptedReplies.push(userMeReply(ACCOUNT.userId));- await access.ensureAccountChecked(ACCOUNT_KEY);- access.forgetAccount(ACCOUNT_KEY);- expect(access.getPhase(ACCOUNT_KEY)).toBe(AccountAccessPhase.UNKNOWN);- });-});--describe('AccountAccess account isolation', () => {- test('a key that names no stored account is never answered by the active account', async () => {- const access = createAccess();- scriptedReplies.push(userMeReply(ACCOUNT.userId));-- await expect(access.ensureAccountChecked(FOREIGN_ACCOUNT_KEY)).resolves.toBe(AccountAccessDecision.INVALID);-- expect(scriptedRequestTokens).toEqual([]);- expect(access.getPhase(FOREIGN_ACCOUNT_KEY)).toBe(AccountAccessPhase.UNKNOWN);- expect(access.getCheckedUser(FOREIGN_ACCOUNT_KEY)).toBeNull();- });-- test('a key that names no stored account is refused even after the active account was checked', async () => {- const access = createAccess();- scriptedReplies.push(userMeReply(ACCOUNT.userId));- await access.ensureAccountChecked(ACCOUNT_KEY);- resetScriptedTransport();-- await expect(access.ensureAccountChecked(FOREIGN_ACCOUNT_KEY)).resolves.toBe(AccountAccessDecision.INVALID);-- expect(scriptedRequestTokens).toEqual([]);- expect(access.getCheckedUser(FOREIGN_ACCOUNT_KEY)).toBeNull();- });-- test('a reply that lands after the token rotated is discarded instead of recorded', async () => {- let releaseReply = (): void => undefined;- let markRequestSent = (): void => undefined;- const requestSent = new Promise<void>((resolve) => {- markRequestSent = resolve;- });- class DeferredXMLHttpRequest extends ScriptedXMLHttpRequest {- override send(): void {- releaseReply = () => super.send();- markRequestSent();- }- }- vi.stubGlobal('XMLHttpRequest', DeferredXMLHttpRequest);- const access = createAccess();- scriptedReplies.push(userMeReply(ACCOUNT.userId));-- const pending = access.ensureAccountChecked(ACCOUNT_KEY);- await requestSent;- await SessionManager.login({token: 'rotated-token', userId: ACCOUNT.userId, runtimeSnapshot: RUNTIME});- releaseReply();-- await expect(pending).resolves.toBe(AccountAccessDecision.UNAVAILABLE);- expect(access.getCheckedUser(ACCOUNT_KEY)).toBeNull();- expect(access.getPhase(ACCOUNT_KEY)).not.toBe(AccountAccessPhase.ALLOWED);-- vi.stubGlobal('XMLHttpRequest', ScriptedXMLHttpRequest);- scriptedReplies.push(userMeReply(ACCOUNT.userId));- await access.ensureAccountChecked(ACCOUNT_KEY);-- expect(scriptedRequestTokens).toEqual([ACCOUNT.token, 'rotated-token']);- expect(access.getCheckedUser(ACCOUNT_KEY)).not.toBeNull();- });-- test('a user checked under a superseded token is withheld until the rotated token is checked', async () => {- const access = createAccess();- scriptedReplies.push(userMeReply(ACCOUNT.userId));- await access.ensureAccountChecked(ACCOUNT_KEY);- expect(access.getCheckedUser(ACCOUNT_KEY)).not.toBeNull();-- await SessionManager.login({token: 'rotated-token', userId: ACCOUNT.userId, runtimeSnapshot: RUNTIME});-- expect(access.getCheckedUser(ACCOUNT_KEY)).toBeNull();-- scriptedReplies.push(userMeReply(ACCOUNT.userId));- await access.ensureAccountChecked(ACCOUNT_KEY);-- expect(access.getCheckedUser(ACCOUNT_KEY)).not.toBeNull();- });-});--describe('AccountAccess re-checks', () => {- test('a restricted account is never re-fetched on a timer, only when something asks again', async () => {- vi.useFakeTimers();- const access = createAccess();- scriptedReplies.push(userMeReply(ACCOUNT.userId, ['REQUIRE_VERIFIED_EMAIL']));- await access.ensureAccountChecked(ACCOUNT_KEY);- expect(scriptedRequestTokens).toHaveLength(1);-- await vi.advanceTimersByTimeAsync(120_000);-- expect(scriptedRequestTokens).toHaveLength(1);- });-});diff --git a/fluxer_app/src/features/auth/state/AccountRestriction.test.ts b/fluxer_app/src/features/auth/state/AccountRestriction.test.tsdeleted file mode 100644index 06f85b29b..000000000--- a/fluxer_app/src/features/auth/state/AccountRestriction.test.ts+++ /dev/null@@ -1,98 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {parseAccountRestriction} from '@app/features/auth/state/AccountRestriction';-import {HttpError} from '@app/features/platform/types/EndpointError';-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';-import type {EnforcementNotice, NetworkBlock} from '@fluxer/schema/src/domains/auth/EnforcementNoticeSchemas';-import {describe, expect, test} from 'vitest';--const notice: EnforcementNotice = {- decision_id: '1234567890123456789',- kind: 'suspension',- permanent: false,- issued_at: '2026-10-01T10:00:00.000Z',- ends_at: '2026-10-08T10:00:00.000Z',- deletion_at: null,- summary: 'We suspended your account until Oct 8, 2026, 10:00 AM UTC.',- effects: ["You can't sign in or use Fluxer until then. Your account, messages and communities are kept."],- rule: {title: 'Spam', url: 'https://fluxer.com/guidelines#6-spam-and-service-abuse'},- facts: ['We found that your account sent unwanted messages in bulk.'],- statement: null,- how_we_decided: ['We reviewed this after a report.'],- appeal: {email: '[email protected]', deadline: 'Nov 30, 2026', account_has_email: true},- redress: [],-};--const block: NetworkBlock = {- ip_address: '203.0.113.7',- appeal_email: '[email protected]',- appeals_supported: true,- ban_kind: 'permanent',- expires_at: null,- reason: null,- product_name: 'Fluxer',-};--function forbidden(body: unknown, status = 403): HttpError {- return new HttpError({method: 'POST', path: '/auth/login', status, body});-}--describe('parseAccountRestriction', () => {- test.each([APIErrorCodes.ACCOUNT_SUSPENDED_TEMPORARILY, APIErrorCodes.ACCOUNT_SUSPENDED_PERMANENTLY])(- '%s with a notice is a notice',- (code) => {- expect(parseAccountRestriction(forbidden({code, message: 'Suspended.', notice}))).toEqual({- type: 'notice',- notice,- });- },- );-- test('a permanent suspension without a notice is not a restriction screen', () => {- const error = forbidden({code: APIErrorCodes.ACCOUNT_SUSPENDED_PERMANENTLY, message: 'Suspended.', notice: null});- expect(parseAccountRestriction(error)).toBeNull();- });-- test('a malformed notice is ignored', () => {- const error = forbidden({- code: APIErrorCodes.ACCOUNT_SUSPENDED_TEMPORARILY,- message: 'Suspended.',- notice: {...notice, summary: 7},- });- expect(parseAccountRestriction(error)).toBeNull();- });-- test.each([- [APIErrorCodes.GLOBAL_IP_BANNED, block],- [- APIErrorCodes.GLOBAL_IP_TEMPORARILY_BANNED,- {- ...block,- ban_kind: 'temporary_24h' as const,- expires_at: '2026-10-15T10:00:00.000Z',- reason: {title: 'Spam', url: null},- },- ],- ])('%s is a network block', (code, data) => {- expect(parseAccountRestriction(forbidden({code, message: 'Blocked.', ...data}))).toEqual({- type: 'network_blocked',- block: data,- });- });-- test('a self-hosted network block keeps its null contact', () => {- const data = {...block, appeal_email: null, appeals_supported: false};- expect(- parseAccountRestriction(forbidden({code: APIErrorCodes.GLOBAL_IP_BANNED, message: 'Blocked.', ...data})),- ).toEqual({type: 'network_blocked', block: data});- });-- test('other errors are not restrictions', () => {- expect(parseAccountRestriction(forbidden({code: APIErrorCodes.MISSING_ACCESS, message: 'No.'}))).toBeNull();- expect(- parseAccountRestriction(forbidden({code: APIErrorCodes.GLOBAL_IP_BANNED, message: 'Blocked.', ...block}, 400)),- ).toBeNull();- expect(parseAccountRestriction(new Error('offline'))).toBeNull();- expect(parseAccountRestriction(forbidden('Forbidden'))).toBeNull();- });-});diff --git a/fluxer_app/src/features/auth/state/AccountStorage.test.ts b/fluxer_app/src/features/auth/state/AccountStorage.test.tsdeleted file mode 100644index b3a11ec59..000000000--- a/fluxer_app/src/features/auth/state/AccountStorage.test.ts+++ /dev/null@@ -1,585 +0,0 @@-// @vitest-environment happy-dom-// SPDX-License-Identifier: AGPL-3.0-or-later--import type {RuntimeConfigSnapshot} from '@app/features/app/state/RuntimeConfig';-import {- FIXTURE_CURRENT_INSTANCE_SNAPSHOT,- FIXTURE_NOW,- FLUXER_ACCOUNTS_DB_VERSION,- FLUXER_ACCOUNTS_STORE_NAME,- openGoldenAccountsDatabase,-} from '@app/features/auth/state/__fixtures__/AccountRecordFixtures';-import type {- AccountRekeyContext,- AccountRekeyOutcome,- KeyedStoredAccount,- StoredAccount,-} from '@app/features/auth/state/AccountStorageContract';-import {installRuntimeBootstrap} from '@app/features/platform/state/__fixtures__/RuntimeBootstrapFixture';-import {beforeEach, describe, expect, test, vi} from 'vitest';--const CURRENT_INSTANCE_KEY = 'https://fluxer.app/api';-const MOVED_API_ENDPOINT = 'https://api.fluxer.app';-const FOREIGN_API_ENDPOINT = 'https://self.hosted.example/api';--const DEPLOYED_SWAP_CAPTURED: Record<string, string> = {- token: 'raw.token',- userId: '4242',- runtimeConfig: '{"apiEndpoint":"https://fluxer.app/api"}',- AccountManager: '{"accounts":[]}',- mobxTheme: '{"theme":"dark"}',- 'mobx-persist:Keybind': '{"binds":[]}',- persistedSidebar: '{"width":300}',- 'fluxer:ui:sidebar-width': '300',- 'fluxer:auth:active-account-key': 'https://fluxer.app/api::1',-};--const DEPLOYED_SWAP_IGNORED: Record<string, string> = {- Theme: '{"type":"dark","__mps__":{"version":1}}',- Drafts: '{"channels":{},"__mps__":{"version":1}}',- VoiceSettings: '{"inputVolume":100,"__mps__":{"version":1}}',- ClientInstallationId: '0123456789abcdef0123456789abcdef',- theme: 'dark',- MobXTheme: '{}',-};--type AccountStorageModule = typeof import('@app/features/auth/state/AccountStorage');--function instanceSnapshot(apiEndpoint: string): RuntimeConfigSnapshot {- return {...FIXTURE_CURRENT_INSTANCE_SNAPSHOT, apiEndpoint, apiPublicEndpoint: apiEndpoint};-}--function storedRecord(userId: string, overrides: Partial<StoredAccount> = {}): StoredAccount {- return {- userId,- token: `token.${userId}`,- userData: {username: `user${userId}`, discriminator: '0001'},- presenceIntent: null,- localStorageData: {},- managedStorageData: {},- lastActive: FIXTURE_NOW - 1_000,- instance: FIXTURE_CURRENT_INSTANCE_SNAPSHOT,- ...overrides,- };-}--function rekeyContext(- userId: string,- instance: RuntimeConfigSnapshot = FIXTURE_CURRENT_INSTANCE_SNAPSHOT,-): AccountRekeyContext {- return {target: {userId, token: `token.${userId}`, instance}, now: FIXTURE_NOW};-}--async function loadAccountStorage(): Promise<AccountStorageModule> {- return import('@app/features/auth/state/AccountStorage');-}--async function seed(records: ReadonlyArray<StoredAccount>): Promise<void> {- const database = await openGoldenAccountsDatabase(window.indexedDB);- await new Promise<void>((resolve, reject) => {- const transaction = database.transaction([FLUXER_ACCOUNTS_STORE_NAME], 'readwrite');- const store = transaction.objectStore(FLUXER_ACCOUNTS_STORE_NAME);- for (const record of records) {- store.put(record);- }- transaction.oncomplete = () => resolve();- transaction.onerror = () => reject(transaction.error ?? new Error('IndexedDB seed failed'));- });- database.close();-}--async function readRaw(userId: string): Promise<StoredAccount | null> {- const database = await openGoldenAccountsDatabase(window.indexedDB);- const record = await new Promise<StoredAccount | null>((resolve, reject) => {- const request = database- .transaction([FLUXER_ACCOUNTS_STORE_NAME], 'readonly')- .objectStore(FLUXER_ACCOUNTS_STORE_NAME)- .get(userId);- request.onsuccess = () => resolve((request.result as StoredAccount | undefined) ?? null);- request.onerror = () => reject(request.error ?? new Error('IndexedDB read failed'));- });- database.close();- return record;-}--function readRawLocalStorage(): Record<string, string> {- const entries: Record<string, string> = {};- for (let i = 0; i < window.localStorage.length; i++) {- const key = window.localStorage.key(i);- if (key == null) {- continue;- }- entries[key] = window.localStorage.getItem(key) ?? '';- }- return entries;-}--function seedRawLocalStorage(entries: Record<string, string>): void {- for (const [key, value] of Object.entries(entries)) {- window.localStorage.setItem(key, value);- }-}--function installIndexedDB(factory: IDBFactory | undefined): void {- Object.defineProperty(window, 'indexedDB', {value: factory, configurable: true, writable: true});-}--beforeEach(() => {- vi.resetModules();- installIndexedDB(new IDBFactory());- installRuntimeBootstrap();- window.localStorage.clear();-});--describe('reading a deployed v2 database', () => {- test('three v2 records stay at version 2 and read back with a derived storageKey', async () => {- await seed([storedRecord('1'), storedRecord('2'), storedRecord('3')]);- const {default: accountStorage} = await loadAccountStorage();- await accountStorage.init();-- const {records, source} = await accountStorage.getAllAccounts();-- expect(source).toBe('idb');- expect(records.map((record) => record.storageKey).sort()).toEqual([- `${CURRENT_INSTANCE_KEY}::1`,- `${CURRENT_INSTANCE_KEY}::2`,- `${CURRENT_INSTANCE_KEY}::3`,- ]);- expect(records.map((record) => record.token).sort()).toEqual(['token.1', 'token.2', 'token.3']);-- const database = await openGoldenAccountsDatabase(window.indexedDB);- expect(database.version).toBe(FLUXER_ACCOUNTS_DB_VERSION);- expect(database.transaction([FLUXER_ACCOUNTS_STORE_NAME]).objectStore(FLUXER_ACCOUNTS_STORE_NAME).keyPath).toBe(- 'userId',- );- database.close();- });-- test('a record with no instance is listed and left unkeyed rather than healed by a read', async () => {- await seed([storedRecord('1'), storedRecord('2', {instance: undefined})]);- const {default: accountStorage} = await loadAccountStorage();-- const {records} = await accountStorage.getAllAccounts();-- expect(records).toHaveLength(2);- const orphan = records.find((record) => record.userId === '2');- expect(orphan?.token).toBe('token.2');- expect(orphan?.storageKey).toBeUndefined();- expect(await readRaw('2')).not.toBeNull();- });-- test('a persisted storageKey survives a read even when the record instance became unkeyable', async () => {- await seed([- storedRecord('1', {- storageKey: `${CURRENT_INSTANCE_KEY}::1`,- instance: instanceSnapshot('https://operator:[email protected]/api?tenant=1'),- }),- ]);- const {default: accountStorage} = await loadAccountStorage();-- const {records} = await accountStorage.getAllAccounts();-- expect(records[0].storageKey).toBe(`${CURRENT_INSTANCE_KEY}::1`);- });-- test('a persisted storageKey naming another user is unavailable rather than redirected', async () => {- await seed([storedRecord('1', {storageKey: `${CURRENT_INSTANCE_KEY}::9`})]);- const {default: accountStorage} = await loadAccountStorage();-- const inventory = await accountStorage.getAccountInventory();-- expect(inventory.readyEntries).toHaveLength(0);- expect(inventory.unavailableRecords).toHaveLength(1);- });-- test('getAllAccounts falls back to an empty list when IndexedDB is unavailable', async () => {- installIndexedDB(undefined);- const {default: accountStorage} = await loadAccountStorage();-- await expect(accountStorage.init()).resolves.toBeUndefined();- await expect(accountStorage.getAllAccounts()).resolves.toEqual({records: [], source: 'idb'});- });-});--describe('unusable IndexedDB', () => {- function installThrowingIndexedDB(): void {- const factory = new IDBFactory();- factory.open = () => {- throw new DOMException('denied', 'SecurityError');- };- installIndexedDB(factory);- }-- test('an open that throws serves accounts from the fallback and keeps them across a reload', async () => {- installThrowingIndexedDB();- const first = await loadAccountStorage();-- await first.default.stashAccountData('1', 'token.1', undefined, FIXTURE_CURRENT_INSTANCE_SNAPSHOT);- expect((await first.default.restoreAccountData(`${CURRENT_INSTANCE_KEY}::1`))?.token).toBe('token.1');-- vi.resetModules();- installThrowingIndexedDB();- const second = await loadAccountStorage();- const {records} = await second.default.getAllAccounts();-- expect(records.map((record) => [record.userId, record.storageKey])).toEqual([['1', `${CURRENT_INSTANCE_KEY}::1`]]);-- await second.default.deleteAccount(`${CURRENT_INSTANCE_KEY}::1`);- expect((await second.default.getAllAccounts()).records).toHaveLength(0);- });-- test('the fallback still refuses a cross-instance overwrite', async () => {- installThrowingIndexedDB();- const {default: accountStorage, CrossInstanceAccountCollisionError} = await loadAccountStorage();- await accountStorage.upsertAccount(storedRecord('1'), FIXTURE_CURRENT_INSTANCE_SNAPSHOT);-- await expect(- accountStorage.upsertAccount(- storedRecord('1', {instance: instanceSnapshot(FOREIGN_API_ENDPOINT)}),- FIXTURE_CURRENT_INSTANCE_SNAPSHOT,- ),- ).rejects.toBeInstanceOf(CrossInstanceAccountCollisionError);- });-- test('accounts stay in memory when localStorage refuses the fallback copy', async () => {- installThrowingIndexedDB();- vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {- throw new DOMException('full', 'QuotaExceededError');- });- const {default: accountStorage} = await loadAccountStorage();-- await accountStorage.upsertAccount(storedRecord('1'), FIXTURE_CURRENT_INSTANCE_SNAPSHOT);-- expect((await accountStorage.getAllAccounts()).records).toHaveLength(1);- vi.restoreAllMocks();- });-- test('a transaction failure on an open database is still refused', async () => {- await seed([storedRecord('1')]);- const {default: accountStorage} = await loadAccountStorage();- const {BrowserAccountStorageUnavailableError} = await import('@app/features/auth/state/AccountStorageContract');- await accountStorage.init();- vi.spyOn(IDBDatabase.prototype, 'transaction').mockImplementation(() => {- throw new DOMException('broken', 'UnknownError');- });-- await expect(accountStorage.getAllAccounts()).rejects.toBeInstanceOf(BrowserAccountStorageUnavailableError);- vi.restoreAllMocks();- });-});--describe('stashAccountData', () => {- test('isValid: false survives a stash of the same token', async () => {- await seed([storedRecord('1', {isValid: false})]);- const {default: accountStorage} = await loadAccountStorage();-- await accountStorage.stashAccountData('1', 'token.1', undefined, FIXTURE_CURRENT_INSTANCE_SNAPSHOT);-- const stored = await readRaw('1');- expect(stored?.isValid).toBe(false);- expect(stored?.userData?.username).toBe('user1');- });-- test('a stash with a new token after invalidation persists the account as valid', async () => {- await seed([storedRecord('1', {isValid: false})]);- const {default: accountStorage} = await loadAccountStorage();-- await accountStorage.stashAccountData('1', 'token.relogin', undefined, FIXTURE_CURRENT_INSTANCE_SNAPSHOT);-- const stored = await readRaw('1');- expect(stored?.isValid).toBe(true);- expect(stored?.token).toBe('token.relogin');- expect((await accountStorage.restoreAccountData(`${CURRENT_INSTANCE_KEY}::1`))?.isValid).toBe(true);- });-- test('a stash rewrites the storage key under the instance it was handed', async () => {- await seed([storedRecord('1', {storageKey: `${CURRENT_INSTANCE_KEY}::1`})]);- const {default: accountStorage} = await loadAccountStorage();-- await accountStorage.stashAccountData('1', 'token.1', undefined, instanceSnapshot(MOVED_API_ENDPOINT));-- expect((await readRaw('1'))?.storageKey).toBe(`${MOVED_API_ENDPOINT}::1`);- });-- test('a stash with no instance keeps the storage key the record already had', async () => {- await seed([storedRecord('1', {storageKey: `${CURRENT_INSTANCE_KEY}::1`, instance: undefined})]);- const {default: accountStorage} = await loadAccountStorage();-- await accountStorage.stashAccountData('1', 'token.1');-- expect((await readRaw('1'))?.storageKey).toBe(`${CURRENT_INSTANCE_KEY}::1`);- });-- test('community and services survive the stored-instance clone', async () => {- const {default: accountStorage} = await loadAccountStorage();- const instance: RuntimeConfigSnapshot = {- ...FIXTURE_CURRENT_INSTANCE_SNAPSHOT,- community: {- single_community: true,- single_community_guild_id: '77',- direct_messages_disabled: true,- guild_create_access: true,- },- services: {gif_enabled: false, youtube_enabled: true, bluesky_enabled: true},- };-- await accountStorage.stashAccountData('1', 'token.1', undefined, instance);-- const stored = await readRaw('1');- expect(stored?.instance?.community).toEqual(instance.community);- expect(stored?.instance?.services).toEqual(instance.services);- });-});--describe('migrateAccountStorageKeys', () => {- test('heals an instance-less record once, persists it, and rewrites nothing on a second run', async () => {- await seed([storedRecord('1'), storedRecord('2', {instance: undefined})]);- const {default: accountStorage} = await loadAccountStorage();-- const first: AccountRekeyOutcome = await accountStorage.migrateAccountStorageKeys(rekeyContext('2'));-- expect(first.status).toBe('complete');- expect(first.source).toBe('idb');- expect(first.written).toBe(1);- expect(first.qualifiedRecords.map((record: KeyedStoredAccount) => record.storageKey).sort()).toEqual([- `${CURRENT_INSTANCE_KEY}::1`,- `${CURRENT_INSTANCE_KEY}::2`,- ]);-- const healed = await readRaw('2');- expect(healed?.storageKey).toBe(`${CURRENT_INSTANCE_KEY}::2`);- expect(healed?.instance?.apiEndpoint).toBe(CURRENT_INSTANCE_KEY);- expect(healed?.token).toBe('token.2');-- const second = await accountStorage.migrateAccountStorageKeys(rekeyContext('2'));- expect(second.status).toBe('complete');- expect(second.written).toBe(0);- });-- test('a record keyed from its own foreign instance is kept and never re-keyed onto the current one', async () => {- await seed([storedRecord('1', {instance: instanceSnapshot(FOREIGN_API_ENDPOINT)})]);- const {default: accountStorage} = await loadAccountStorage();-- const outcome = await accountStorage.migrateAccountStorageKeys(rekeyContext('1'));-- expect(outcome.written).toBe(0);- expect(outcome.qualifiedRecords[0].storageKey).toBe(`${FOREIGN_API_ENDPOINT}::1`);- });-- test('a secondary account with only a legacy instance on the current instance is healed at once', async () => {- const legacyInstance = {apiEndpoint: CURRENT_INSTANCE_KEY} as RuntimeConfigSnapshot;- await seed([storedRecord('1'), storedRecord('2', {instance: legacyInstance})]);- const {default: accountStorage} = await loadAccountStorage();-- const first = await accountStorage.migrateAccountStorageKeys(rekeyContext('1'));-- expect(first.status).toBe('complete');- expect(first.deferredRecords).toHaveLength(0);- expect(first.written).toBe(1);- const healed = await readRaw('2');- expect(healed?.storageKey).toBe(`${CURRENT_INSTANCE_KEY}::2`);- expect(healed?.instance).toEqual(FIXTURE_CURRENT_INSTANCE_SNAPSHOT);- expect(healed?.token).toBe('token.2');- expect((await accountStorage.getAccountInventory()).runtimeRecoveryCandidates).toHaveLength(0);-- const second = await accountStorage.migrateAccountStorageKeys(rekeyContext('1'));- expect(second.status).toBe('complete');- expect(second.written).toBe(0);- });-- test('a secondary account with a legacy instance elsewhere stays deferred with its record intact', async () => {- const legacyInstance = {apiEndpoint: FOREIGN_API_ENDPOINT} as RuntimeConfigSnapshot;- await seed([storedRecord('1'), storedRecord('2', {instance: legacyInstance})]);- const {default: accountStorage} = await loadAccountStorage();-- const outcome = await accountStorage.migrateAccountStorageKeys(rekeyContext('1'));-- expect(outcome.status).toBe('deferred');- expect(outcome.deferredRecords).toHaveLength(1);- expect(outcome.written).toBe(0);- expect((await readRaw('2'))?.instance).toEqual(legacyInstance);- });-- test('an active credential for another account does not heal the record', async () => {- await seed([storedRecord('2', {instance: undefined})]);- const {default: accountStorage} = await loadAccountStorage();-- const outcome = await accountStorage.migrateAccountStorageKeys(rekeyContext('1'));-- expect(outcome.status).toBe('deferred');- expect(outcome.written).toBe(0);- expect(outcome.qualifiedRecords).toHaveLength(0);- expect(outcome.deferredRecords).toHaveLength(1);- expect(await readRaw('2')).not.toBeNull();- expect((await accountStorage.getAllAccounts()).records).toHaveLength(1);- });-- test('an unkeyable current instance heals nothing', async () => {- await seed([storedRecord('2', {instance: undefined})]);- const {default: accountStorage} = await loadAccountStorage();-- const outcome = await accountStorage.migrateAccountStorageKeys(- rekeyContext('2', instanceSnapshot('https://operator:[email protected]/api?tenant=1')),- );-- expect(outcome.written).toBe(0);- expect((await readRaw('2'))?.storageKey).toBeUndefined();- });-- test('an unavailable IndexedDB migrates the fallback copy instead of failing', async () => {- installIndexedDB(undefined);- const {default: accountStorage} = await loadAccountStorage();- await accountStorage.importAccounts([storedRecord('1', {instance: undefined})]);-- const outcome = await accountStorage.migrateAccountStorageKeys(rekeyContext('1'));-- expect(outcome.written).toBe(1);- expect((await accountStorage.getAllAccounts()).records[0]?.storageKey).toBe(`${CURRENT_INSTANCE_KEY}::1`);- });-});--describe('upsertAccount', () => {- test('a cross-instance userId collision is refused and leaves the stored record intact', async () => {- await seed([storedRecord('1')]);- const {default: accountStorage, CrossInstanceAccountCollisionError} = await loadAccountStorage();-- await expect(- accountStorage.upsertAccount(- storedRecord('1', {token: 'token.foreign', instance: instanceSnapshot(FOREIGN_API_ENDPOINT)}),- FIXTURE_CURRENT_INSTANCE_SNAPSHOT,- ),- ).rejects.toBeInstanceOf(CrossInstanceAccountCollisionError);-- const stored = await readRaw('1');- expect(stored?.token).toBe('token.1');- expect(stored?.instance?.apiEndpoint).toBe(CURRENT_INSTANCE_KEY);- });-- test('an instance that moved its own apiEndpoint re-keys the record instead of being refused', async () => {- await seed([storedRecord('1', {storageKey: `${CURRENT_INSTANCE_KEY}::1`})]);- const {default: accountStorage} = await loadAccountStorage();- const moved = instanceSnapshot(MOVED_API_ENDPOINT);-- await accountStorage.upsertAccount(storedRecord('1', {instance: moved}), moved);-- expect((await readRaw('1'))?.storageKey).toBe(`${MOVED_API_ENDPOINT}::1`);- });-- test('a first write for an unknown userId on a foreign instance is accepted', async () => {- const {default: accountStorage} = await loadAccountStorage();- const foreign = instanceSnapshot(FOREIGN_API_ENDPOINT);-- await accountStorage.upsertAccount(storedRecord('1', {instance: foreign}), FIXTURE_CURRENT_INSTANCE_SNAPSHOT);-- expect((await readRaw('1'))?.storageKey).toBe(`${FOREIGN_API_ENDPOINT}::1`);- });-});--describe('deleteAccount', () => {- test('an instance-qualified key evicts the row it names', async () => {- await seed([storedRecord('1')]);- const {default: accountStorage} = await loadAccountStorage();-- await accountStorage.deleteAccount(`${CURRENT_INSTANCE_KEY}::1`);-- expect(await readRaw('1')).toBeNull();- });-- test('a key qualified by another instance evicts nothing', async () => {- await seed([storedRecord('1')]);- const {default: accountStorage} = await loadAccountStorage();-- await accountStorage.deleteAccount(`${FOREIGN_API_ENDPOINT}::1`);-- expect((await readRaw('1'))?.token).toBe('token.1');- });-- test('a key qualified by another instance leaves the account readable', async () => {- await seed([storedRecord('1')]);- const {default: accountStorage} = await loadAccountStorage();-- await accountStorage.deleteAccount(`${FOREIGN_API_ENDPOINT}::1`);-- const {records} = await accountStorage.getAllAccounts();- expect(records.map((record) => record.storageKey)).toEqual([`${CURRENT_INSTANCE_KEY}::1`]);- });-});--describe('restoreAccountData', () => {- test('a restore rewrites no raw localStorage key', async () => {- await seed([- storedRecord('1', {- localStorageData: {token: 'stashed.token', 'fluxer:ui:sidebar-width': '999', 'fluxer:ui:only-in-record': 'x'},- managedStorageData: {token: 'stashed.token', 'fluxer:ui:sidebar-width': '999', 'fluxer:ui:only-in-record': 'x'},- }),- ]);- const {default: accountStorage} = await loadAccountStorage();- seedRawLocalStorage({...DEPLOYED_SWAP_CAPTURED, ...DEPLOYED_SWAP_IGNORED});- const before = readRawLocalStorage();-- await accountStorage.restoreAccountData('1');-- expect(readRawLocalStorage()).toEqual(before);- expect(window.localStorage.getItem('fluxer:ui:only-in-record')).toBeNull();- });-- test('a restore returns the stored snapshot instead of applying it', async () => {- const snapshot = {'fluxer:ui:sidebar-width': '999'};- await seed([storedRecord('1', {localStorageData: snapshot, managedStorageData: snapshot})]);- const {default: accountStorage} = await loadAccountStorage();- seedRawLocalStorage({'fluxer:ui:sidebar-width': '300'});-- const restored = await accountStorage.restoreAccountData('1');-- expect(restored?.token).toBe('token.1');- expect(restored?.localStorageData).toEqual(snapshot);- expect(window.localStorage.getItem('fluxer:ui:sidebar-width')).toBe('300');- });-- test('a restore still refreshes lastActive', async () => {- await seed([storedRecord('1')]);- const {default: accountStorage} = await loadAccountStorage();- const before = (await readRaw('1'))?.lastActive ?? 0;-- await accountStorage.restoreAccountData('1');-- expect((await readRaw('1'))?.lastActive ?? 0).toBeGreaterThan(before);- });-- test('a foreign-instance record restores and touches no raw localStorage', async () => {- await seed([storedRecord('1', {instance: instanceSnapshot(FOREIGN_API_ENDPOINT)})]);- const {default: accountStorage} = await loadAccountStorage();- seedRawLocalStorage(DEPLOYED_SWAP_CAPTURED);- const before = readRawLocalStorage();-- expect((await accountStorage.restoreAccountData('1'))?.token).toBe('token.1');-- expect(readRawLocalStorage()).toEqual(before);- });-});--describe('the per-account storage snapshot', () => {- test('a stash captures nothing, because no build here reads the snapshot back', async () => {- const {default: accountStorage} = await loadAccountStorage();- seedRawLocalStorage({...DEPLOYED_SWAP_CAPTURED, ...DEPLOYED_SWAP_IGNORED});-- await accountStorage.stashAccountData('1', 'token.1', undefined, FIXTURE_CURRENT_INSTANCE_SNAPSHOT);-- const stored = await readRaw('1');- expect(stored?.managedStorageData).toEqual({});- expect(stored?.localStorageData).toEqual({});- });-- test('a snapshot a deployed build already wrote is preserved rather than destroyed', async () => {- await seed([- storedRecord('1', {token: 'token.0', localStorageData: DEPLOYED_SWAP_CAPTURED, managedStorageData: undefined}),- ]);- const {default: accountStorage} = await loadAccountStorage();-- await accountStorage.stashAccountData('1', 'token.1', undefined, FIXTURE_CURRENT_INSTANCE_SNAPSHOT);-- const stored = await readRaw('1');- expect(stored?.managedStorageData).toEqual(DEPLOYED_SWAP_CAPTURED);- expect(stored?.token).toBe('token.1');- });-});diff --git a/fluxer_app/src/features/auth/state/OfficialAliasStoredAccount.test.ts b/fluxer_app/src/features/auth/state/OfficialAliasStoredAccount.test.tsdeleted file mode 100644index 86309b6f4..000000000--- a/fluxer_app/src/features/auth/state/OfficialAliasStoredAccount.test.ts+++ /dev/null@@ -1,268 +0,0 @@-// @vitest-environment happy-dom-// SPDX-License-Identifier: AGPL-3.0-or-later--import {- resolveDiscoveryApiEndpoint,- runtimeInstanceKey,- storedInstanceKey,-} from '@app/features/app/state/InstanceSnapshotStore';-import type {RuntimeConfigSnapshot} from '@app/features/app/state/RuntimeConfig';-import {- FIXTURE_CURRENT_INSTANCE_SNAPSHOT,- FIXTURE_NOW,- FLUXER_ACCOUNTS_STORE_NAME,- openGoldenAccountsDatabase,-} from '@app/features/auth/state/__fixtures__/AccountRecordFixtures';-import {planAccountRekey} from '@app/features/auth/state/AccountStorageContract';-import {classifyStoredAccount} from '@app/features/auth/state/StoredAccountInventoryPolicy';-import {AuthSessionStoredAccountResolver} from '@app/features/platform/state/auth_session/AuthSessionStoredAccountResolver';-import {beforeEach, describe, expect, test, vi} from 'vitest';--type AccountStorageModule = typeof import('@app/features/auth/state/AccountStorage');--const MIGRATED_ORIGIN = 'https://canary.fluxer.com';-const LEGACY_WEB_ORIGIN = 'https://web.canary.fluxer.app';-const OFFICIAL_INSTANCE_KEY = `${LEGACY_WEB_ORIGIN}/api`;-const USER_ID = '100000000000000002';-const OTHER_USER_ID = '100000000000000003';--function instanceSnapshot(origin: string): RuntimeConfigSnapshot {- return {- ...FIXTURE_CURRENT_INSTANCE_SNAPSHOT,- apiEndpoint: `${origin}/api`,- apiPublicEndpoint: 'https://api.canary.fluxer.app',- webAppEndpoint: origin,- };-}--function oldClientRecord(origin: string, userId: string): Record<string, unknown> {- return {- userId,- token: `token.${userId}`,- userData: {username: `user${userId}`, discriminator: '0001'},- presenceIntent: null,- localStorageData: {},- managedStorageData: {},- lastActive: FIXTURE_NOW - 1_000,- instance: {- apiEndpoint: `${origin}/api`,- webAppEndpoint: origin,- gatewayEndpoint: 'wss://gateway.fluxer.app',- },- isValid: true,- };-}--function newClientRecord(origin: string, userId: string): Record<string, unknown> {- return {- ...oldClientRecord(origin, userId),- instance: instanceSnapshot(origin),- storageKey: `${origin}/api::${userId}`,- };-}--function classifyBrowserRecord(value: unknown) {- return classifyStoredAccount({value, authoritativeStorageKey: null, source: 'idb'});-}--function setDocumentUrl(url: string): void {- (window as unknown as {happyDOM: {setURL(url: string): void}}).happyDOM.setURL(url);-}--async function seed(records: ReadonlyArray<Record<string, unknown>>): Promise<void> {- const database = await openGoldenAccountsDatabase(window.indexedDB);- await new Promise<void>((resolve, reject) => {- const transaction = database.transaction([FLUXER_ACCOUNTS_STORE_NAME], 'readwrite');- const store = transaction.objectStore(FLUXER_ACCOUNTS_STORE_NAME);- for (const record of records) {- store.put(record);- }- transaction.oncomplete = () => resolve();- transaction.onerror = () => reject(transaction.error ?? new Error('IndexedDB seed failed'));- });- database.close();-}--async function readAllRaw(): Promise<Array<Record<string, unknown>>> {- const database = await openGoldenAccountsDatabase(window.indexedDB);- const records = await new Promise<Array<Record<string, unknown>>>((resolve, reject) => {- const request = database- .transaction([FLUXER_ACCOUNTS_STORE_NAME], 'readonly')- .objectStore(FLUXER_ACCOUNTS_STORE_NAME)- .getAll();- request.onsuccess = () => resolve(request.result as Array<Record<string, unknown>>);- request.onerror = () => reject(request.error ?? new Error('IndexedDB read failed'));- });- database.close();- return records;-}--function createResolver(accountStorage: AccountStorageModule['default'], inputs: Array<string>) {- return new AuthSessionStoredAccountResolver({- accountStorage,- resolveRuntimeEndpoint: async (input) => {- inputs.push(input);- const snapshot = instanceSnapshot(new URL(resolveDiscoveryApiEndpoint(input)).origin);- const instanceKey = runtimeInstanceKey(snapshot);- if (instanceKey === null) {- throw new Error(`No instance key for ${input}`);- }- return {snapshot, instanceKey, productName: 'Fluxer'};- },- });-}--beforeEach(() => {- vi.resetModules();- Object.defineProperty(window, 'indexedDB', {value: new IDBFactory(), configurable: true, writable: true});- window.localStorage.clear();- setDocumentUrl('fluxer-app://app/channels/@me');-});--describe('classifying an account stored on the migrated official domain', () => {- test('an old client record is a recovery candidate for the official instance', () => {- const classified = classifyBrowserRecord(oldClientRecord(MIGRATED_ORIGIN, USER_ID));-- expect(classified.kind).toBe('runtime-recovery');- expect(classified).toMatchObject({- instanceKey: OFFICIAL_INSTANCE_KEY,- storageKey: `${OFFICIAL_INSTANCE_KEY}::${USER_ID}`,- });- });-- test('the same user harvested from either official origin is one account', () => {- const migrated = classifyBrowserRecord(oldClientRecord(MIGRATED_ORIGIN, USER_ID));- const legacy = classifyBrowserRecord(oldClientRecord(LEGACY_WEB_ORIGIN, USER_ID));-- expect(migrated).toMatchObject({kind: 'runtime-recovery', storageKey: `${OFFICIAL_INSTANCE_KEY}::${USER_ID}`});- expect(legacy).toMatchObject({kind: 'runtime-recovery', storageKey: `${OFFICIAL_INSTANCE_KEY}::${USER_ID}`});- });-- test('a record the new web client keyed on the migrated domain is recovered under the official instance', () => {- const classified = classifyBrowserRecord(newClientRecord(MIGRATED_ORIGIN, USER_ID));-- expect(classified).toMatchObject({- kind: 'runtime-recovery',- instanceKey: OFFICIAL_INSTANCE_KEY,- storageKey: `${OFFICIAL_INSTANCE_KEY}::${USER_ID}`,- });- });-- test('a record keyed on the official instance stays ready', () => {- const classified = classifyBrowserRecord(newClientRecord(LEGACY_WEB_ORIGIN, USER_ID));-- expect(classified).toMatchObject({kind: 'ready', record: {storageKey: `${OFFICIAL_INSTANCE_KEY}::${USER_ID}`}});- });-- test('a desktop row whose authoritative key names the migrated domain is not silently rekeyed', () => {- const classified = classifyStoredAccount({- value: newClientRecord(MIGRATED_ORIGIN, USER_ID),- authoritativeStorageKey: `${MIGRATED_ORIGIN}/api::${USER_ID}`,- source: 'desktop',- });-- expect(classified.kind).toBe('unavailable');- });-- test('an account on another instance keeps its own identity', () => {- const classified = classifyBrowserRecord(oldClientRecord('https://chat.example.test', USER_ID));-- expect(classified).toMatchObject({- kind: 'runtime-recovery',- instanceKey: 'https://chat.example.test/api',- storageKey: `https://chat.example.test/api::${USER_ID}`,- });- });-});--describe('a web user on the migrated official domain', () => {- test.each(['https://fluxer.com', MIGRATED_ORIGIN])(- 'on %s the stored account keeps the same-origin instance it was stored with',- (origin) => {- setDocumentUrl(`${origin}/channels/@me`);-- expect(storedInstanceKey(`${origin}/api`)).toBe(`${origin}/api`);- expect(classifyBrowserRecord(oldClientRecord(origin, USER_ID))).toMatchObject({- kind: 'runtime-recovery',- instanceKey: `${origin}/api`,- storageKey: `${origin}/api::${USER_ID}`,- });- expect(classifyBrowserRecord(newClientRecord(origin, USER_ID))).toMatchObject({- kind: 'ready',- record: {storageKey: `${origin}/api::${USER_ID}`, instance: {apiEndpoint: `${origin}/api`}},- });- },- );-});--describe('restoring the session of an account harvested from the migrated official domain', () => {- test.each([- ['an old client record', oldClientRecord],- ['a record keyed by the new web client', newClientRecord],- ])('%s signs in on the official instance and is stored once', async (_label, buildRecord) => {- await seed([buildRecord(MIGRATED_ORIGIN, USER_ID)]);- const {default: accountStorage} = await import('@app/features/auth/state/AccountStorage');- await accountStorage.init();- const inputs: Array<string> = [];-- const restoration = await createResolver(accountStorage, inputs).resolveActiveRestoration({- storageKey: null,- userId: USER_ID,- token: `token.${USER_ID}`,- });-- expect(inputs).toEqual([OFFICIAL_INSTANCE_KEY]);- expect(restoration.kind).toBe('resolved');- expect(restoration).toMatchObject({- accountKey: `${OFFICIAL_INSTANCE_KEY}::${USER_ID}`,- record: {- userId: USER_ID,- token: `token.${USER_ID}`,- storageKey: `${OFFICIAL_INSTANCE_KEY}::${USER_ID}`,- instance: {apiEndpoint: OFFICIAL_INSTANCE_KEY, webAppEndpoint: LEGACY_WEB_ORIGIN},- },- });- const stored = await readAllRaw();- expect(stored).toHaveLength(1);- expect(stored[0]).toMatchObject({- userId: USER_ID,- storageKey: `${OFFICIAL_INSTANCE_KEY}::${USER_ID}`,- instance: {apiEndpoint: OFFICIAL_INSTANCE_KEY, webAppEndpoint: LEGACY_WEB_ORIGIN},- });- const inventory = await accountStorage.getAccountInventory();- expect(inventory.readyEntries.map((entry) => entry.record.storageKey)).toEqual([- `${OFFICIAL_INSTANCE_KEY}::${USER_ID}`,- ]);- expect(inventory.runtimeRecoveryCandidates).toHaveLength(0);- expect(inventory.unavailableRecords).toHaveLength(0);- });-- test('every harvested account is keyed once under the official instance', async () => {- await seed([oldClientRecord(MIGRATED_ORIGIN, USER_ID), oldClientRecord(MIGRATED_ORIGIN, OTHER_USER_ID)]);- const {default: accountStorage} = await import('@app/features/auth/state/AccountStorage');- await accountStorage.init();- const restoration = await createResolver(accountStorage, []).resolveActiveRestoration({- storageKey: null,- userId: USER_ID,- token: `token.${USER_ID}`,- });- if (restoration.kind !== 'resolved') {- throw new Error(`Expected a resolved restoration, got ${restoration.kind}`);- }-- const {records} = await accountStorage.getAllAccounts();- const plan = planAccountRekey(records, {- target: {userId: USER_ID, token: `token.${USER_ID}`, instance: restoration.record.instance},- now: FIXTURE_NOW,- });-- expect(records.map((record) => record.storageKey).sort()).toEqual([- `${OFFICIAL_INSTANCE_KEY}::${USER_ID}`,- `${OFFICIAL_INSTANCE_KEY}::${OTHER_USER_ID}`,- ]);- expect(plan.qualifiedRecords.map((record) => record.storageKey)).toContain(`${OFFICIAL_INSTANCE_KEY}::${USER_ID}`);- expect(- [...plan.qualifiedRecords, ...plan.deferredRecords].filter((record) => record.userId === USER_ID),- ).toHaveLength(1);- });-});diff --git a/fluxer_app/src/features/auth/state/__fixtures__/AccountRecordFixtures.ts b/fluxer_app/src/features/auth/state/__fixtures__/AccountRecordFixtures.tsdeleted file mode 100644index ed9c39b53..000000000--- a/fluxer_app/src/features/auth/state/__fixtures__/AccountRecordFixtures.ts+++ /dev/null@@ -1,171 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import type {RuntimeConfigSnapshot} from '@app/features/app/state/RuntimeConfig';-import type {StoredAccount} from '@app/features/auth/state/AccountStorageContract';-import {BOOTSTRAP_APP_PUBLIC} from '@app/features/platform/state/__fixtures__/RuntimeBootstrapFixture';--const FIXTURE_CURRENT_API_ENDPOINT = 'https://fluxer.app/api';-export const FIXTURE_CURRENT_INSTANCE_KEY = 'https://fluxer.app/api';-const FIXTURE_PATHED_API_ENDPOINT = 'HTTPS://Self.Hosted.Example/fluxer/api/';-const FIXTURE_PATHED_INSTANCE_KEY = 'https://self.hosted.example/fluxer/api';-const FIXTURE_UNKEYABLE_API_ENDPOINT = 'https://operator:[email protected]/api?tenant=1';-export const FIXTURE_NOW = 1_755_000_000_000;--function runtimeConfigSnapshotFixture(apiEndpoint: string): RuntimeConfigSnapshot {- return {- apiEndpoint,- apiPublicEndpoint: apiEndpoint,- gatewayEndpoint: 'wss://gateway.fluxer.app',- mediaEndpoint: 'https://media.fluxer.app',- staticCdnEndpoint: 'https://cdn.fluxer.app',- marketingEndpoint: 'https://fluxer.app',- adminEndpoint: 'https://admin.fluxer.app',- inviteEndpoint: 'https://flux.gg',- giftEndpoint: 'https://flux.gift',- webAppEndpoint: 'https://fluxer.app',- uploadRelayEndpoint: 'https://upload.fluxer.app',- gifProvider: 'tenor',- gifProviderDisplayName: 'Tenor',- gifAttributionRequired: true,- apiCodeVersion: 9,- 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,- },- sso: null,- 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},- publicPushVapidKey: null,- limits: {version: 1, traitDefinitions: [], rules: []},- appPublic: BOOTSTRAP_APP_PUBLIC,- agePolicy: null,- domainMigration: null,- };-}--export const FIXTURE_CURRENT_INSTANCE_SNAPSHOT: RuntimeConfigSnapshot =- runtimeConfigSnapshotFixture(FIXTURE_CURRENT_API_ENDPOINT);--function storedAccountFixture(overrides: Partial<StoredAccount> & Pick<StoredAccount, 'userId'>): StoredAccount {- return {- token: `token.${overrides.userId}`,- userData: {- username: `user${overrides.userId}`,- discriminator: '0001',- globalName: null,- email: null,- avatar: null,- },- presenceIntent: null,- localStorageData: {},- managedStorageData: {},- lastActive: FIXTURE_NOW - 1_000,- instance: runtimeConfigSnapshotFixture(FIXTURE_CURRENT_API_ENDPOINT),- ...overrides,- };-}--export const BULK_RECORD_CLASS_SIZE = 1025;--interface AccountRecordClass {- readonly id: string;- readonly description: string;- readonly records: ReadonlyArray<StoredAccount>;- readonly expectedStorageKeys: ReadonlyArray<string>;-}--const noInstanceRecord = storedAccountFixture({userId: '100000000000000001', instance: undefined});--const sameInstanceRecords = [- storedAccountFixture({userId: '100000000000000002', lastActive: FIXTURE_NOW - 5_000}),- storedAccountFixture({userId: '100000000000000003', lastActive: FIXTURE_NOW - 2_000}),-];--const pathedInstanceRecord = storedAccountFixture({- userId: '100000000000000004',- instance: runtimeConfigSnapshotFixture(FIXTURE_PATHED_API_ENDPOINT),-});--const corruptInstanceRecord = storedAccountFixture({- userId: '100000000000000005',- instance: runtimeConfigSnapshotFixture(FIXTURE_UNKEYABLE_API_ENDPOINT),-});--const nullTokenRecord = storedAccountFixture({userId: '100000000000000006', token: null, isValid: false});--const bulkRecords = Array.from({length: BULK_RECORD_CLASS_SIZE}, (_unused, index) =>- storedAccountFixture({- userId: `2${String(index).padStart(17, '0')}`,- lastActive: FIXTURE_NOW - index,- }),-);--export const FLUXER_ACCOUNTS_V2_RECORD_CLASSES: ReadonlyArray<AccountRecordClass> = [- {- id: 'no-instance',- description: 'Unqualified active record recovered from exact credentials',- records: [noInstanceRecord],- expectedStorageKeys: [`${FIXTURE_CURRENT_INSTANCE_KEY}::${noInstanceRecord.userId}`],- },- {- id: 'same-instance-pair',- description: 'Class A, the overwhelming majority: two records on the current instance',- records: sameInstanceRecords,- expectedStorageKeys: sameInstanceRecords.map((record) => `${FIXTURE_CURRENT_INSTANCE_KEY}::${record.userId}`),- },- {- id: 'api-endpoint-with-path',- description: 'Class C: self-hosted instance whose apiEndpoint has a path, with case and trailing slash normalised',- records: [pathedInstanceRecord],- expectedStorageKeys: [`${FIXTURE_PATHED_INSTANCE_KEY}::${pathedInstanceRecord.userId}`],- },- {- id: 'corrupt-instance',- description: 'Unkeyable active record recovered from exact credentials',- records: [corruptInstanceRecord],- expectedStorageKeys: [`${FIXTURE_CURRENT_INSTANCE_KEY}::${corruptInstanceRecord.userId}`],- },- {- id: 'null-token',- description: 'Class A with a null token is listed, flagged invalid and never silently deleted',- records: [nullTokenRecord],- expectedStorageKeys: [`${FIXTURE_CURRENT_INSTANCE_KEY}::${nullTokenRecord.userId}`],- },- {- id: 'bulk-1025',- description: 'Class A at scale: 1025 records, above every 1024-sized batch boundary in the train',- records: bulkRecords,- expectedStorageKeys: bulkRecords.map((record) => `${FIXTURE_CURRENT_INSTANCE_KEY}::${record.userId}`),- },-];--const FLUXER_ACCOUNTS_DB_NAME = 'FluxerAccounts';-export const FLUXER_ACCOUNTS_DB_VERSION = 2;-export const FLUXER_ACCOUNTS_STORE_NAME = 'accounts';-export const FLUXER_ACCOUNTS_KEY_PATH = 'userId';-export const FLUXER_ACCOUNTS_INDEX_NAME = 'lastActive';--export function openGoldenAccountsDatabase(factory: IDBFactory): Promise<IDBDatabase> {- return new Promise<IDBDatabase>((resolve, reject) => {- const request = factory.open(FLUXER_ACCOUNTS_DB_NAME, FLUXER_ACCOUNTS_DB_VERSION);- request.onupgradeneeded = () => {- request.result- .createObjectStore(FLUXER_ACCOUNTS_STORE_NAME, {keyPath: FLUXER_ACCOUNTS_KEY_PATH})- .createIndex(FLUXER_ACCOUNTS_INDEX_NAME, FLUXER_ACCOUNTS_INDEX_NAME);- };- request.onsuccess = () => resolve(request.result);- request.onerror = () => reject(request.error ?? new Error('IndexedDB open failed'));- });-}