Skip to content

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

TypeScript fluxerfluxerapp

test(app): drop mock-heavy account switch and auth screen tests

Hampus941294611b54
diff --git a/fluxer_app/src/features/auth/flow/AccountRestrictionScreen.test.tsx b/fluxer_app/src/features/auth/flow/AccountRestrictionScreen.test.tsx
deleted file mode 100644
index 2cedc5f63..000000000
--- a/fluxer_app/src/features/auth/flow/AccountRestrictionScreen.test.tsx
+++ /dev/null
@@ -1,441 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {readFileSync} from 'node:fs';
-import {join} from 'node:path';
-import type {AccountRestriction} from '@app/features/auth/state/AccountRestriction';
-import type {EnforcementNotice, NetworkBlock} from '@fluxer/schema/src/domains/auth/EnforcementNoticeSchemas';
-import type {ReactNode} from 'react';
-import {act} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
-
-const mocks = vi.hoisted(() => ({
- restriction: null as unknown,
- pathname: '/reset',
- clearAccountRestriction: vi.fn(),
- replaceWith: vi.fn(),
- pushModal: vi.fn(),
- popModal: vi.fn(),
- locale: 'en-US',
- mobile: false,
-}));
-
-function interpolate(message: string, values: Record<string, unknown> = {}): string {
- return message.replace(/\{(\w+)\}/g, (_match, name: string) => String(values[name]));
-}
-
-vi.mock('@lingui/core/macro', () => ({msg: (descriptor: unknown) => descriptor}));
-vi.mock('@lingui/react/macro', () => ({
- Trans: ({children}: {children: ReactNode}) => children,
- useLingui: () => ({
- i18n: {
- get locale() {
- return mocks.locale;
- },
- _: (descriptor: {message: string}, values?: Record<string, unknown>) => interpolate(descriptor.message, values),
- },
- }),
-}));
-vi.mock('mobx-react-lite', () => ({observer: (component: unknown) => component}));
-vi.mock('@app/features/auth/flow/AccountRestrictionScreen.module.css', () => ({
- default: new Proxy({}, {get: (_target, name) => String(name)}),
-}));
-vi.mock('@app/features/app/components/shared/ExternalLink', () => ({
- ExternalLink: ({href, children}: {href: string; children: ReactNode}) => (
- <a href={href} data-external-link="true" data-flx="auth.flow.account-restriction-screen-test.external-link">
- {children}
- </a>
- ),
-}));
-vi.mock('@app/features/ui/button/Button', () => ({
- Button: ({onClick, children}: {onClick: () => void; children: ReactNode}) => (
- <button type="button" onClick={onClick} data-flx="auth.flow.account-restriction-screen-test.button">
- {children}
- </button>
- ),
-}));
-vi.mock('@app/features/i18n/utils/CommonMessageDescriptors', () => ({
- BACK_TO_SIGN_IN_DESCRIPTOR: {message: 'Back to sign-in'},
- TRY_AGAIN_DESCRIPTOR: {message: 'Try again'},
-}));
-vi.mock('@app/features/auth/flow/useAuthPresentation', () => ({useAuthPresentation: () => {}}));
-vi.mock('@app/features/ui/utils/MobileExperience', () => ({isMobileExperienceEnabled: () => mocks.mobile}));
-vi.mock('@app/features/auth/state/AuthLayoutContext', () => ({AuthCardVariant: {STANDARD: 'standard'}}));
-vi.mock('@app/features/auth/state/Authentication', () => ({
- default: {
- get accountRestriction() {
- return mocks.restriction;
- },
- },
-}));
-vi.mock('@app/features/auth/commands/AuthenticationCommands', () => ({
- clearAccountRestriction: mocks.clearAccountRestriction,
-}));
-vi.mock('@app/features/navigation/utils/RouterUtils', () => ({replaceWith: mocks.replaceWith}));
-vi.mock('@app/features/platform/components/router/RouterReact', () => ({
- useLocation: () => ({pathname: mocks.pathname}),
-}));
-vi.mock('@app/features/app/components/dialogs/Modal', () => ({
- Root: ({className, children}: {className: string; children: ReactNode}) => (
- <div role="dialog" className={className} data-flx="auth.flow.account-restriction-screen-test.root">
- {children}
- </div>
- ),
- Header: ({title}: {title: string}) => <h1 data-flx="auth.flow.account-restriction-screen-test.header">{title}</h1>,
- Content: ({children, dir}: {children: ReactNode; dir?: string}) => (
- <div data-modal-content="true" dir={dir} data-flx="auth.flow.account-restriction-screen-test.content">
- {children}
- </div>
- ),
- ContentLayout: ({children}: {children: ReactNode}) => children,
- Footer: ({children}: {children: ReactNode}) => children,
-}));
-vi.mock('@app/features/ui/commands/ModalCommands', () => ({
- push: mocks.pushModal,
- pop: mocks.popModal,
- modal: (render: () => ReactNode) => render,
-}));
-
-const {AccountRestrictionGate, AccountRestrictionScreen} = await import(
- '@app/features/auth/flow/AccountRestrictionScreen'
-);
-const {showNetworkBlockedModal} = await import('@app/features/auth/components/NetworkBlockedHandler');
-
-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 anywhere until then. Your account, messages and communities are kept."],
- rule: {title: 'Spam and service abuse', url: 'https://fluxer.com/guidelines#6-spam-and-service-abuse'},
- facts: [
- 'We found that your account sent unwanted messages in bulk.',
- '3 messages in #general of Example, between Oct 1, 2026, 9:00 AM UTC and Oct 1, 2026, 9:05 AM UTC.',
- ],
- statement: 'Please read the rules.',
- how_we_decided: ['We reviewed this after a report.', 'A person on our team reviewed this and made the decision.'],
- appeal: {email: '[email protected]', deadline: 'Nov 30, 2026', account_has_email: true},
- redress: [
- "If you're in the EU, you can also refer this decision to a certified out-of-court dispute settlement body. The European Commission keeps a [list of these bodies](https://digital-strategy.ec.europa.eu/en/policies/dsa-out-court-dispute-settlement).",
- ],
-};
-
-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',
-};
-
-let root: Root | null = null;
-let container: HTMLElement | null = null;
-
-function render(node: ReactNode): HTMLElement {
- const target = container;
- if (target == null) {
- throw new Error('The test container is not mounted');
- }
- act(() => root?.render(node));
- return target;
-}
-
-function renderScreen(restriction: AccountRestriction, handlers = {onBackToSignIn: vi.fn(), onTryAgain: vi.fn()}) {
- const element = render(
- <AccountRestrictionScreen
- restriction={restriction}
- {...handlers}
- data-flx="auth.flow.account-restriction-screen-test.account-restriction-screen"
- />,
- );
- return {element, ...handlers};
-}
-
-function text(element: HTMLElement): string {
- return (element.textContent ?? '').replace(/\s+/g, ' ');
-}
-
-function paragraphs(element: HTMLElement): Array<string> {
- return [...element.querySelectorAll('p')].map((paragraph) => text(paragraph));
-}
-
-function clickButton(element: HTMLElement, label: string): void {
- const button = [...element.querySelectorAll('button')].find((candidate) => candidate.textContent === label);
- if (button == null) {
- throw new Error(`No ${label} button`);
- }
- act(() => button.click());
-}
-
-beforeEach(() => {
- (globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
- container = document.createElement('div');
- document.body.appendChild(container);
- root = createRoot(container);
- mocks.restriction = null;
- mocks.pathname = '/reset';
- mocks.locale = 'en-US';
- mocks.mobile = false;
- vi.clearAllMocks();
-});
-
-afterEach(() => {
- act(() => root?.unmount());
- container?.remove();
- root = null;
- container = null;
-});
-
-describe('account notice', () => {
- test('shows every section of the notice with a real mailto link', () => {
- const {element} = renderScreen({type: 'notice', notice});
- const content = text(element);
- expect(element.querySelector('h1')?.textContent).toBe('Account suspended');
- expect([...element.querySelectorAll('h2')].map((heading) => heading.textContent)).toEqual([
- 'What happened',
- 'Why',
- 'How we decided',
- 'How to appeal',
- ]);
- for (const line of [notice.summary, ...notice.effects, ...notice.facts, ...notice.how_we_decided]) {
- expect(content).toContain(line);
- }
- expect(content).toContain('The European Commission keeps a list of these bodies.');
- expect(content).not.toContain('](');
- expect(content).toContain('Rule: Spam and service abuse');
- expect(content).toContain('Note from our team: Please read the rules.');
- expect(content).toContain(
- 'If you think we got this wrong, email [email protected] by Nov 30, 2026. Write from the email address on your account if you can, and include the decision ID. Appeals are free, and a person reviews each one.',
- );
- expect(content).toContain('Decision ID: 1234567890123456789');
- const links = [...element.querySelectorAll('a[data-external-link]')].map((link) => link.getAttribute('href'));
- expect(links).toEqual([
- 'https://fluxer.com/guidelines#6-spam-and-service-abuse',
- 'mailto:[email protected]',
- 'https://digital-strategy.ec.europa.eu/en/policies/dsa-out-court-dispute-settlement',
- ]);
- });
-
- test('the primary button sits in the footer, and mobile gets its own card', () => {
- const {element} = renderScreen({type: 'notice', notice});
- const root = element.firstElementChild;
- expect(root?.lastElementChild?.className).toBe('footer');
- expect(root?.lastElementChild?.querySelector('button')?.textContent).toBe('Back to sign-in');
- expect(root?.className.split(' ')).not.toContain('surface');
- mocks.mobile = true;
- renderScreen({type: 'notice', notice});
- expect(container?.firstElementChild?.className.split(' ')).toContain('surface');
- });
-
- test('follows the direction of the locale', () => {
- mocks.locale = 'ar';
- const {element} = renderScreen({type: 'notice', notice});
- expect(element.firstElementChild?.getAttribute('dir')).toBe('rtl');
- });
-
- test('titles follow the kind and permanence', () => {
- renderScreen({type: 'notice', notice: {...notice, permanent: true, ends_at: null}});
- expect(container?.querySelector('h1')?.textContent).toBe('Account banned');
- renderScreen({type: 'notice', notice: {...notice, kind: 'closure', deletion_at: '2027-01-01T00:00:00.000Z'}});
- expect(container?.querySelector('h1')?.textContent).toBe('Account closed');
- });
-
- test('the root is selectable and the decision ID has no copy control', () => {
- const {element} = renderScreen({type: 'notice', notice});
- expect(element.firstElementChild?.className.split(' ')).toContain('selectable');
- expect([...element.querySelectorAll('button')].map((button) => button.textContent)).toEqual(['Back to sign-in']);
- expect(text(element)).not.toMatch(/cop(y|ied)/i);
- const css = readFileSync(join(process.cwd(), 'src/features/auth/flow/AccountRestrictionScreen.module.css'), 'utf8');
- expect(css).toMatch(
- /\.selectable,\s*\.selectable \* \{\s*user-select: text !important;\s*-webkit-user-select: text !important;/,
- );
- });
-
- test('an account with no email asks for the decision ID and username', () => {
- const {element} = renderScreen({
- type: 'notice',
- notice: {...notice, appeal: {email: '[email protected]', deadline: 'Nov 30, 2026', account_has_email: false}},
- });
- expect(text(element)).toContain(
- 'If you think we got this wrong, email [email protected] by Nov 30, 2026. Include the decision ID and your username. Appeals are free, and a person reviews each one.',
- );
- });
-
- test('a deadline that ends in a period does not double the full stop', () => {
- const {element} = renderScreen({
- type: 'notice',
- notice: {...notice, appeal: {email: '[email protected]', deadline: '14. pro 2026.', account_has_email: true}},
- });
- expect(text(element)).toContain('by 14. pro 2026. Write from');
- });
-
- test('a restriction from before decisions has no deadline and no decision ID', () => {
- const {element} = renderScreen({
- type: 'notice',
- notice: {
- ...notice,
- decision_id: null,
- rule: null,
- statement: null,
- how_we_decided: [],
- facts: ["We don't have more detail on record for this decision."],
- appeal: {email: '[email protected]', deadline: null, account_has_email: true},
- },
- });
- const content = text(element);
- expect(content).toContain('If you think we got this wrong, email [email protected] and include your username.');
- expect(content).not.toContain('Decision ID');
- expect(content).not.toContain('Rule:');
- expect(content).not.toContain('How we decided');
- });
-
- test('self-hosted notices have no appeal section and no email link', () => {
- const {element} = renderScreen({
- type: 'notice',
- notice: {...notice, rule: {title: 'Spam and service abuse', url: null}, appeal: null, redress: []},
- });
- const content = text(element);
- expect(content).not.toContain('How to appeal');
- expect(content).not.toContain('@');
- expect(content).toContain('Rule: Spam and service abuse');
- expect(element.querySelectorAll('a')).toHaveLength(0);
- });
-
- test('back to sign-in calls its handler', () => {
- const {element, onBackToSignIn} = renderScreen({type: 'notice', notice});
- clickButton(element, 'Back to sign-in');
- expect(onBackToSignIn).toHaveBeenCalledOnce();
- });
-});
-
-describe('network blocked', () => {
- test('without a reason shows the plain lead, the shared-network paragraph and the contact', () => {
- const {element} = renderScreen({type: 'network_blocked', block});
- expect(element.querySelector('h1')?.textContent).toBe('Network blocked');
- expect(paragraphs(element)).toEqual([
- 'Fluxer blocked access from this network.',
- 'If you share this network, for example at school, at work, on public Wi-Fi, through your mobile carrier or a VPN, this block may have nothing to do with you. The quickest fix is to switch networks, for example to mobile data instead of Wi-Fi, or to turn your VPN on or off.',
- 'If you think this block is a mistake, email [email protected] and include your IP address, 203.0.113.7.',
- ]);
- expect(text(element)).not.toMatch(/sign in/i);
- expect(element.querySelector('a')?.getAttribute('href')).toBe('mailto:[email protected]');
- expect(element.firstElementChild?.className.split(' ')).toContain('selectable');
- });
-
- test('with a reason leads with the rule', () => {
- const {element} = renderScreen({
- type: 'network_blocked',
- block: {...block, appeal_email: '[email protected]', reason: {title: 'Spam and service abuse', url: null}},
- });
- expect(paragraphs(element).slice(0, 2)).toEqual([
- 'Fluxer blocked access from this network because of activity that broke its rules.',
- 'Rule: Spam and service abuse',
- ]);
- });
-
- test('a temporary block says when it ends', () => {
- const {element} = renderScreen({
- type: 'network_blocked',
- block: {...block, ban_kind: 'temporary_24h', expires_at: '2026-10-15T10:00:00.000Z'},
- });
- expect(text(element)).toContain('The block ends on Oct 15, 2026, 10:00 AM UTC.');
- });
-
- test('self-hosted blocks have no contact line', () => {
- const {element} = renderScreen({
- type: 'network_blocked',
- block: {...block, appeal_email: null, appeals_supported: false},
- });
- expect(text(element)).not.toContain('mistake');
- expect(element.querySelectorAll('a')).toHaveLength(0);
- });
-
- test('an unnamed self-hosted instance uses the name the server sent', () => {
- const {element} = renderScreen({
- type: 'network_blocked',
- block: {...block, appeal_email: null, appeals_supported: false, product_name: 'chat.example.org'},
- });
- expect(paragraphs(element)[0]).toBe('chat.example.org blocked access from this network.');
- expect(text(element)).not.toContain('Fluxer');
- });
-
- test('try again calls its handler', () => {
- const {element, onTryAgain} = renderScreen({type: 'network_blocked', block});
- clickButton(element, 'Try again');
- expect(onTryAgain).toHaveBeenCalledOnce();
- });
-});
-
-describe('gate', () => {
- test('renders its page when nothing is restricted', () => {
- const element = render(
- <AccountRestrictionGate data-flx="auth.flow.account-restriction-screen-test.gate">
- <p data-flx="auth.flow.account-restriction-screen-test.page">page</p>
- </AccountRestrictionGate>,
- );
- expect(text(element)).toBe('page');
- });
-
- test('replaces the page and returns to sign-in from another page', () => {
- mocks.restriction = {type: 'notice', notice};
- const element = render(
- <AccountRestrictionGate data-flx="auth.flow.account-restriction-screen-test.gate--2">
- <p data-flx="auth.flow.account-restriction-screen-test.page--2">page</p>
- </AccountRestrictionGate>,
- );
- expect(text(element)).not.toContain('page');
- clickButton(element, 'Back to sign-in');
- expect(mocks.clearAccountRestriction).toHaveBeenCalledOnce();
- expect(mocks.replaceWith).toHaveBeenCalledWith('/login');
- });
-
- test('try again on the sign-in page stays on it', () => {
- mocks.restriction = {type: 'network_blocked', block};
- mocks.pathname = '/login';
- const element = render(
- <AccountRestrictionGate data-flx="auth.flow.account-restriction-screen-test.gate--3">
- <p data-flx="auth.flow.account-restriction-screen-test.page--3">page</p>
- </AccountRestrictionGate>,
- );
- clickButton(element, 'Try again');
- expect(mocks.clearAccountRestriction).toHaveBeenCalledOnce();
- expect(mocks.replaceWith).not.toHaveBeenCalled();
- });
-});
-
-describe('signed-in network block modal', () => {
- test('opens once until someone tries again', () => {
- showNetworkBlockedModal(block);
- showNetworkBlockedModal(block);
- expect(mocks.pushModal).toHaveBeenCalledOnce();
- const renderModal = mocks.pushModal.mock.calls[0]?.[0] as () => ReactNode;
- const element = render(renderModal());
- expect(element.querySelector('[role="dialog"]')?.className).toBe('selectable');
- expect(element.querySelector('h1')?.textContent).toBe('Network blocked');
- expect(text(element)).toContain('Fluxer blocked access from this network.');
- clickButton(element, 'Try again');
- expect(mocks.popModal).toHaveBeenCalledOnce();
- showNetworkBlockedModal({...block, appeal_email: null, appeals_supported: false, product_name: 'chat.example.org'});
- expect(mocks.pushModal).toHaveBeenCalledTimes(2);
- const renderSelfHosted = mocks.pushModal.mock.calls[1]?.[0] as () => ReactNode;
- const selfHosted = render(renderSelfHosted());
- expect(text(selfHosted)).toContain('chat.example.org blocked access from this network.');
- expect(text(selfHosted)).not.toContain('Fluxer');
- clickButton(selfHosted, 'Try again');
- });
-
- test('follows the direction of the locale', () => {
- mocks.locale = 'he';
- showNetworkBlockedModal(block);
- const renderModal = mocks.pushModal.mock.calls[0]?.[0] as () => ReactNode;
- const element = render(renderModal());
- expect(element.querySelector('[data-modal-content]')?.getAttribute('dir')).toBe('rtl');
- clickButton(element, 'Try again');
- });
-});
diff --git a/fluxer_app/src/features/auth/flow/ResourceAuthPages.test.tsx b/fluxer_app/src/features/auth/flow/ResourceAuthPages.test.tsx
deleted file mode 100644
index 80c463e00..000000000
--- a/fluxer_app/src/features/auth/flow/ResourceAuthPages.test.tsx
+++ /dev/null
@@ -1,233 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {RuntimeConfigSnapshot} from '@app/features/app/state/InstanceSnapshotStore';
-import type {TokenResponse} from '@app/features/auth/commands/AuthenticationCommands';
-import {
- type ResourceAuthPageConfig,
- ResourceLoginPage,
- ResourceRegisterPage,
-} from '@app/features/auth/flow/ResourceAuthPages';
-import type {ReactNode} from 'react';
-import {renderToStaticMarkup} from 'react-dom/server';
-import {beforeEach, describe, expect, it, vi} from 'vitest';
-
-const mocks = vi.hoisted(() => ({
- snapshot: {
- apiEndpoint: 'https://instance.example/api',
- apiCodeVersion: 7,
- features: {},
- registration: {mode: 'open', admin_registration_urls_enabled: false},
- } as RuntimeConfigSnapshot,
- reset: vi.fn(),
- completeLogin: vi.fn(),
- search: '',
- loginProps: null as any,
- registerProps: null as any,
- ssoProps: null as any,
- carouselProps: null as any,
-}));
-vi.mock('@lingui/core/macro', () => ({msg: (descriptor: unknown) => descriptor}));
-vi.mock('@lingui/react/macro', () => ({useLingui: () => ({i18n: {_: (d: any) => d.message ?? d.id}})}));
-vi.mock('@app/features/auth/flow/auth_login_core/useDesktopHandoffFlow', () => ({
- isHandoffRequest: (params: URLSearchParams) => params.has('desktop_handoff'),
-}));
-vi.mock('mobx-react-lite', () => ({observer: (component: unknown) => component}));
-vi.mock('@app/features/i18n/utils/CommonMessageDescriptors', () => ({REGISTER_DESCRIPTOR: {message: 'Register'}}));
-vi.mock('@app/features/auth/commands/AuthenticationCommands', () => ({
- completeLogin: mocks.completeLogin,
- authResponseUserToUserData: () => ({id: 'user'}),
-}));
-vi.mock('@app/features/auth/state/AuthRuntimeTarget', () => ({useAuthRuntimeTarget: () => ({reset: mocks.reset})}));
-vi.mock('@app/features/platform/components/router/RouterReact', () => ({useLocation: () => ({search: mocks.search})}));
-vi.mock('@app/features/window/hooks/useFluxerDocumentTitle', () => ({useFluxerDocumentTitle: () => {}}));
-vi.mock('@app/features/auth/flow/useAuthPresentation', () => ({useAuthPresentation: () => {}}));
-vi.mock('@app/features/auth/state/AuthLayoutContext', () => ({AuthCardVariant: {STANDARD: 'standard'}}));
-vi.mock('@app/features/auth/flow/AuthRuntimeTargetGate', () => ({
- AuthRuntimeTargetGate: ({children}: {children: (snapshot: RuntimeConfigSnapshot) => ReactNode}) =>
- children(mocks.snapshot),
-}));
-vi.mock('@app/features/auth/flow/AuthLoadingState', () => ({
- AuthLoadingState: () => <span data-flx="auth.flow.resource-auth-pages-test.auth-loading-state.span">loading</span>,
-}));
-vi.mock('@app/features/auth/flow/AuthErrorState', () => ({
- AuthErrorState: () => <span data-flx="auth.flow.resource-auth-pages-test.auth-error-state.span">error</span>,
-}));
-vi.mock('@app/features/auth/flow/AuthRuntimeTargetResetAction', () => ({AuthRuntimeTargetResetAction: () => null}));
-vi.mock('@app/features/auth/flow/AuthLoginLayout', () => ({
- AuthLoginLayout: (props: any) => {
- mocks.loginProps = props;
- return props.extraTopContent;
- },
-}));
-vi.mock('@app/features/auth/flow/AuthLoginStepCarousel', () => ({
- AuthLoginStepCarousel: (props: any) => {
- mocks.carouselProps = props;
- return props.children;
- },
-}));
-vi.mock('@app/features/auth/flow/AuthRegisterFormCore', () => ({
- AuthRegisterFormCore: (props: any) => {
- mocks.registerProps = props;
- return null;
- },
-}));
-vi.mock('@app/features/auth/flow/AuthRouterLink', () => ({AuthRouterLink: () => null}));
-vi.mock('@app/features/auth/flow/AuthBottomLink', () => ({AuthBottomLink: () => null}));
-vi.mock('@app/features/auth/flow/DesktopDeepLinkPrompt', () => ({
- DesktopDeepLinkPrompt: (props: any) => (
- <span data-flx="auth.flow.resource-auth-pages-test.desktop-deep-link-prompt.span">
- {props.preferLogin ? 'prefer-login' : 'default'}
- </span>
- ),
-}));
-vi.mock('@app/features/auth/flow/AuthSsoPanel', () => ({
- resolveAuthPanelSso: (snapshot: any) => snapshot.sso,
- AuthSsoPanel: (props: any) => {
- mocks.ssoProps = props;
- return null;
- },
-}));
-
-function config(overrides: Partial<ResourceAuthPageConfig<string>> = {}): ResourceAuthPageConfig<string> {
- return {
- kind: 'gift',
- dataFlxPrefix: (mode) => `gift.${mode}`,
- useResource: () => ({loading: false, error: false, resource: 'gift'}),
- renderHeader: (resource) => (
- <span data-flx="auth.flow.resource-auth-pages-test.render-header.span">{resource}</span>
- ),
- documentTitle: () => 'Claim gift',
- errorTitle: () => 'Not found',
- errorText: 'Not found',
- registerPath: (id) => `/gift/${id}/register`,
- loginPath: (id) => `/gift/${id}/login`,
- redirectPath: (id, redirect) => redirect ?? `/gift/${id}/register`,
- fallbackRedirectPath: () => '/',
- registerRedirectPath: () => '/',
- onComplete: vi.fn(),
- submitLabel: 'Create account',
- ...overrides,
- };
-}
-beforeEach(() => {
- vi.clearAllMocks();
- mocks.search = '';
- mocks.loginProps = mocks.registerProps = mocks.ssoProps = mocks.carouselProps = null;
- delete (mocks.snapshot as any).sso;
- (mocks.snapshot as any).registration = {mode: 'open', admin_registration_urls_enabled: false};
-});
-describe('resource auth guards', () => {
- it('blocks redeemed resources before login, registration or enforced SSO', () => {
- (mocks.snapshot as any).sso = {enabled: true, enforced: true};
- const blocked = config({
- renderBlockingState: () => (
- <span data-flx="auth.flow.resource-auth-pages-test.render-blocking-state.span">redeemed</span>
- ),
- });
- expect(
- renderToStaticMarkup(
- <ResourceLoginPage id="code" config={blocked} data-flx="auth.flow.resource-auth-pages-test.code" />,
- ),
- ).toContain('redeemed');
- expect(
- renderToStaticMarkup(
- <ResourceRegisterPage id="code" config={blocked} data-flx="auth.flow.resource-auth-pages-test.code--2" />,
- ),
- ).toContain('redeemed');
- expect(mocks.loginProps).toBeNull();
- expect(mocks.registerProps).toBeNull();
- expect(mocks.ssoProps).toBeNull();
- });
- it('keeps loading and missing resources outside authentication', () => {
- renderToStaticMarkup(
- <ResourceLoginPage
- id="code"
- config={config({useResource: () => ({loading: true, error: false, resource: null})})}
- data-flx="auth.flow.resource-auth-pages-test.code--3"
- />,
- );
- renderToStaticMarkup(
- <ResourceRegisterPage
- id="code"
- config={config({useResource: () => ({loading: false, error: true, resource: null})})}
- data-flx="auth.flow.resource-auth-pages-test.code--4"
- />,
- );
- expect(mocks.loginProps).toBeNull();
- expect(mocks.registerProps).toBeNull();
- });
- it('preserves safe redirects, gift login preference, MFA fallback and async completion order', async () => {
- mocks.search = '?redirect_to=%2Fchannels%2F%40me';
- let finish!: () => void;
- const accept = vi.fn(
- () =>
- new Promise<void>((resolve) => {
- finish = resolve;
- }),
- );
- const html = renderToStaticMarkup(
- <ResourceLoginPage
- id="code"
- config={config({preferLogin: true, onComplete: accept, fallbackRedirectPath: () => '/gift/code'})}
- data-flx="auth.flow.resource-auth-pages-test.code--5"
- />,
- );
- expect(html).toContain('prefer-login');
- expect(mocks.loginProps.redirectPath).toBe('/channels/@me');
- expect(mocks.carouselProps.mfaFallbackRedirectPath).toBe('/gift/code');
- const pending = mocks.loginProps.onLoginComplete();
- expect(accept).toHaveBeenCalledWith('code', expect.anything(), mocks.snapshot);
- expect(mocks.reset).not.toHaveBeenCalled();
- finish();
- await pending;
- expect(mocks.reset).toHaveBeenCalledOnce();
- });
- it('finishes registration against the captured instance before accepting the resource', async () => {
- const accept = vi.fn();
- renderToStaticMarkup(
- <ResourceRegisterPage
- id="code"
- config={config({onComplete: accept})}
- data-flx="auth.flow.resource-auth-pages-test.code--6"
- />,
- );
- const response = {token: 'token', user_id: 'user', user: {id: 'user'}} as TokenResponse;
- await mocks.registerProps.onRegister(response);
- expect(mocks.completeLogin).toHaveBeenCalledWith({
- token: 'token',
- userId: 'user',
- runtimeSnapshot: mocks.snapshot,
- userData: {id: 'user'},
- });
- expect(mocks.completeLogin.mock.invocationCallOrder[0]).toBeLessThan(accept.mock.invocationCallOrder[0]);
- expect(accept).toHaveBeenCalledWith('code', expect.anything(), mocks.snapshot);
- expect(mocks.registerProps.onAuthenticated).toBe(mocks.reset);
- });
- it('uses enforced SSO without mounting the registration form', () => {
- (mocks.snapshot as any).sso = {enabled: true, enforced: true};
- renderToStaticMarkup(
- <ResourceRegisterPage id="code" config={config()} data-flx="auth.flow.resource-auth-pages-test.code--7" />,
- );
- expect(mocks.ssoProps.runtimeSnapshot).toBe(mocks.snapshot);
- expect(mocks.ssoProps.redirectPath).toBe('/gift/code/register');
- expect(mocks.registerProps).toBeNull();
- });
- it('asks for an email and password on an approval instance', () => {
- (mocks.snapshot as any).registration = {mode: 'approval', admin_registration_urls_enabled: false};
- renderToStaticMarkup(
- <ResourceRegisterPage id="code" config={config()} data-flx="auth.flow.resource-auth-pages-test.code--8" />,
- );
- expect(mocks.registerProps.fields).toMatchObject({
- showEmail: true,
- showPassword: true,
- showPasswordConfirmation: true,
- });
- });
- it('keeps the minimal form on an open email instance', () => {
- renderToStaticMarkup(
- <ResourceRegisterPage id="code" config={config()} data-flx="auth.flow.resource-auth-pages-test.code--9" />,
- );
- expect(mocks.registerProps.fields).toEqual({showUsername: false});
- });
-});
diff --git a/fluxer_app/src/features/auth/flow/browser_handoff/useBrowserLoginHandoff.test.ts b/fluxer_app/src/features/auth/flow/browser_handoff/useBrowserLoginHandoff.test.ts
deleted file mode 100644
index 34310326a..000000000
--- a/fluxer_app/src/features/auth/flow/browser_handoff/useBrowserLoginHandoff.test.ts
+++ /dev/null
@@ -1,404 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {installHarnessBootstrap} from '@app/features/auth/state/__fixtures__/AccountSwitchHarness';
-import type {DesktopHandoffAPI, DesktopHandoffSession} from '@fluxer/desktop_ipc/src/BrowserHandoffContract';
-import {act, createElement, type ReactNode} from 'react';
-import {createRoot, type Root} from 'react-dom/client';
-import {afterEach, beforeEach, 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('@lingui/react/macro', () => ({
- Trans: ({children}: {children?: ReactNode}) => children ?? null,
- useLingui: () => ({i18n: {_: (descriptor: {message?: string}) => descriptor.message ?? ''}}),
-}));
-vi.mock('@app/features/ui/commands/TextCopyCommands', () => ({
- copy: (...args: Array<unknown>) => harness.copy(...args),
-}));
-vi.mock('@app/features/auth/hooks/useAuthForm', () => ({
- getAuthErrorMessage: (error: unknown) => (error instanceof Error ? error.message : 'error'),
-}));
-vi.mock('@app/features/platform/transport/InstanceHTTP', () => ({
- instanceTargetFromSnapshot: (snapshot: {apiEndpoint: string; apiCodeVersion: number}) => ({
- instanceKey: snapshot.apiEndpoint,
- apiEndpoint: snapshot.apiEndpoint,
- apiVersion: snapshot.apiCodeVersion,
- }),
-}));
-
-const harness = vi.hoisted(() => ({
- initiateDesktopHandoff: vi.fn(),
- pollDesktopHandoffStatus: vi.fn(),
- navigateToExternalURL: vi.fn(async (_url: string) => {}),
- copy: vi.fn(async (..._args: Array<unknown>) => true),
-}));
-
-vi.mock('@app/features/auth/commands/AuthenticationCommands', () => ({
- initiateDesktopHandoff: harness.initiateDesktopHandoff,
- pollDesktopHandoffStatus: harness.pollDesktopHandoffStatus,
- authResponseUserToUserData: (user?: {username?: string} | null) =>
- user == null ? undefined : {username: user.username, discriminator: '0001'},
-}));
-vi.mock(import('@app/features/ui/utils/NativeUtils'), async (importOriginal) => ({
- ...(await importOriginal()),
- navigateToExternalURL: harness.navigateToExternalURL,
-}));
-
-installHarnessBootstrap();
-
-const {useBrowserLoginHandoff} = await import('@app/features/auth/flow/browser_handoff/useBrowserLoginHandoff');
-const {BrowserLoginHandoffTransportKind, resolveBrowserLoginHandoffTransport} = await import(
- '@app/features/auth/flow/browser_handoff/BrowserLoginHandoffTransport'
-);
-
-type Controller = ReturnType<typeof useBrowserLoginHandoff>;
-
-(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT = true;
-
-const RUNTIME_SNAPSHOT = {
- apiEndpoint: 'https://self.hosted.example/api',
- apiCodeVersion: 1,
- webAppEndpoint: 'https://self.hosted.example/',
- features: {},
-} as unknown as Parameters<typeof useBrowserLoginHandoff>[0]['runtimeSnapshot'];
-
-const CODE = 'ABCDEF-123456';
-const COMPLETED_USER = {username: 'ada', discriminator: '0001', global_name: 'Ada', avatar: null, email: null};
-
-function installElectron(api: unknown): void {
- Object.defineProperty(window, 'electron', {value: api, configurable: true, writable: true});
-}
-
-function createDesktopHandoffAPI(): DesktopHandoffAPI & {
- readonly initiated: Array<unknown>;
- readonly polled: Array<string>;
-} {
- const initiated: Array<unknown> = [];
- const polled: Array<string> = [];
- let completed = false;
- return {
- initiated,
- polled,
- initiate: async (instance) => {
- initiated.push(instance);
- const session: DesktopHandoffSession = {
- instance,
- code: CODE,
- expiresAt: new Date(Date.now() + 300_000).toISOString(),
- returnMethod: 'deep_link',
- };
- return session;
- },
- status: async (code) => {
- polled.push(code);
- if (!completed) {
- completed = true;
- return {status: 'pending'};
- }
- return {status: 'completed', token: 'ipc-token', userId: '77', user: COMPLETED_USER};
- },
- };
-}
-
-let container: HTMLDivElement;
-let root: Root;
-let controller: Controller | null = null;
-
-function Probe({
- onEnded,
- onSuccess,
- runtimeSnapshot,
-}: {
- onEnded: () => void;
- onSuccess: (payload: {token: string; userId: string}) => Promise<void> | void;
- runtimeSnapshot: typeof RUNTIME_SNAPSHOT;
-}) {
- controller = useBrowserLoginHandoff({
- runtimeSnapshot,
- onEnded,
- onSuccess,
- });
- return null;
-}
-
-function requireController(): Controller {
- if (controller == null) {
- throw new Error('The browser handoff hook was never mounted');
- }
- return controller;
-}
-
-async function mountProbe(
- onSuccess: (payload: {token: string; userId: string}) => Promise<void> | void,
- runtimeSnapshot: typeof RUNTIME_SNAPSHOT = RUNTIME_SNAPSHOT,
- onEnded: () => void = () => {},
-): Promise<void> {
- await act(async () => {
- root.render(createElement(Probe, {onEnded, onSuccess, runtimeSnapshot}));
- });
-}
-
-async function advancePollInterval(): Promise<void> {
- await act(async () => {
- await vi.advanceTimersByTimeAsync(2100);
- });
-}
-
-beforeEach(() => {
- vi.useFakeTimers();
- controller = null;
- harness.initiateDesktopHandoff.mockReset();
- harness.pollDesktopHandoffStatus.mockReset();
- harness.navigateToExternalURL.mockClear();
- harness.copy.mockReset();
- harness.copy.mockResolvedValue(true);
- harness.initiateDesktopHandoff.mockResolvedValue({
- code: CODE,
- expires_at: new Date(Date.now() + 300_000).toISOString(),
- poll_secret: 'server-poll-secret',
- });
- harness.pollDesktopHandoffStatus
- .mockResolvedValueOnce({status: 'pending'})
- .mockResolvedValue({status: 'completed', token: 'renderer-token', user_id: '42', user: COMPLETED_USER});
- installElectron(undefined);
- container = document.createElement('div');
- document.body.append(container);
- root = createRoot(container);
-});
-
-afterEach(() => {
- act(() => {
- root.unmount();
- });
- container.remove();
- vi.useRealTimers();
-});
-
-describe('browser handoff transport selection', () => {
- test('picks the renderer transport on a deployed shell whose preload has no desktopHandoff', () => {
- installElectron({platform: 'darwin'});
-
- expect(resolveBrowserLoginHandoffTransport().kind).toBe(BrowserLoginHandoffTransportKind.RENDERER);
- });
-
- test('picks the renderer transport when the shell exposes a partial desktopHandoff namespace', () => {
- installElectron({platform: 'darwin', desktopHandoff: {status: () => Promise.resolve({status: 'pending'})}});
-
- expect(resolveBrowserLoginHandoffTransport().kind).toBe(BrowserLoginHandoffTransportKind.RENDERER);
- });
-
- test('picks the renderer transport on the web, where there is no window.electron at all', () => {
- installElectron(undefined);
-
- expect(resolveBrowserLoginHandoffTransport().kind).toBe(BrowserLoginHandoffTransportKind.RENDERER);
- });
-
- test('picks the IPC transport once the shell exposes the whole desktopHandoff namespace', () => {
- installElectron({platform: 'darwin', desktopHandoff: createDesktopHandoffAPI()});
-
- expect(resolveBrowserLoginHandoffTransport().kind).toBe(BrowserLoginHandoffTransportKind.IPC);
- });
-});
-
-describe('browser sign-in against a deployed desktop shell', () => {
- test('completes over the renderer transport when window.electron carries no desktopHandoff', async () => {
- installElectron({platform: 'darwin'});
- const succeeded: Array<{token: string; userId: string}> = [];
- await mountProbe((payload) => {
- succeeded.push(payload);
- });
-
- await act(async () => {
- await requireController().openBrowser();
- });
-
- expect(harness.initiateDesktopHandoff).toHaveBeenCalledTimes(1);
- expect(harness.navigateToExternalURL).toHaveBeenCalledTimes(1);
- expect(harness.navigateToExternalURL.mock.calls[0]?.[0]).toBe(
- `https://self.hosted.example/login?handoff=1&code=${encodeURIComponent(CODE)}&api=${encodeURIComponent('https://self.hosted.example')}`,
- );
-
- await advancePollInterval();
- await advancePollInterval();
-
- expect(succeeded).toEqual([
- {token: 'renderer-token', userId: '42', userData: {username: 'ada', discriminator: '0001'}},
- ]);
- });
-
- test('falls back to the unauthenticated status read against an instance that issues no poll secret', async () => {
- installElectron({platform: 'darwin'});
- harness.initiateDesktopHandoff.mockResolvedValue({
- code: CODE,
- expires_at: new Date(Date.now() + 300_000).toISOString(),
- });
- await mountProbe(() => {});
-
- await act(async () => {
- await requireController().openBrowser();
- });
- await advancePollInterval();
-
- expect(harness.pollDesktopHandoffStatus).toHaveBeenCalledTimes(1);
- expect(harness.pollDesktopHandoffStatus.mock.calls[0]?.[1]).toBeNull();
- });
-
- test('polls with the secret the instance issued rather than the unauthenticated fallback', async () => {
- installElectron({platform: 'darwin'});
- await mountProbe(() => {});
-
- await act(async () => {
- await requireController().openBrowser();
- });
- await advancePollInterval();
-
- expect(harness.pollDesktopHandoffStatus).toHaveBeenCalledTimes(1);
- expect(harness.pollDesktopHandoffStatus.mock.calls[0]).toEqual([
- CODE,
- 'server-poll-secret',
- {
- instanceKey: 'https://self.hosted.example/api',
- apiEndpoint: 'https://self.hosted.example/api',
- apiVersion: 1,
- },
- ]);
- });
-});
-
-describe('browser sign-in against an updated desktop shell', () => {
- test('routes the whole ceremony through the main process and completes', async () => {
- const api = createDesktopHandoffAPI();
- installElectron({platform: 'darwin', desktopHandoff: api});
- const succeeded: Array<{token: string; userId: string}> = [];
- await mountProbe((payload) => {
- succeeded.push(payload);
- });
-
- await act(async () => {
- await requireController().openBrowser();
- });
-
- expect(api.initiated).toEqual([
- {apiEndpoint: 'https://self.hosted.example/api', apiVersion: 1, webAppEndpoint: 'https://self.hosted.example'},
- ]);
- expect(harness.initiateDesktopHandoff).not.toHaveBeenCalled();
- expect(requireController().session?.pollSecret).toBeNull();
-
- await advancePollInterval();
- await advancePollInterval();
-
- expect(api.polled).toEqual([CODE, CODE]);
- expect(harness.pollDesktopHandoffStatus).not.toHaveBeenCalled();
- expect(succeeded).toEqual([{token: 'ipc-token', userId: '77', userData: {username: 'ada', discriminator: '0001'}}]);
- });
-});
-
-describe('when the instance stops answering the status poll', () => {
- test('stops the spinner instead of waiting forever, and resumes on request', async () => {
- installElectron({platform: 'darwin'});
- harness.pollDesktopHandoffStatus.mockReset();
- harness.pollDesktopHandoffStatus.mockRejectedValue(new Error('network down'));
- await mountProbe(() => {});
- await act(async () => {
- await requireController().openBrowser();
- });
-
- await advancePollInterval();
- await advancePollInterval();
- await advancePollInterval();
-
- expect(harness.pollDesktopHandoffStatus).toHaveBeenCalledTimes(3);
- expect(requireController().hasStoppedWaiting).toBe(true);
-
- await advancePollInterval();
- expect(harness.pollDesktopHandoffStatus).toHaveBeenCalledTimes(3);
-
- await act(async () => {
- requireController().resumeWaiting();
- });
- expect(requireController().hasStoppedWaiting).toBe(false);
-
- await advancePollInterval();
- expect(harness.pollDesktopHandoffStatus).toHaveBeenCalledTimes(4);
- });
-});
-
-describe('when finishing the approved sign-in fails', () => {
- test('stops the spinner and lets the same session be retried instead of reporting a poll error', async () => {
- installElectron({platform: 'darwin'});
- harness.pollDesktopHandoffStatus.mockReset();
- harness.pollDesktopHandoffStatus.mockResolvedValue({
- status: 'completed',
- token: 'renderer-token',
- user_id: '42',
- user: COMPLETED_USER,
- });
- let failCompletion = true;
- const attempts: Array<{token: string; userId: string}> = [];
- await mountProbe(async (payload) => {
- attempts.push(payload);
- if (failCompletion) {
- throw new Error('storing the account failed');
- }
- });
- await act(async () => {
- await requireController().openBrowser();
- });
-
- await advancePollInterval();
-
- expect(attempts).toHaveLength(1);
- expect(requireController().hasStoppedWaiting).toBe(true);
- expect(requireController().error).toBe('storing the account failed');
-
- await advancePollInterval();
- expect(harness.pollDesktopHandoffStatus).toHaveBeenCalledTimes(1);
-
- failCompletion = false;
- await act(async () => {
- requireController().resumeWaiting();
- });
- await advancePollInterval();
-
- expect(harness.pollDesktopHandoffStatus).toHaveBeenCalledTimes(2);
- expect(attempts).toHaveLength(2);
- expect(requireController().hasStoppedWaiting).toBe(false);
- });
-});
-
-describe('when the instance reports the code as dead', () => {
- test('stops polling, clears the session and reports the expiry exactly once', async () => {
- installElectron({platform: 'darwin'});
- harness.pollDesktopHandoffStatus.mockReset();
- harness.pollDesktopHandoffStatus.mockResolvedValue({status: 'expired'});
- let expiredCount = 0;
- await mountProbe(
- () => {},
- RUNTIME_SNAPSHOT,
- () => {
- expiredCount += 1;
- },
- );
- await act(async () => {
- await requireController().openBrowser();
- });
- expect(requireController().hasCode).toBe(true);
-
- await advancePollInterval();
-
- expect(expiredCount).toBe(1);
- expect(harness.pollDesktopHandoffStatus).toHaveBeenCalledTimes(1);
- expect(requireController().session).toBeNull();
- expect(requireController().code).toBeNull();
- expect(requireController().error).toBe('The sign-in request expired before your browser approved it.');
-
- await advancePollInterval();
- await advancePollInterval();
-
- expect(harness.pollDesktopHandoffStatus).toHaveBeenCalledTimes(1);
- expect(expiredCount).toBe(1);
- });
-});
diff --git a/fluxer_app/src/features/auth/state/Accounts.test.ts b/fluxer_app/src/features/auth/state/Accounts.test.ts
deleted file mode 100644
index 6d62d4212..000000000
--- a/fluxer_app/src/features/auth/state/Accounts.test.ts
+++ /dev/null
@@ -1,667 +0,0 @@
-// @vitest-environment happy-dom
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {RuntimeConfigSnapshot} from '@app/features/app/state/RuntimeConfig';
-import {
- HARNESS_API_ENDPOINT,
- installHarnessBootstrap,
- resetScriptedTransport,
- ScriptedXMLHttpRequest,
- scriptedReplies,
- scriptedRequestTokens,
- serverErrorReply,
- unauthorizedReply,
- userMeReply,
-} from '@app/features/auth/state/__fixtures__/AccountSwitchHarness';
-import {instanceDiscoveryFixture} from '@app/features/platform/state/__fixtures__/RuntimeBootstrapFixture';
-import type {VoiceAccountExitRequest, VoiceAccountIdentity} from '@app/features/voice/VoiceAccountLifecyclePort';
-import type {MessageDescriptor} from '@lingui/core';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
-
-vi.mock('@lingui/core/macro', () => ({msg: (descriptor: MessageDescriptor) => descriptor}));
-
-const mocks = vi.hoisted(() => ({
- foregroundAccountKey: null as string | null,
- isForegroundReady: false,
- waitForForegroundReady: vi.fn<(accountKey: string | null) => Promise<void>>(() => Promise.resolve()),
- beginForegroundPromotion: vi.fn<(accountKey: string) => Promise<void>>(() => Promise.resolve()),
- reuseReadyForegroundSession: vi.fn<(accountKey: string, token: string) => void>(),
- recoverForegroundSession: vi.fn<(accountKey: string) => void>(),
- completeForegroundPromotion: vi.fn<(accountKey: string) => Promise<void>>(() => Promise.resolve()),
- rollbackForegroundPromotion: vi.fn<(accountKey: string) => Promise<void>>(() => Promise.resolve()),
- retireForAccountTransition: vi.fn<(reason: string) => Promise<void>>(() => Promise.resolve()),
- gatewayLogout: vi.fn<() => void>(),
- sendInvisiblePresence: vi.fn<() => void>(),
- replaceWith: vi.fn<(path: string) => void>((path) => {
- mocks.currentPath = path;
- mocks.commitRouterPath(path);
- }),
- readRouterPath: (): string => '',
- commitRouterPath: (_path: string): void => undefined,
- abandonUnreachableLastLocation: vi.fn<() => void>(),
- currentPath: '',
- lastLocation: null as string | null,
- saveLocation: vi.fn<(path: string) => void>(),
- readHydratedAccountKey: (): string | null => null,
- hydrateForegroundStores: (_accountKey: string | null): void => undefined,
- readCurrentAccountKey: (): string | null => null,
- leaveVoiceChannelForAccountExit: vi.fn<(request: VoiceAccountExitRequest) => Promise<void>>(),
- suspendVoiceForAccountRestriction: vi.fn<(account: VoiceAccountIdentity) => Promise<void>>(),
- unregisterAllPushSubscriptions: vi.fn<() => Promise<void>>(),
- registerPushSubscription: vi.fn<() => Promise<string | null>>(),
- isGranted: vi.fn<() => Promise<boolean>>(),
- isInstalledPwa: false,
-}));
-
-vi.mock('@app/features/gateway/transport/GatewaySessionPool', () => ({
- default: {
- waitForForegroundReady: mocks.waitForForegroundReady,
- beginPromote: mocks.beginForegroundPromotion,
- completePromote: mocks.completeForegroundPromotion,
- rollbackPromote: mocks.rollbackForegroundPromotion,
- recoverForegroundSession: mocks.recoverForegroundSession,
- retireForAccountTransition: mocks.retireForAccountTransition,
- foregroundConnection: {
- get foregroundAccountKey() {
- return mocks.foregroundAccountKey;
- },
- get isReady() {
- return mocks.isForegroundReady;
- },
- reuseReadySession: mocks.reuseReadyForegroundSession,
- logout: mocks.gatewayLogout,
- sendInvisiblePresenceForCurrentSession: mocks.sendInvisiblePresence,
- },
- },
-}));
-
-vi.mock('@app/features/navigation/utils/RouterUtils', () => ({
- replaceWith: mocks.replaceWith,
- transitionTo: () => undefined,
- getCurrentPath: () => mocks.currentPath,
- getHistory: () => null,
- history: null,
-}));
-
-vi.mock('@app/features/navigation/state/Navigation', async () => {
- const {observable, runInAction} = await import('mobx');
- const routerPath = observable.box('');
- mocks.readRouterPath = () => routerPath.get();
- mocks.commitRouterPath = (path) => runInAction(() => routerPath.set(path));
- return {
- default: {
- get pathname() {
- return mocks.readRouterPath();
- },
- },
- };
-});
-
-vi.mock('@app/features/ui/state/Location', () => ({
- default: {getLastLocation: () => mocks.lastLocation, saveLocation: mocks.saveLocation},
-}));
-
-vi.mock('@app/features/user/state/Users', async () => {
- const {observable, runInAction} = await import('mobx');
- const hydratedAccountKey = observable.box<string | null>(null);
- mocks.readHydratedAccountKey = () => hydratedAccountKey.get();
- mocks.hydrateForegroundStores = (accountKey) => runInAction(() => hydratedAccountKey.set(accountKey));
- return {
- default: {
- get isCurrentUserHydrated() {
- const accountKey = hydratedAccountKey.get();
- return accountKey !== null && accountKey === mocks.readCurrentAccountKey();
- },
- },
- };
-});
-
-vi.mock('@app/features/navigation/utils/ChannelRouteReachability', () => ({
- abandonUnreachableLastLocation: mocks.abandonUnreachableLastLocation,
-}));
-
-vi.mock('@app/features/ui/utils/PwaUtils', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@app/features/ui/utils/PwaUtils')>()),
- isInstalledPwa: () => mocks.isInstalledPwa,
-}));
-
-vi.mock('@app/features/notification/utils/NotificationUtils', () => ({isGranted: mocks.isGranted}));
-
-vi.mock('@app/features/platform/push/PushSubscriptionService', () => ({
- unregisterAllPushSubscriptions: mocks.unregisterAllPushSubscriptions,
- registerPushSubscription: mocks.registerPushSubscription,
-}));
-
-vi.mock('@app/features/voice/VoiceAccountLifecycle', () => ({
- leaveVoiceChannelForAccountExit: mocks.leaveVoiceChannelForAccountExit,
- suspendVoiceForAccountRestriction: mocks.suspendVoiceForAccountRestriction,
-}));
-
-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,
- captureAccountTransitionCheckpoint: () => ({
- accountEpoch: 0,
- hydrated: false,
- syncedPreferences: {},
- wireSyncedPreferences: {},
- wireSyncedPreferencesBase: null,
- dirtySyncedPreferenceFields: [],
- recentlyAckedSyncedPreferenceFields: [],
- syncConsecutive429s: 0,
- hadPendingFlush: false,
- }),
- restoreAccountTransitionCheckpoint: () => Promise.resolve(),
- },
-}));
-
-installHarnessBootstrap();
-
-const {default: RuntimeConfig} = await import('@app/features/app/state/RuntimeConfig');
-const {default: AccountAccess, AccountInstanceUnavailableError} = await import(
- '@app/features/auth/state/AccountAccess'
-);
-const {default: Accounts, AccountReplacementOperationCapacityExceededError} = await import(
- '@app/features/auth/state/Accounts'
-);
-const {ForegroundGatewayConnectionRecoverableError, ForegroundGatewayRecoveryCause} = await import(
- '@app/features/gateway/transport/ForegroundGatewayConnectionFailure'
-);
-const {default: accountStorage} = await import('@app/features/auth/state/AccountStorage');
-const {default: SessionManager, SessionExpiredError} = await import('@app/features/platform/state/AuthSession');
-const {AccountScopedWork} = await import('@app/features/platform/state/AccountScopedWork');
-const {default: AppStorage, resetAppStorage} = await import('@app/features/platform/state/PersistentStorage');
-const {AuthSessionStorageKey} = await import('@app/features/platform/state/auth_session/AuthSessionStorage');
-
-mocks.readCurrentAccountKey = () => SessionManager.currentAccountKey;
-
-const ACCOUNT_A = {userId: '100', token: 'token-a'};
-const ACCOUNT_B = {userId: '200', token: 'token-b'};
-const ACCOUNT_C = {userId: '300', token: 'token-c'};
-const BASE_SNAPSHOT: RuntimeConfigSnapshot = RuntimeConfig.getSnapshot();
-
-function accountKeyOf(userId: string): string {
- return `${HARNESS_API_ENDPOINT}::${userId}`;
-}
-
-async function flushPushRegistration(): Promise<void> {
- await new Promise<void>((resolve) => setTimeout(resolve, 0));
-}
-
-async function seedTwoAccounts(): Promise<void> {
- scriptedReplies.push(userMeReply(ACCOUNT_A.userId));
- await SessionManager.login({token: ACCOUNT_A.token, userId: ACCOUNT_A.userId, runtimeSnapshot: BASE_SNAPSHOT});
- scriptedReplies.push(userMeReply(ACCOUNT_B.userId));
- await SessionManager.login({token: ACCOUNT_B.token, userId: ACCOUNT_B.userId, runtimeSnapshot: BASE_SNAPSHOT});
- scriptedReplies.push(userMeReply(ACCOUNT_A.userId));
- await SessionManager.switchAccount(ACCOUNT_A.userId);
- resetScriptedTransport();
- vi.clearAllMocks();
- mocks.isGranted.mockResolvedValue(false);
- mocks.unregisterAllPushSubscriptions.mockResolvedValue(undefined);
- mocks.registerPushSubscription.mockResolvedValue(null);
- mocks.leaveVoiceChannelForAccountExit.mockResolvedValue(undefined);
- mocks.suspendVoiceForAccountRestriction.mockResolvedValue(undefined);
-}
-
-function gatewayOutage(accountKey: string): InstanceType<typeof ForegroundGatewayConnectionRecoverableError> {
- return new ForegroundGatewayConnectionRecoverableError(
- accountKey,
- ForegroundGatewayRecoveryCause.READINESS_TIMEOUT,
- new Error('gateway unreachable'),
- );
-}
-
-beforeEach(async () => {
- mocks.currentPath = '';
- mocks.commitRouterPath('');
- mocks.lastLocation = null;
- mocks.replaceWith.mockImplementation((path) => {
- mocks.currentPath = path;
- mocks.commitRouterPath(path);
- });
- mocks.foregroundAccountKey = null;
- mocks.hydrateForegroundStores(null);
- mocks.isForegroundReady = false;
- mocks.isInstalledPwa = false;
- 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'},
- }),
- ),
- );
- mocks.isGranted.mockResolvedValue(false);
- mocks.unregisterAllPushSubscriptions.mockResolvedValue(undefined);
- mocks.registerPushSubscription.mockResolvedValue(null);
- mocks.leaveVoiceChannelForAccountExit.mockResolvedValue(undefined);
- mocks.suspendVoiceForAccountRestriction.mockResolvedValue(undefined);
- RuntimeConfig.applySnapshot(BASE_SNAPSHOT);
- await SessionManager.reset();
- AccountAccess.forgetAccount(accountKeyOf(ACCOUNT_A.userId));
- AccountAccess.forgetAccount(accountKeyOf(ACCOUNT_B.userId));
- AccountAccess.forgetAccount(accountKeyOf(ACCOUNT_C.userId));
- await resetAppStorage([]);
- await accountStorage.deleteAccount(ACCOUNT_A.userId);
- await accountStorage.deleteAccount(ACCOUNT_B.userId);
- await accountStorage.deleteAccount(ACCOUNT_C.userId);
- await SessionManager.initialize();
- await seedTwoAccounts();
-});
-
-afterEach(() => {
- vi.unstubAllGlobals();
- vi.clearAllMocks();
- resetScriptedTransport();
-});
-
-describe('Accounts switch transaction', () => {
- test('a successful switch activates the target and starts its gateway session', async () => {
- scriptedReplies.push(userMeReply(ACCOUNT_B.userId), userMeReply(ACCOUNT_B.userId));
- await Accounts.switchToAccount(accountKeyOf(ACCOUNT_B.userId), '/channels/@me');
- expect(SessionManager.userId).toBe(ACCOUNT_B.userId);
- expect(SessionManager.token).toBe(ACCOUNT_B.token);
- expect(mocks.leaveVoiceChannelForAccountExit).toHaveBeenCalledWith({
- reason: 'account-switch',
- accountKey: accountKeyOf(ACCOUNT_A.userId),
- userId: ACCOUNT_A.userId,
- });
- expect(mocks.waitForForegroundReady).toHaveBeenLastCalledWith(accountKeyOf(ACCOUNT_B.userId));
- expect(mocks.replaceWith).toHaveBeenCalledWith('/channels/@me');
- });
-
- test('a failed activation leaves the previous account, credentials and gateway session intact', async () => {
- scriptedReplies.push(userMeReply(ACCOUNT_B.userId));
- mocks.completeForegroundPromotion.mockRejectedValueOnce(new SessionExpiredError());
- await expect(Accounts.switchToAccount(accountKeyOf(ACCOUNT_B.userId))).rejects.toBeInstanceOf(SessionExpiredError);
- expect(SessionManager.userId).toBe(ACCOUNT_A.userId);
- expect(SessionManager.token).toBe(ACCOUNT_A.token);
- expect(AppStorage.getItem(AuthSessionStorageKey.UserId)).toBe(ACCOUNT_A.userId);
- expect(AppStorage.getItem(AuthSessionStorageKey.Token)).toBe(ACCOUNT_A.token);
- expect(RuntimeConfig.getSnapshot().apiEndpoint).toBe(BASE_SNAPSHOT.apiEndpoint);
- expect(mocks.waitForForegroundReady).toHaveBeenLastCalledWith(accountKeyOf(ACCOUNT_A.userId));
- expect(mocks.replaceWith).not.toHaveBeenCalled();
- });
-
- test('a rollback that is already on the previous account does not re-fence account scoped work', async () => {
- const runSuspended = vi.spyOn(AccountScopedWork, 'runSuspended');
- scriptedReplies.push(userMeReply(ACCOUNT_B.userId));
- mocks.beginForegroundPromotion.mockRejectedValueOnce(new SessionExpiredError());
-
- await expect(Accounts.switchToAccount(accountKeyOf(ACCOUNT_B.userId))).rejects.toBeInstanceOf(SessionExpiredError);
-
- expect(SessionManager.currentAccountKey).toBe(accountKeyOf(ACCOUNT_A.userId));
- expect(runSuspended).toHaveBeenCalledTimes(1);
- expect(AccountScopedWork.isSuspended).toBe(false);
- runSuspended.mockRestore();
- });
-
- test('a failed activation restores the runtime snapshot the previous account was using', async () => {
- const foreignSnapshot: RuntimeConfigSnapshot = {...BASE_SNAPSHOT, apiEndpoint: 'https://foreign.test/api'};
- mocks.leaveVoiceChannelForAccountExit.mockImplementation(async () => {
- RuntimeConfig.applySnapshot(foreignSnapshot);
- });
- scriptedReplies.push(userMeReply(ACCOUNT_B.userId));
- await expect(Accounts.switchToAccount(accountKeyOf(ACCOUNT_B.userId))).rejects.toThrow();
- expect(RuntimeConfig.apiEndpoint).toBe(BASE_SNAPSHOT.apiEndpoint);
- expect(SessionManager.userId).toBe(ACCOUNT_A.userId);
- expect(mocks.waitForForegroundReady).toHaveBeenLastCalledWith(accountKeyOf(ACCOUNT_A.userId));
- expect(Accounts.getAccount(accountKeyOf(ACCOUNT_B.userId))?.isValid).toBe(true);
- });
-
- test('a rejected pre-flight never touches voice, push or the gateway', async () => {
- mocks.isInstalledPwa = true;
- scriptedReplies.push(unauthorizedReply());
- await expect(Accounts.switchToAccount(accountKeyOf(ACCOUNT_B.userId))).rejects.toBeInstanceOf(SessionExpiredError);
- expect(mocks.leaveVoiceChannelForAccountExit).not.toHaveBeenCalled();
- expect(mocks.unregisterAllPushSubscriptions).not.toHaveBeenCalled();
- expect(mocks.waitForForegroundReady).not.toHaveBeenCalled();
- expect(SessionManager.userId).toBe(ACCOUNT_A.userId);
- expect(Accounts.getAccount(accountKeyOf(ACCOUNT_B.userId))?.isValid).toBe(false);
- });
-
- test('a second replacement while one is in flight is refused rather than interleaved', async () => {
- scriptedReplies.push(userMeReply(ACCOUNT_B.userId), userMeReply(ACCOUNT_B.userId));
- const first = Accounts.switchToAccount(accountKeyOf(ACCOUNT_B.userId));
- const second = Accounts.switchToAccount(accountKeyOf(ACCOUNT_B.userId));
- await expect(second).rejects.toBeInstanceOf(AccountReplacementOperationCapacityExceededError);
- await first;
- expect(SessionManager.userId).toBe(ACCOUNT_B.userId);
- });
-
- test('a switch during a gateway outage commits to the target and keeps reconnecting it', async () => {
- const target = accountKeyOf(ACCOUNT_B.userId);
- scriptedReplies.push(userMeReply(ACCOUNT_B.userId), userMeReply(ACCOUNT_B.userId));
- mocks.waitForForegroundReady.mockImplementation(async (accountKey) => {
- throw gatewayOutage(accountKey ?? target);
- });
-
- await Accounts.switchToAccount(target, '/channels/@me');
-
- expect(SessionManager.currentAccountKey).toBe(target);
- expect(SessionManager.token).toBe(ACCOUNT_B.token);
- expect(mocks.waitForForegroundReady).toHaveBeenCalledTimes(1);
- expect(mocks.waitForForegroundReady).toHaveBeenCalledWith(target);
- expect(mocks.beginForegroundPromotion).not.toHaveBeenCalledWith(accountKeyOf(ACCOUNT_A.userId));
- expect(mocks.recoverForegroundSession).toHaveBeenCalledWith(target);
- expect(mocks.replaceWith).toHaveBeenCalledWith('/channels/@me');
- expect(Accounts.isSwitching).toBe(false);
- mocks.waitForForegroundReady.mockReset();
- mocks.waitForForegroundReady.mockResolvedValue(undefined);
- });
-
- test('a restore that meets a dead gateway keeps the previous account reconnecting', async () => {
- const previous = accountKeyOf(ACCOUNT_A.userId);
- const target = accountKeyOf(ACCOUNT_B.userId);
- const activationFailure = new Error('foreground gateway was superseded');
- mocks.currentPath = '/channels/111/222';
- scriptedReplies.push(userMeReply(ACCOUNT_B.userId), userMeReply(ACCOUNT_B.userId));
- mocks.waitForForegroundReady.mockImplementation(async (accountKey) => {
- if (accountKey === target) {
- throw activationFailure;
- }
- throw gatewayOutage(accountKey ?? previous);
- });
-
- await expect(Accounts.switchToAccount(target, '/channels/@me')).rejects.toBe(activationFailure);
-
- expect(SessionManager.currentAccountKey).toBe(previous);
- expect(mocks.recoverForegroundSession).toHaveBeenCalledWith(previous);
- expect(mocks.replaceWith).not.toHaveBeenCalled();
- expect(mocks.currentPath).toBe('/channels/111/222');
- mocks.waitForForegroundReady.mockReset();
- mocks.waitForForegroundReady.mockResolvedValue(undefined);
- });
-
- test('switching to the account that is already current is a no-op', async () => {
- await Accounts.switchToAccount(accountKeyOf(ACCOUNT_A.userId));
- expect(mocks.leaveVoiceChannelForAccountExit).not.toHaveBeenCalled();
- expect(mocks.waitForForegroundReady).not.toHaveBeenCalled();
- });
-
- test('isSwitching covers the whole transaction, not just the session state', async () => {
- scriptedReplies.push(userMeReply(ACCOUNT_B.userId), userMeReply(ACCOUNT_B.userId));
- const pending = Accounts.switchToAccount(accountKeyOf(ACCOUNT_B.userId));
- expect(Accounts.isSwitching).toBe(true);
- expect(Accounts.canSwitchAccounts).toBe(false);
- await pending;
- expect(Accounts.isSwitching).toBe(false);
- });
-});
-
-describe('Accounts foreground access checks', () => {
- test('a user-initiated switch re-checks an account parked behind an unavailable backoff', async () => {
- const accountKey = accountKeyOf(ACCOUNT_B.userId);
- AccountAccess.markGatewayUnavailable(accountKey, new Error('gateway refused the session'));
- expect(AccountAccess.getRetryEligibleAt(accountKey)).toBeGreaterThan(Date.now());
-
- scriptedReplies.push(userMeReply(ACCOUNT_B.userId), userMeReply(ACCOUNT_B.userId));
- await Accounts.switchToAccount(accountKey, '/channels/@me');
-
- expect(scriptedRequestTokens).toContain(ACCOUNT_B.token);
- expect(SessionManager.userId).toBe(ACCOUNT_B.userId);
- expect(mocks.replaceWith).toHaveBeenCalledWith('/channels/@me');
- });
-
- test('a foreground re-check that fails again keeps the background backoff escalating', async () => {
- const accountKey = accountKeyOf(ACCOUNT_B.userId);
- AccountAccess.markGatewayUnavailable(accountKey, new Error('gateway refused the session'));
-
- scriptedReplies.push(serverErrorReply());
- await expect(Accounts.switchToAccount(accountKey)).rejects.toBeInstanceOf(AccountInstanceUnavailableError);
-
- expect(scriptedRequestTokens).toContain(ACCOUNT_B.token);
- expect(AccountAccess.getRetryEligibleAt(accountKey) - Date.now()).toBeGreaterThan(10_000);
- expect(SessionManager.userId).toBe(ACCOUNT_A.userId);
- expect(mocks.leaveVoiceChannelForAccountExit).not.toHaveBeenCalled();
- });
-});
-
-describe('Accounts new account activation', () => {
- test('a new account replaces the active one and lands on the requested route', async () => {
- await Accounts.switchToNewAccount({
- userId: ACCOUNT_C.userId,
- token: ACCOUNT_C.token,
- runtimeSnapshot: BASE_SNAPSHOT,
- redirectPath: '/channels/@me',
- });
-
- expect(SessionManager.userId).toBe(ACCOUNT_C.userId);
- expect(SessionManager.token).toBe(ACCOUNT_C.token);
- expect(SessionManager.currentAccountKey).toBe(accountKeyOf(ACCOUNT_C.userId));
- expect(mocks.leaveVoiceChannelForAccountExit).toHaveBeenCalledWith({
- reason: 'account-switch',
- accountKey: accountKeyOf(ACCOUNT_A.userId),
- userId: ACCOUNT_A.userId,
- });
- expect(mocks.beginForegroundPromotion).toHaveBeenCalledWith(accountKeyOf(ACCOUNT_C.userId));
- expect(mocks.waitForForegroundReady).toHaveBeenLastCalledWith(accountKeyOf(ACCOUNT_C.userId));
- expect(mocks.replaceWith).toHaveBeenCalledWith('/channels/@me');
- });
-
- test('re-authenticating the active account rotates its token without promoting a gateway again', async () => {
- await Accounts.switchToNewAccount({
- userId: ACCOUNT_A.userId,
- token: 'rotated-token-a',
- runtimeSnapshot: BASE_SNAPSHOT,
- redirectPath: '/channels/@me',
- });
-
- expect(SessionManager.currentAccountKey).toBe(accountKeyOf(ACCOUNT_A.userId));
- expect(SessionManager.token).toBe('rotated-token-a');
- expect(Accounts.getAccount(accountKeyOf(ACCOUNT_A.userId))?.token).toBe('rotated-token-a');
- expect(mocks.beginForegroundPromotion).not.toHaveBeenCalled();
- expect(mocks.completeForegroundPromotion).not.toHaveBeenCalled();
- expect(mocks.leaveVoiceChannelForAccountExit).not.toHaveBeenCalled();
- expect(mocks.waitForForegroundReady).toHaveBeenLastCalledWith(accountKeyOf(ACCOUNT_A.userId));
- expect(mocks.replaceWith).toHaveBeenCalledWith('/channels/@me');
- });
-
- test('a rotated token is handed to the foreground gateway that is already ready for the account', async () => {
- mocks.foregroundAccountKey = accountKeyOf(ACCOUNT_A.userId);
- mocks.isForegroundReady = true;
-
- await Accounts.switchToNewAccount({
- userId: ACCOUNT_A.userId,
- token: 'rotated-token-a',
- runtimeSnapshot: BASE_SNAPSHOT,
- });
-
- expect(mocks.reuseReadyForegroundSession).toHaveBeenCalledWith(accountKeyOf(ACCOUNT_A.userId), 'rotated-token-a');
- expect(mocks.beginForegroundPromotion).not.toHaveBeenCalled();
- });
-
- test('a foreground gateway that is not ready yet is left to finish its own handshake', async () => {
- mocks.foregroundAccountKey = accountKeyOf(ACCOUNT_A.userId);
- mocks.isForegroundReady = false;
-
- await Accounts.switchToNewAccount({
- userId: ACCOUNT_A.userId,
- token: 'rotated-token-a',
- runtimeSnapshot: BASE_SNAPSHOT,
- });
-
- expect(mocks.reuseReadyForegroundSession).not.toHaveBeenCalled();
- expect(mocks.waitForForegroundReady).toHaveBeenLastCalledWith(accountKeyOf(ACCOUNT_A.userId));
- });
-
- test('a foreground gateway left attached to another account refuses the re-authentication', async () => {
- mocks.foregroundAccountKey = accountKeyOf(ACCOUNT_B.userId);
- mocks.isForegroundReady = true;
-
- await expect(
- Accounts.switchToNewAccount({
- userId: ACCOUNT_A.userId,
- token: 'rotated-token-a',
- runtimeSnapshot: BASE_SNAPSHOT,
- redirectPath: '/channels/@me',
- }),
- ).rejects.toThrow(
- `Foreground gateway ${accountKeyOf(ACCOUNT_B.userId)} remained attached after activating ${accountKeyOf(ACCOUNT_A.userId)}`,
- );
-
- expect(mocks.reuseReadyForegroundSession).not.toHaveBeenCalled();
- expect(mocks.waitForForegroundReady).not.toHaveBeenCalled();
- expect(mocks.replaceWith).not.toHaveBeenCalled();
- });
-});
-
-describe('Accounts push subscriptions on an installed PWA', () => {
- test('the outgoing account loses its push subscriptions before the incoming one is registered', async () => {
- mocks.isInstalledPwa = true;
- mocks.isGranted.mockResolvedValue(true);
- scriptedReplies.push(userMeReply(ACCOUNT_B.userId), userMeReply(ACCOUNT_B.userId));
-
- await Accounts.switchToAccount(accountKeyOf(ACCOUNT_B.userId), '/channels/@me');
- await flushPushRegistration();
-
- expect(mocks.unregisterAllPushSubscriptions).toHaveBeenCalledTimes(1);
- expect(mocks.registerPushSubscription).toHaveBeenCalledTimes(1);
- expect(mocks.unregisterAllPushSubscriptions.mock.invocationCallOrder[0]).toBeLessThan(
- mocks.waitForForegroundReady.mock.invocationCallOrder[0],
- );
- expect(mocks.registerPushSubscription.mock.invocationCallOrder[0]).toBeGreaterThan(
- mocks.waitForForegroundReady.mock.invocationCallOrder[0],
- );
- });
-
- test('a browser that never granted notifications is not asked for a push subscription', async () => {
- mocks.isInstalledPwa = true;
- mocks.isGranted.mockResolvedValue(false);
- scriptedReplies.push(userMeReply(ACCOUNT_B.userId), userMeReply(ACCOUNT_B.userId));
-
- await Accounts.switchToAccount(accountKeyOf(ACCOUNT_B.userId), '/channels/@me');
- await flushPushRegistration();
-
- expect(mocks.unregisterAllPushSubscriptions).toHaveBeenCalledTimes(1);
- expect(mocks.registerPushSubscription).not.toHaveBeenCalled();
- });
-
- test('an account that still owes a required action is never re-subscribed to push', async () => {
- mocks.isInstalledPwa = true;
- mocks.isGranted.mockResolvedValue(true);
- scriptedReplies.push(
- userMeReply(ACCOUNT_B.userId, ['REQUIRE_VERIFIED_EMAIL']),
- userMeReply(ACCOUNT_B.userId, ['REQUIRE_VERIFIED_EMAIL']),
- );
-
- await Accounts.switchToAccount(accountKeyOf(ACCOUNT_B.userId), '/channels/@me');
- await flushPushRegistration();
-
- expect(SessionManager.currentAccountKey).toBe(accountKeyOf(ACCOUNT_B.userId));
- expect(AccountAccess.currentPhase).toBe('action_required');
- expect(mocks.unregisterAllPushSubscriptions).toHaveBeenCalledTimes(1);
- expect(mocks.registerPushSubscription).not.toHaveBeenCalled();
- });
-
- test('a failed activation re-registers push for the account it rolled back to', async () => {
- mocks.isInstalledPwa = true;
- mocks.isGranted.mockResolvedValue(true);
- scriptedReplies.push(userMeReply(ACCOUNT_B.userId));
- mocks.completeForegroundPromotion.mockRejectedValueOnce(new SessionExpiredError());
-
- await expect(Accounts.switchToAccount(accountKeyOf(ACCOUNT_B.userId))).rejects.toBeInstanceOf(SessionExpiredError);
- await flushPushRegistration();
-
- expect(SessionManager.currentAccountKey).toBe(accountKeyOf(ACCOUNT_A.userId));
- expect(mocks.unregisterAllPushSubscriptions).toHaveBeenCalledTimes(1);
- expect(mocks.registerPushSubscription).toHaveBeenCalledTimes(1);
- });
-
- test('a browser tab that is not an installed PWA never touches push subscriptions', async () => {
- mocks.isGranted.mockResolvedValue(true);
- scriptedReplies.push(userMeReply(ACCOUNT_B.userId), userMeReply(ACCOUNT_B.userId));
-
- await Accounts.switchToAccount(accountKeyOf(ACCOUNT_B.userId), '/channels/@me');
- await flushPushRegistration();
-
- expect(mocks.unregisterAllPushSubscriptions).not.toHaveBeenCalled();
- expect(mocks.registerPushSubscription).not.toHaveBeenCalled();
- });
-});
-
-describe('Accounts account keys', () => {
- test('accounts are keyed by instance-qualified account key', () => {
- expect([...Accounts.accounts.keys()].sort()).toEqual([
- accountKeyOf(ACCOUNT_A.userId),
- accountKeyOf(ACCOUNT_B.userId),
- ]);
- });
-
- test('removing the current account leaves voice with the account-removed context', async () => {
- await Accounts.removeStoredAccount(accountKeyOf(ACCOUNT_A.userId));
- expect(mocks.leaveVoiceChannelForAccountExit).toHaveBeenCalledWith({
- reason: 'account-removed',
- accountKey: accountKeyOf(ACCOUNT_A.userId),
- userId: ACCOUNT_A.userId,
- });
- expect(Accounts.getAccount(accountKeyOf(ACCOUNT_A.userId))).toBeNull();
- });
-
- test('removing a background account never touches voice', async () => {
- await Accounts.removeStoredAccount(accountKeyOf(ACCOUNT_B.userId));
- expect(mocks.leaveVoiceChannelForAccountExit).not.toHaveBeenCalled();
- expect(SessionManager.userId).toBe(ACCOUNT_A.userId);
- });
-});
-
-describe('Accounts restriction handling', () => {
- test('a restricted account reaches voice only through the lifecycle boundary', async () => {
- await Accounts.suspendVoiceForAccountRestriction(accountKeyOf(ACCOUNT_A.userId));
- expect(mocks.suspendVoiceForAccountRestriction).toHaveBeenCalledWith({
- accountKey: accountKeyOf(ACCOUNT_A.userId),
- userId: ACCOUNT_A.userId,
- });
- expect(mocks.leaveVoiceChannelForAccountExit).not.toHaveBeenCalled();
- });
-
- test('a restriction reported for a background account never suspends the active account voice session', async () => {
- await Accounts.suspendVoiceForAccountRestriction(accountKeyOf(ACCOUNT_B.userId));
-
- expect(mocks.suspendVoiceForAccountRestriction).not.toHaveBeenCalled();
- expect(mocks.leaveVoiceChannelForAccountExit).not.toHaveBeenCalled();
- });
-
- test('a restriction reported for an account on another instance never suspends the active account voice session', async () => {
- await Accounts.suspendVoiceForAccountRestriction(`https://foreign.test/api::${ACCOUNT_A.userId}`);
-
- expect(mocks.suspendVoiceForAccountRestriction).not.toHaveBeenCalled();
- });
-});
-
-describe('Accounts logout', () => {
- test('logout leaves voice, ends the session and navigates to the login page', async () => {
- await Accounts.logout();
- expect(mocks.leaveVoiceChannelForAccountExit).toHaveBeenCalledWith({
- reason: 'logout',
- accountKey: accountKeyOf(ACCOUNT_A.userId),
- userId: ACCOUNT_A.userId,
- });
- expect(SessionManager.userId).toBeNull();
- expect(mocks.replaceWith).toHaveBeenCalledWith('/login');
- });
-
- test('a stored account left behind by the logout can still be activated', async () => {
- await Accounts.logout();
- expect(SessionManager.currentAccountKey).toBeNull();
- expect(Accounts.canSwitchAccounts).toBe(true);
-
- scriptedReplies.push(userMeReply(ACCOUNT_B.userId), userMeReply(ACCOUNT_B.userId));
- await Accounts.switchToAccount(accountKeyOf(ACCOUNT_B.userId), '/channels/@me');
-
- expect(SessionManager.userId).toBe(ACCOUNT_B.userId);
- expect(SessionManager.token).toBe(ACCOUNT_B.token);
- expect(mocks.waitForForegroundReady).toHaveBeenLastCalledWith(accountKeyOf(ACCOUNT_B.userId));
- expect(mocks.replaceWith).toHaveBeenLastCalledWith('/channels/@me');
- });
-});
diff --git a/fluxer_app/src/features/auth/state/__fixtures__/AccountSwitchHarness.ts b/fluxer_app/src/features/auth/state/__fixtures__/AccountSwitchHarness.ts
deleted file mode 100644
index f7b715b54..000000000
--- a/fluxer_app/src/features/auth/state/__fixtures__/AccountSwitchHarness.ts
+++ /dev/null
@@ -1,134 +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';
-
-export const HARNESS_API_ENDPOINT = 'https://primary.test/api';
-
-export interface ScriptedReply {
- status: number;
- body: unknown;
-}
-
-export const scriptedReplies: Array<ScriptedReply> = [];
-export const scriptedRequestTokens: Array<string | undefined> = [];
-export const scriptedRequestUrls: Array<string> = [];
-
-export function installHarnessBootstrap(): void {
- RuntimeConfig.applySnapshot(
- runtimeSnapshotFromDiscovery(
- parseInstanceDiscoveryDocument({
- api_code_version: Number.MAX_SAFE_INTEGER,
- endpoints: {
- api: HARNESS_API_ENDPOINT,
- api_client: HARNESS_API_ENDPOINT,
- api_public: HARNESS_API_ENDPOINT,
- gateway: 'wss://gateway.primary.test',
- media: 'https://media.primary.test',
- static_cdn: 'https://cdn.primary.test',
- marketing: 'https://primary.test',
- admin: 'https://admin.primary.test',
- invite: 'https://primary.test/invite',
- gift: 'https://primary.test/gift',
- webapp: 'https://app.primary.test',
- upload_relay: 'https://upload.primary.test',
- },
- captcha: {provider: 'none'},
- features: {
- voice_enabled: false,
- stripe_enabled: false,
- self_hosted: false,
- presigned_attachment_uploads: false,
- emails_enabled: false,
- },
- gif: {provider: 'klipy', display_name: 'Klipy', attribution_required: false},
- 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},
- services: {gif_enabled: true, youtube_enabled: false, bluesky_enabled: false},
- limits: {version: 1, traitDefinitions: [], rules: []},
- push: {public_vapid_key: null},
- app_public: {
- branding: {
- product_name: 'Fluxer',
- icon_url: null,
- symbol_url: null,
- logo_url: null,
- wordmark_url: null,
- favicon_url: null,
- theme_color: null,
- },
- setup: {configured: true, admin_url: null},
- legal: {terms_url: null, privacy_url: null},
- registration: {collect_date_of_birth: true},
- },
- }),
- ),
- );
-}
-
-export class ScriptedXMLHttpRequest extends EventTarget {
- readonly upload = new EventTarget();
- private readonly requestHeaders: Record<string, string> = {};
- status = 200;
- statusText = 'OK';
- responseText = '{}';
- response: unknown = '{}';
- responseType = '';
- timeout = 0;
-
- private requestUrl = '';
-
- open(_method: string, url: string): void {
- this.requestUrl = url;
- }
-
- setRequestHeader(name: string, value: string): void {
- this.requestHeaders[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 {
- scriptedRequestUrls.push(this.requestUrl);
- scriptedRequestTokens.push(this.requestHeaders.authorization);
- const reply = scriptedReplies.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'));
- });
- }
-}
-
-export function userMeReply(userId: string, requiredActions: ReadonlyArray<string> = []): ScriptedReply {
- return {
- status: 200,
- body: {id: userId, username: `user-${userId}`, required_actions: [...requiredActions]},
- };
-}
-
-export function unauthorizedReply(): ScriptedReply {
- return {status: 401, body: {code: 0, message: 'Unauthorized'}};
-}
-
-export function serverErrorReply(): ScriptedReply {
- return {status: 500, body: {code: 0, message: 'Internal server error'}};
-}
-
-export function resetScriptedTransport(): void {
- scriptedReplies.length = 0;
- scriptedRequestTokens.length = 0;
- scriptedRequestUrls.length = 0;
-}