mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-22 21:11:14 +00:00
fix(native): Prettier on the native client files, rate-limit e2e requests in sequence
Formats the files the client formatting gate listed, and NATIVE-E2E-005 sends its twenty exchange attempts one after another: all at once they reset the test server's connections.
This commit is contained in:
@@ -11,22 +11,22 @@
|
||||
* Android's adaptive icon masks the foreground to a circle inside the
|
||||
* canvas, so the mark there sits smaller than on the iOS tile.
|
||||
*/
|
||||
import { mkdirSync, readFileSync } from 'fs'
|
||||
import { dirname, join } from 'path'
|
||||
import { fileURLToPath } from 'url'
|
||||
import sharp from 'sharp'
|
||||
import { mkdirSync, readFileSync } from 'fs';
|
||||
import { dirname, join } from 'path';
|
||||
import sharp from 'sharp';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const clientDir = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const outDir = join(clientDir, 'assets')
|
||||
mkdirSync(outDir, { recursive: true })
|
||||
const clientDir = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const outDir = join(clientDir, 'assets');
|
||||
mkdirSync(outDir, { recursive: true });
|
||||
|
||||
const source = readFileSync(join(clientDir, 'public', 'icons', 'icon-white.svg'), 'utf8')
|
||||
const markPath = [...source.matchAll(/<path d="([^"]+)"/g)].map((m) => m[1]).find((d) => d.length > 500)
|
||||
if (!markPath) throw new Error('No mark path found in icon-white.svg')
|
||||
const source = readFileSync(join(clientDir, 'public', 'icons', 'icon-white.svg'), 'utf8');
|
||||
const markPath = [...source.matchAll(/<path d="([^"]+)"/g)].map((m) => m[1]).find((d) => d.length > 500);
|
||||
if (!markPath) throw new Error('No mark path found in icon-white.svg');
|
||||
// The mark's extent inside its 1500 x 1500 viewBox.
|
||||
const MARK = { x: 40, y: 5, w: 1420, h: 1490 }
|
||||
const MARK = { x: 40, y: 5, w: 1420, h: 1490 };
|
||||
|
||||
const LAUNCH_BG = '#09090b'
|
||||
const LAUNCH_BG = '#09090b';
|
||||
|
||||
function tile(size) {
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 1024 1024">
|
||||
@@ -55,16 +55,16 @@ function tile(size) {
|
||||
<rect width="1024" height="1024" fill="url(#depth)"/>
|
||||
<rect width="1024" height="1024" fill="url(#light)"/>
|
||||
<rect width="1024" height="1024" fill="url(#sheen)"/>
|
||||
</svg>`
|
||||
</svg>`;
|
||||
}
|
||||
|
||||
/** The white mark, `share` of the canvas tall, centred, with a soft shadow for depth. */
|
||||
function mark(size, share, shadow = true) {
|
||||
const scale = (1024 * share) / MARK.h
|
||||
const w = MARK.w * scale
|
||||
const h = MARK.h * scale
|
||||
const tx = (1024 - w) / 2 - MARK.x * scale
|
||||
const ty = (1024 - h) / 2 - MARK.y * scale
|
||||
const scale = (1024 * share) / MARK.h;
|
||||
const w = MARK.w * scale;
|
||||
const h = MARK.h * scale;
|
||||
const tx = (1024 - w) / 2 - MARK.x * scale;
|
||||
const ty = (1024 - h) / 2 - MARK.y * scale;
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 1024 1024">
|
||||
<defs>
|
||||
<linearGradient id="ink" x1="0" y1="0" x2="0" y2="1">
|
||||
@@ -78,27 +78,31 @@ function mark(size, share, shadow = true) {
|
||||
<g ${shadow ? 'filter="url(#lift)"' : ''}>
|
||||
<path transform="translate(${tx} ${ty}) scale(${scale})" fill="url(#ink)" d="${markPath}"/>
|
||||
</g>
|
||||
</svg>`
|
||||
</svg>`;
|
||||
}
|
||||
|
||||
async function render(svg, file) {
|
||||
await sharp(Buffer.from(svg)).png().toFile(join(outDir, file))
|
||||
await sharp(Buffer.from(svg)).png().toFile(join(outDir, file));
|
||||
}
|
||||
|
||||
async function composite(background, overlay, file, size) {
|
||||
const base = await sharp(Buffer.from(background)).resize(size, size).png().toBuffer()
|
||||
const top = await sharp(Buffer.from(overlay)).resize(size, size).png().toBuffer()
|
||||
await sharp(base).composite([{ input: top }]).flatten({ background: LAUNCH_BG }).png().toFile(join(outDir, file))
|
||||
const base = await sharp(Buffer.from(background)).resize(size, size).png().toBuffer();
|
||||
const top = await sharp(Buffer.from(overlay)).resize(size, size).png().toBuffer();
|
||||
await sharp(base)
|
||||
.composite([{ input: top }])
|
||||
.flatten({ background: LAUNCH_BG })
|
||||
.png()
|
||||
.toFile(join(outDir, file));
|
||||
}
|
||||
|
||||
// iOS and store listings: one opaque tile, the mark at about half its height.
|
||||
await composite(tile(1024), mark(1024, 0.5), 'icon-only.png', 1024)
|
||||
await composite(tile(1024), mark(1024, 0.5), 'icon-only.png', 1024);
|
||||
// Android adaptive icon: the two layers apart, the mark inside the safe circle.
|
||||
await render(tile(1024), 'icon-background.png')
|
||||
await render(mark(1024, 0.58), 'icon-foreground.png')
|
||||
await render(tile(1024), 'icon-background.png');
|
||||
await render(mark(1024, 0.58), 'icon-foreground.png');
|
||||
// Splash: the launch background with the mark, light and dark alike.
|
||||
const splashBg = `<svg xmlns="http://www.w3.org/2000/svg" width="2732" height="2732"><rect width="2732" height="2732" fill="${LAUNCH_BG}"/></svg>`
|
||||
await composite(splashBg, mark(2732, 0.2, false), 'splash.png', 2732)
|
||||
await composite(splashBg, mark(2732, 0.2, false), 'splash-dark.png', 2732)
|
||||
const splashBg = `<svg xmlns="http://www.w3.org/2000/svg" width="2732" height="2732"><rect width="2732" height="2732" fill="${LAUNCH_BG}"/></svg>`;
|
||||
await composite(splashBg, mark(2732, 0.2, false), 'splash.png', 2732);
|
||||
await composite(splashBg, mark(2732, 0.2, false), 'splash-dark.png', 2732);
|
||||
|
||||
console.log(`[app-icons] wrote icon and splash sources to ${outDir}`)
|
||||
console.log(`[app-icons] wrote icon and splash sources to ${outDir}`);
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
*/
|
||||
import { mkdirSync } from 'fs';
|
||||
import { dirname, join } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import sharp from 'sharp';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const clientDir = join(__dirname, '..');
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { nativeAuthApi } from './nativeAuth'
|
||||
import { apiClient } from './client'
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { apiClient } from './client';
|
||||
import { nativeAuthApi } from './nativeAuth';
|
||||
|
||||
vi.mock('./client', () => ({ apiClient: { post: vi.fn() } }))
|
||||
vi.mock('./client', () => ({ apiClient: { post: vi.fn() } }));
|
||||
|
||||
describe('nativeAuthApi', () => {
|
||||
it('mints a hand-off code for a challenge', async () => {
|
||||
vi.mocked(apiClient.post).mockResolvedValue({ data: { code: 'c1' } })
|
||||
await expect(nativeAuthApi.handoff('ab'.repeat(32))).resolves.toEqual({ code: 'c1' })
|
||||
expect(apiClient.post).toHaveBeenCalledWith('/auth/native/handoff', { challenge: 'ab'.repeat(32) })
|
||||
})
|
||||
vi.mocked(apiClient.post).mockResolvedValue({ data: { code: 'c1' } });
|
||||
await expect(nativeAuthApi.handoff('ab'.repeat(32))).resolves.toEqual({ code: 'c1' });
|
||||
expect(apiClient.post).toHaveBeenCalledWith('/auth/native/handoff', { challenge: 'ab'.repeat(32) });
|
||||
});
|
||||
|
||||
it('redeems the code with its verifier', async () => {
|
||||
vi.mocked(apiClient.post).mockResolvedValue({ data: { ok: true } })
|
||||
await expect(nativeAuthApi.exchange({ code: 'c1', verifier: 'v'.repeat(64) })).resolves.toBeUndefined()
|
||||
expect(apiClient.post).toHaveBeenCalledWith('/auth/native/exchange', { code: 'c1', verifier: 'v'.repeat(64) })
|
||||
})
|
||||
})
|
||||
vi.mocked(apiClient.post).mockResolvedValue({ data: { ok: true } });
|
||||
await expect(nativeAuthApi.exchange({ code: 'c1', verifier: 'v'.repeat(64) })).resolves.toBeUndefined();
|
||||
expect(apiClient.post).toHaveBeenCalledWith('/auth/native/exchange', { code: 'c1', verifier: 'v'.repeat(64) });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { NativeExchangeRequest, NativeHandoffResponse } from '@trek/shared'
|
||||
import { apiClient } from './client'
|
||||
import type { NativeExchangeRequest, NativeHandoffResponse } from '@trek/shared';
|
||||
import { apiClient } from './client';
|
||||
|
||||
/** The two halves of the sign-in hand-off between system browser and app. */
|
||||
export const nativeAuthApi = {
|
||||
@@ -9,4 +9,4 @@ export const nativeAuthApi = {
|
||||
/** App side: redeem the code with the verifier; the response sets the session cookie. */
|
||||
exchange: (body: NativeExchangeRequest): Promise<void> =>
|
||||
apiClient.post('/auth/native/exchange', body).then(() => undefined),
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,49 +1,49 @@
|
||||
// FE-SETTINGS-NATIVE-SERVER-001 to FE-SETTINGS-NATIVE-SERVER-006
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent } from '../../../tests/helpers/render'
|
||||
import NativeServerSection from './NativeServerSection'
|
||||
import MSettingsServer from '../../mobile/screens/settings/MSettingsServer'
|
||||
import NativeServerLink from '../../pages/login/NativeServerLink'
|
||||
import { nativeServerHost } from '../../native/platform'
|
||||
import { TrekShell } from '../../native/trekShell'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import MSettingsServer from '../../mobile/screens/settings/MSettingsServer';
|
||||
import { nativeServerHost } from '../../native/platform';
|
||||
import { TrekShell } from '../../native/trekShell';
|
||||
import NativeServerLink from '../../pages/login/NativeServerLink';
|
||||
import NativeServerSection from './NativeServerSection';
|
||||
|
||||
vi.mock('../../native/platform', () => ({ nativeServerHost: vi.fn() }))
|
||||
vi.mock('../../native/trekShell', () => ({ TrekShell: { resetServer: vi.fn() } }))
|
||||
vi.mock('../../native/platform', () => ({ nativeServerHost: vi.fn() }));
|
||||
vi.mock('../../native/trekShell', () => ({ TrekShell: { resetServer: vi.fn() } }));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(TrekShell.resetServer).mockReset().mockResolvedValue()
|
||||
})
|
||||
vi.mocked(TrekShell.resetServer).mockReset().mockResolvedValue();
|
||||
});
|
||||
|
||||
describe.each([
|
||||
['desktop', NativeServerSection],
|
||||
['mobile', MSettingsServer],
|
||||
])('the %s server section', (_shell, Section) => {
|
||||
it('renders nothing in a browser', () => {
|
||||
vi.mocked(nativeServerHost).mockReturnValue(null)
|
||||
const { container } = render(<Section />)
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
})
|
||||
vi.mocked(nativeServerHost).mockReturnValue(null);
|
||||
const { container } = render(<Section />);
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
it('names the server and leads back to the address screen', () => {
|
||||
vi.mocked(nativeServerHost).mockReturnValue('trek.example.com')
|
||||
render(<Section />)
|
||||
expect(screen.getByText('This app is connected to trek.example.com.')).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Change server' }))
|
||||
expect(TrekShell.resetServer).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
vi.mocked(nativeServerHost).mockReturnValue('trek.example.com');
|
||||
render(<Section />);
|
||||
expect(screen.getByText('This app is connected to trek.example.com.')).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Change server' }));
|
||||
expect(TrekShell.resetServer).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('the sign-in screen link', () => {
|
||||
it('renders nothing in a browser', () => {
|
||||
vi.mocked(nativeServerHost).mockReturnValue(null)
|
||||
const { container } = render(<NativeServerLink />)
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
})
|
||||
vi.mocked(nativeServerHost).mockReturnValue(null);
|
||||
const { container } = render(<NativeServerLink />);
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
it('leads back to the address screen in the app', () => {
|
||||
vi.mocked(nativeServerHost).mockReturnValue('trek.example.com')
|
||||
render(<NativeServerLink />)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Change server' }))
|
||||
expect(TrekShell.resetServer).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
vi.mocked(nativeServerHost).mockReturnValue('trek.example.com');
|
||||
render(<NativeServerLink />);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Change server' }));
|
||||
expect(TrekShell.resetServer).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,7 +11,7 @@ export default function MSettingsServer() {
|
||||
if (!host) return null;
|
||||
return (
|
||||
<MSetCard title={t('native.settings.server')} icon={Server} className="mb-3">
|
||||
<MSetHint className="mt-0 mb-3">{t('native.settings.serverHint', { server: host })}</MSetHint>
|
||||
<MSetHint className="mb-3 mt-0">{t('native.settings.serverHint', { server: host })}</MSetHint>
|
||||
<MSetButton variant="ghost" onClick={changeServer}>
|
||||
{t('native.changeServer')}
|
||||
</MSetButton>
|
||||
|
||||
@@ -1,71 +1,79 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { sha256 } from '@noble/hashes/sha2'
|
||||
import { bytesToHex } from '@noble/hashes/utils'
|
||||
import { BrowserSignInCancelled, createHandoffSecret, handoffUrl, requestHandoffCode, signInThroughBrowser } from './browserSignIn'
|
||||
import { TrekShell } from './trekShell'
|
||||
import { nativeAuthApi } from '../api/nativeAuth'
|
||||
import { sha256 } from '@noble/hashes/sha2';
|
||||
import { bytesToHex } from '@noble/hashes/utils';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { nativeAuthApi } from '../api/nativeAuth';
|
||||
import {
|
||||
BrowserSignInCancelled,
|
||||
createHandoffSecret,
|
||||
handoffUrl,
|
||||
requestHandoffCode,
|
||||
signInThroughBrowser,
|
||||
} from './browserSignIn';
|
||||
import { TrekShell } from './trekShell';
|
||||
|
||||
vi.mock('./trekShell', () => ({ APP_URL_SCHEME: 'com.liketrek.trek', TrekShell: { authenticate: vi.fn() } }))
|
||||
vi.mock('../api/nativeAuth', () => ({ nativeAuthApi: { exchange: vi.fn(), handoff: vi.fn() } }))
|
||||
vi.mock('./trekShell', () => ({ APP_URL_SCHEME: 'com.liketrek.trek', TrekShell: { authenticate: vi.fn() } }));
|
||||
vi.mock('../api/nativeAuth', () => ({ nativeAuthApi: { exchange: vi.fn(), handoff: vi.fn() } }));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(TrekShell.authenticate).mockReset()
|
||||
vi.mocked(nativeAuthApi.exchange).mockReset().mockResolvedValue()
|
||||
})
|
||||
vi.mocked(TrekShell.authenticate).mockReset();
|
||||
vi.mocked(nativeAuthApi.exchange).mockReset().mockResolvedValue();
|
||||
});
|
||||
|
||||
describe('createHandoffSecret', () => {
|
||||
it('pairs a fresh 64-character verifier with the hex sha256 the server checks against', () => {
|
||||
const { verifier, challenge } = createHandoffSecret()
|
||||
expect(verifier).toMatch(/^[0-9a-f]{64}$/)
|
||||
expect(challenge).toBe(bytesToHex(sha256(new TextEncoder().encode(verifier))))
|
||||
expect(createHandoffSecret().verifier).not.toBe(verifier)
|
||||
})
|
||||
})
|
||||
const { verifier, challenge } = createHandoffSecret();
|
||||
expect(verifier).toMatch(/^[0-9a-f]{64}$/);
|
||||
expect(challenge).toBe(bytesToHex(sha256(new TextEncoder().encode(verifier))));
|
||||
expect(createHandoffSecret().verifier).not.toBe(verifier);
|
||||
});
|
||||
});
|
||||
|
||||
describe('requestHandoffCode', () => {
|
||||
it('asks the server for the one-time code bound to the challenge', async () => {
|
||||
vi.mocked(nativeAuthApi.handoff).mockResolvedValue({ code: 'c-1' })
|
||||
await expect(requestHandoffCode('ab'.repeat(32))).resolves.toBe('c-1')
|
||||
expect(nativeAuthApi.handoff).toHaveBeenCalledWith('ab'.repeat(32))
|
||||
})
|
||||
})
|
||||
vi.mocked(nativeAuthApi.handoff).mockResolvedValue({ code: 'c-1' });
|
||||
await expect(requestHandoffCode('ab'.repeat(32))).resolves.toBe('c-1');
|
||||
expect(nativeAuthApi.handoff).toHaveBeenCalledWith('ab'.repeat(32));
|
||||
});
|
||||
});
|
||||
|
||||
describe('handoffUrl', () => {
|
||||
it('points at the hand-off page with the challenge and an optional start', () => {
|
||||
expect(handoffUrl('https://trek.example.com', 'c')).toBe('https://trek.example.com/native-handoff?challenge=c')
|
||||
expect(handoffUrl('https://trek.example.com', 'c', 'oidc')).toBe('https://trek.example.com/native-handoff?challenge=c&start=oidc')
|
||||
})
|
||||
})
|
||||
expect(handoffUrl('https://trek.example.com', 'c')).toBe('https://trek.example.com/native-handoff?challenge=c');
|
||||
expect(handoffUrl('https://trek.example.com', 'c', 'oidc')).toBe(
|
||||
'https://trek.example.com/native-handoff?challenge=c&start=oidc'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('signInThroughBrowser', () => {
|
||||
it('opens the hand-off page and redeems the returned code with the verifier', async () => {
|
||||
vi.mocked(TrekShell.authenticate).mockResolvedValue({ url: 'com.liketrek.trek://auth?code=abc' })
|
||||
vi.mocked(TrekShell.authenticate).mockResolvedValue({ url: 'com.liketrek.trek://auth?code=abc' });
|
||||
|
||||
await signInThroughBrowser('oidc')
|
||||
await signInThroughBrowser('oidc');
|
||||
|
||||
const opened = new URL(vi.mocked(TrekShell.authenticate).mock.calls[0][0].url)
|
||||
expect(opened.pathname).toBe('/native-handoff')
|
||||
expect(opened.searchParams.get('start')).toBe('oidc')
|
||||
expect(vi.mocked(TrekShell.authenticate).mock.calls[0][0].callbackScheme).toBe('com.liketrek.trek')
|
||||
const { code, verifier } = vi.mocked(nativeAuthApi.exchange).mock.calls[0][0]
|
||||
expect(code).toBe('abc')
|
||||
expect(bytesToHex(sha256(new TextEncoder().encode(verifier)))).toBe(opened.searchParams.get('challenge'))
|
||||
})
|
||||
const opened = new URL(vi.mocked(TrekShell.authenticate).mock.calls[0][0].url);
|
||||
expect(opened.pathname).toBe('/native-handoff');
|
||||
expect(opened.searchParams.get('start')).toBe('oidc');
|
||||
expect(vi.mocked(TrekShell.authenticate).mock.calls[0][0].callbackScheme).toBe('com.liketrek.trek');
|
||||
const { code, verifier } = vi.mocked(nativeAuthApi.exchange).mock.calls[0][0];
|
||||
expect(code).toBe('abc');
|
||||
expect(bytesToHex(sha256(new TextEncoder().encode(verifier)))).toBe(opened.searchParams.get('challenge'));
|
||||
});
|
||||
|
||||
it('turns a closed browser into BrowserSignInCancelled', async () => {
|
||||
vi.mocked(TrekShell.authenticate).mockRejectedValue(Object.assign(new Error('closed'), { code: 'CANCELLED' }))
|
||||
await expect(signInThroughBrowser()).rejects.toBeInstanceOf(BrowserSignInCancelled)
|
||||
expect(nativeAuthApi.exchange).not.toHaveBeenCalled()
|
||||
})
|
||||
vi.mocked(TrekShell.authenticate).mockRejectedValue(Object.assign(new Error('closed'), { code: 'CANCELLED' }));
|
||||
await expect(signInThroughBrowser()).rejects.toBeInstanceOf(BrowserSignInCancelled);
|
||||
expect(nativeAuthApi.exchange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('passes other failures on', async () => {
|
||||
vi.mocked(TrekShell.authenticate).mockRejectedValue(new Error('no browser'))
|
||||
await expect(signInThroughBrowser()).rejects.toThrow('no browser')
|
||||
})
|
||||
vi.mocked(TrekShell.authenticate).mockRejectedValue(new Error('no browser'));
|
||||
await expect(signInThroughBrowser()).rejects.toThrow('no browser');
|
||||
});
|
||||
|
||||
it('refuses a return without a code', async () => {
|
||||
vi.mocked(TrekShell.authenticate).mockResolvedValue({ url: 'com.liketrek.trek://auth' })
|
||||
await expect(signInThroughBrowser()).rejects.toThrow('without a sign-in code')
|
||||
expect(nativeAuthApi.exchange).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
vi.mocked(TrekShell.authenticate).mockResolvedValue({ url: 'com.liketrek.trek://auth' });
|
||||
await expect(signInThroughBrowser()).rejects.toThrow('without a sign-in code');
|
||||
expect(nativeAuthApi.exchange).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { sha256 } from '@noble/hashes/sha2'
|
||||
import { bytesToHex } from '@noble/hashes/utils'
|
||||
import { nativeAuthApi } from '../api/nativeAuth'
|
||||
import { APP_URL_SCHEME, TrekShell } from './trekShell'
|
||||
import { sha256 } from '@noble/hashes/sha2';
|
||||
import { bytesToHex } from '@noble/hashes/utils';
|
||||
import { nativeAuthApi } from '../api/nativeAuth';
|
||||
import { APP_URL_SCHEME, TrekShell } from './trekShell';
|
||||
|
||||
/**
|
||||
* SSO and passkeys cannot run inside the app's WebView: identity providers
|
||||
@@ -17,51 +17,51 @@ import { APP_URL_SCHEME, TrekShell } from './trekShell'
|
||||
* home networks reach theirs.
|
||||
*/
|
||||
|
||||
export const HANDOFF_PATH = '/native-handoff'
|
||||
export const HANDOFF_PATH = '/native-handoff';
|
||||
|
||||
export type BrowserSignInStart = 'oidc'
|
||||
export type BrowserSignInStart = 'oidc';
|
||||
|
||||
export function createHandoffSecret(): { verifier: string; challenge: string } {
|
||||
const bytes = crypto.getRandomValues(new Uint8Array(32))
|
||||
const verifier = bytesToHex(bytes)
|
||||
return { verifier, challenge: bytesToHex(sha256(new TextEncoder().encode(verifier))) }
|
||||
const bytes = crypto.getRandomValues(new Uint8Array(32));
|
||||
const verifier = bytesToHex(bytes);
|
||||
return { verifier, challenge: bytesToHex(sha256(new TextEncoder().encode(verifier))) };
|
||||
}
|
||||
|
||||
export function handoffUrl(origin: string, challenge: string, start?: BrowserSignInStart, invite?: string): string {
|
||||
const url = new URL(HANDOFF_PATH, origin)
|
||||
url.searchParams.set('challenge', challenge)
|
||||
if (start) url.searchParams.set('start', start)
|
||||
if (invite) url.searchParams.set('invite', invite)
|
||||
return url.href
|
||||
const url = new URL(HANDOFF_PATH, origin);
|
||||
url.searchParams.set('challenge', challenge);
|
||||
if (start) url.searchParams.set('start', start);
|
||||
if (invite) url.searchParams.set('invite', invite);
|
||||
return url.href;
|
||||
}
|
||||
|
||||
/** The browser side: trade the signed-in session for a one-time code bound to `challenge`. */
|
||||
export async function requestHandoffCode(challenge: string): Promise<string> {
|
||||
const { code } = await nativeAuthApi.handoff(challenge)
|
||||
return code
|
||||
const { code } = await nativeAuthApi.handoff(challenge);
|
||||
return code;
|
||||
}
|
||||
|
||||
export class BrowserSignInCancelled extends Error {
|
||||
constructor() {
|
||||
super('Sign-in cancelled')
|
||||
this.name = 'BrowserSignInCancelled'
|
||||
super('Sign-in cancelled');
|
||||
this.name = 'BrowserSignInCancelled';
|
||||
}
|
||||
}
|
||||
|
||||
/** Resolves once the WebView holds a session cookie of its own. */
|
||||
export async function signInThroughBrowser(start?: BrowserSignInStart, invite?: string): Promise<void> {
|
||||
const { verifier, challenge } = createHandoffSecret()
|
||||
let returned: string
|
||||
const { verifier, challenge } = createHandoffSecret();
|
||||
let returned: string;
|
||||
try {
|
||||
;({ url: returned } = await TrekShell.authenticate({
|
||||
({ url: returned } = await TrekShell.authenticate({
|
||||
url: handoffUrl(window.location.origin, challenge, start, invite),
|
||||
callbackScheme: APP_URL_SCHEME,
|
||||
}))
|
||||
}));
|
||||
} catch (err) {
|
||||
if ((err as { code?: string })?.code === 'CANCELLED') throw new BrowserSignInCancelled()
|
||||
throw err
|
||||
if ((err as { code?: string })?.code === 'CANCELLED') throw new BrowserSignInCancelled();
|
||||
throw err;
|
||||
}
|
||||
const code = new URL(returned).searchParams.get('code')
|
||||
if (!code) throw new Error('The browser returned without a sign-in code')
|
||||
await nativeAuthApi.exchange({ code, verifier })
|
||||
const code = new URL(returned).searchParams.get('code');
|
||||
if (!code) throw new Error('The browser returned without a sign-in code');
|
||||
await nativeAuthApi.exchange({ code, verifier });
|
||||
}
|
||||
|
||||
@@ -1,42 +1,44 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { Haptics, NotificationType } from '@capacitor/haptics'
|
||||
import { toastHaptic } from './haptics'
|
||||
import { isNativeApp } from './platform'
|
||||
import { Haptics, NotificationType } from '@capacitor/haptics';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { toastHaptic } from './haptics';
|
||||
import { isNativeApp } from './platform';
|
||||
|
||||
vi.mock('@capacitor/haptics', () => ({
|
||||
Haptics: { notification: vi.fn() },
|
||||
NotificationType: { Success: 'SUCCESS', Warning: 'WARNING', Error: 'ERROR' },
|
||||
}))
|
||||
vi.mock('./platform', () => ({ isNativeApp: vi.fn() }))
|
||||
}));
|
||||
vi.mock('./platform', () => ({ isNativeApp: vi.fn() }));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(Haptics.notification).mockReset().mockResolvedValue()
|
||||
vi.mocked(isNativeApp).mockReturnValue(true)
|
||||
})
|
||||
vi.mocked(Haptics.notification).mockReset().mockResolvedValue();
|
||||
vi.mocked(isNativeApp).mockReturnValue(true);
|
||||
});
|
||||
|
||||
describe('toastHaptic', () => {
|
||||
it('taps for success, warning and error toasts in the app', () => {
|
||||
toastHaptic('success')
|
||||
toastHaptic('warning')
|
||||
toastHaptic('error')
|
||||
toastHaptic('success');
|
||||
toastHaptic('warning');
|
||||
toastHaptic('error');
|
||||
expect(vi.mocked(Haptics.notification).mock.calls.map(([o]) => o?.type)).toEqual([
|
||||
NotificationType.Success, NotificationType.Warning, NotificationType.Error,
|
||||
])
|
||||
})
|
||||
NotificationType.Success,
|
||||
NotificationType.Warning,
|
||||
NotificationType.Error,
|
||||
]);
|
||||
});
|
||||
|
||||
it('stays still for info toasts and in a browser', () => {
|
||||
toastHaptic('info')
|
||||
vi.mocked(isNativeApp).mockReturnValue(false)
|
||||
toastHaptic('success')
|
||||
expect(Haptics.notification).not.toHaveBeenCalled()
|
||||
})
|
||||
toastHaptic('info');
|
||||
vi.mocked(isNativeApp).mockReturnValue(false);
|
||||
toastHaptic('success');
|
||||
expect(Haptics.notification).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not let a missing vibrator surface as an error', async () => {
|
||||
const report = vi.fn()
|
||||
vi.stubGlobal('reportError', report)
|
||||
vi.mocked(Haptics.notification).mockRejectedValue(new Error('not available'))
|
||||
toastHaptic('error')
|
||||
await vi.waitFor(() => expect(report).toHaveBeenCalledWith(expect.any(Error)))
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
})
|
||||
const report = vi.fn();
|
||||
vi.stubGlobal('reportError', report);
|
||||
vi.mocked(Haptics.notification).mockRejectedValue(new Error('not available'));
|
||||
toastHaptic('error');
|
||||
await vi.waitFor(() => expect(report).toHaveBeenCalledWith(expect.any(Error)));
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { Haptics, NotificationType } from '@capacitor/haptics'
|
||||
import { isNativeApp } from './platform'
|
||||
import { reportNativeFailure } from './reportFailure'
|
||||
import { Haptics, NotificationType } from '@capacitor/haptics';
|
||||
import { isNativeApp } from './platform';
|
||||
import { reportNativeFailure } from './reportFailure';
|
||||
|
||||
const FEEDBACK: Record<string, NotificationType | undefined> = {
|
||||
success: NotificationType.Success,
|
||||
warning: NotificationType.Warning,
|
||||
error: NotificationType.Error,
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* The short tap a native app gives when something saved, warned or failed.
|
||||
@@ -14,7 +14,7 @@ const FEEDBACK: Record<string, NotificationType | undefined> = {
|
||||
* one; plain info toasts stay silent. Does nothing in a browser.
|
||||
*/
|
||||
export function toastHaptic(type: string): void {
|
||||
const feedback = FEEDBACK[type]
|
||||
if (!feedback || !isNativeApp()) return
|
||||
Haptics.notification({ type: feedback }).catch(reportNativeFailure)
|
||||
const feedback = FEEDBACK[type];
|
||||
if (!feedback || !isNativeApp()) return;
|
||||
Haptics.notification({ type: feedback }).catch(reportNativeFailure);
|
||||
}
|
||||
|
||||
@@ -1,109 +1,109 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { App } from '@capacitor/app'
|
||||
import { Keyboard } from '@capacitor/keyboard'
|
||||
import { SplashScreen } from '@capacitor/splash-screen'
|
||||
import { StatusBar, Style } from '@capacitor/status-bar'
|
||||
import { startNativeApp } from './nativeApp'
|
||||
import { isNativeApp, isNativeIos } from './platform'
|
||||
import { keepOfflineShellFresh } from './offlineShell'
|
||||
import { isEffectivelyOffline } from '../sync/networkMode'
|
||||
import { App } from '@capacitor/app';
|
||||
import { Keyboard } from '@capacitor/keyboard';
|
||||
import { SplashScreen } from '@capacitor/splash-screen';
|
||||
import { StatusBar, Style } from '@capacitor/status-bar';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { isEffectivelyOffline } from '../sync/networkMode';
|
||||
import { startNativeApp } from './nativeApp';
|
||||
import { keepOfflineShellFresh } from './offlineShell';
|
||||
import { isNativeApp, isNativeIos } from './platform';
|
||||
|
||||
vi.mock('@capacitor/app', () => ({ App: { addListener: vi.fn(), minimizeApp: vi.fn() } }))
|
||||
vi.mock('@capacitor/keyboard', () => ({ Keyboard: { setAccessoryBarVisible: vi.fn() } }))
|
||||
vi.mock('@capacitor/splash-screen', () => ({ SplashScreen: { hide: vi.fn() } }))
|
||||
vi.mock('@capacitor/status-bar', () => ({ StatusBar: { setStyle: vi.fn() }, Style: { Dark: 'DARK', Light: 'LIGHT' } }))
|
||||
vi.mock('./platform', () => ({ isNativeApp: vi.fn(), isNativeIos: vi.fn() }))
|
||||
vi.mock('./offlineShell', () => ({ keepOfflineShellFresh: vi.fn() }))
|
||||
vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn() }))
|
||||
vi.mock('@capacitor/app', () => ({ App: { addListener: vi.fn(), minimizeApp: vi.fn() } }));
|
||||
vi.mock('@capacitor/keyboard', () => ({ Keyboard: { setAccessoryBarVisible: vi.fn() } }));
|
||||
vi.mock('@capacitor/splash-screen', () => ({ SplashScreen: { hide: vi.fn() } }));
|
||||
vi.mock('@capacitor/status-bar', () => ({ StatusBar: { setStyle: vi.fn() }, Style: { Dark: 'DARK', Light: 'LIGHT' } }));
|
||||
vi.mock('./platform', () => ({ isNativeApp: vi.fn(), isNativeIos: vi.fn() }));
|
||||
vi.mock('./offlineShell', () => ({ keepOfflineShellFresh: vi.fn() }));
|
||||
vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn() }));
|
||||
|
||||
function backButtonHandler(): (event: { canGoBack: boolean }) => void {
|
||||
const call = vi.mocked(App.addListener).mock.calls.find(([name]) => name === 'backButton')
|
||||
if (!call) throw new Error('no backButton listener')
|
||||
return call[1] as unknown as (event: { canGoBack: boolean }) => void
|
||||
const call = vi.mocked(App.addListener).mock.calls.find(([name]) => name === 'backButton');
|
||||
if (!call) throw new Error('no backButton listener');
|
||||
return call[1] as unknown as (event: { canGoBack: boolean }) => void;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(isNativeApp).mockReturnValue(true)
|
||||
vi.mocked(isNativeIos).mockReturnValue(false)
|
||||
vi.mocked(isEffectivelyOffline).mockReturnValue(false)
|
||||
vi.mocked(keepOfflineShellFresh).mockResolvedValue()
|
||||
document.documentElement.classList.remove('dark')
|
||||
})
|
||||
vi.useFakeTimers();
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(isNativeApp).mockReturnValue(true);
|
||||
vi.mocked(isNativeIos).mockReturnValue(false);
|
||||
vi.mocked(isEffectivelyOffline).mockReturnValue(false);
|
||||
vi.mocked(keepOfflineShellFresh).mockResolvedValue();
|
||||
document.documentElement.classList.remove('dark');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('startNativeApp', () => {
|
||||
it('does nothing in a browser', () => {
|
||||
vi.mocked(isNativeApp).mockReturnValue(false)
|
||||
startNativeApp()
|
||||
expect(App.addListener).not.toHaveBeenCalled()
|
||||
expect(StatusBar.setStyle).not.toHaveBeenCalled()
|
||||
})
|
||||
vi.mocked(isNativeApp).mockReturnValue(false);
|
||||
startNativeApp();
|
||||
expect(App.addListener).not.toHaveBeenCalled();
|
||||
expect(StatusBar.setStyle).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('hides the splash after the first frame', () => {
|
||||
startNativeApp()
|
||||
vi.runOnlyPendingTimers()
|
||||
expect(SplashScreen.hide).toHaveBeenCalled()
|
||||
})
|
||||
startNativeApp();
|
||||
vi.runOnlyPendingTimers();
|
||||
expect(SplashScreen.hide).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('walks back through history before it leaves the app', () => {
|
||||
const back = vi.spyOn(window.history, 'back').mockImplementation(() => {})
|
||||
startNativeApp()
|
||||
backButtonHandler()({ canGoBack: true })
|
||||
expect(back).toHaveBeenCalled()
|
||||
backButtonHandler()({ canGoBack: false })
|
||||
expect(App.minimizeApp).toHaveBeenCalled()
|
||||
})
|
||||
const back = vi.spyOn(window.history, 'back').mockImplementation(() => {});
|
||||
startNativeApp();
|
||||
backButtonHandler()({ canGoBack: true });
|
||||
expect(back).toHaveBeenCalled();
|
||||
backButtonHandler()({ canGoBack: false });
|
||||
expect(App.minimizeApp).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps the status bar icons readable when the scheme changes', async () => {
|
||||
startNativeApp()
|
||||
expect(StatusBar.setStyle).toHaveBeenLastCalledWith({ style: Style.Light })
|
||||
document.documentElement.classList.add('dark')
|
||||
await vi.waitFor(() => expect(StatusBar.setStyle).toHaveBeenLastCalledWith({ style: Style.Dark }))
|
||||
})
|
||||
startNativeApp();
|
||||
expect(StatusBar.setStyle).toHaveBeenLastCalledWith({ style: Style.Light });
|
||||
document.documentElement.classList.add('dark');
|
||||
await vi.waitFor(() => expect(StatusBar.setStyle).toHaveBeenLastCalledWith({ style: Style.Dark }));
|
||||
});
|
||||
|
||||
it('hides the keyboard accessory bar on iOS only', () => {
|
||||
startNativeApp()
|
||||
expect(Keyboard.setAccessoryBarVisible).not.toHaveBeenCalled()
|
||||
vi.mocked(isNativeIos).mockReturnValue(true)
|
||||
startNativeApp()
|
||||
expect(Keyboard.setAccessoryBarVisible).toHaveBeenCalledWith({ isVisible: false })
|
||||
})
|
||||
startNativeApp();
|
||||
expect(Keyboard.setAccessoryBarVisible).not.toHaveBeenCalled();
|
||||
vi.mocked(isNativeIos).mockReturnValue(true);
|
||||
startNativeApp();
|
||||
expect(Keyboard.setAccessoryBarVisible).toHaveBeenCalledWith({ isVisible: false });
|
||||
});
|
||||
|
||||
it('refreshes the offline start on iOS once the first screen has settled', () => {
|
||||
vi.mocked(isNativeIos).mockReturnValue(true)
|
||||
startNativeApp()
|
||||
expect(keepOfflineShellFresh).not.toHaveBeenCalled()
|
||||
vi.advanceTimersByTime(15_000)
|
||||
expect(keepOfflineShellFresh).toHaveBeenCalled()
|
||||
})
|
||||
vi.mocked(isNativeIos).mockReturnValue(true);
|
||||
startNativeApp();
|
||||
expect(keepOfflineShellFresh).not.toHaveBeenCalled();
|
||||
vi.advanceTimersByTime(15_000);
|
||||
expect(keepOfflineShellFresh).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('skips the refresh while offline, and never on Android', () => {
|
||||
vi.mocked(isNativeIos).mockReturnValue(true)
|
||||
vi.mocked(isEffectivelyOffline).mockReturnValue(true)
|
||||
startNativeApp()
|
||||
vi.advanceTimersByTime(15_000)
|
||||
expect(keepOfflineShellFresh).not.toHaveBeenCalled()
|
||||
vi.mocked(isNativeIos).mockReturnValue(true);
|
||||
vi.mocked(isEffectivelyOffline).mockReturnValue(true);
|
||||
startNativeApp();
|
||||
vi.advanceTimersByTime(15_000);
|
||||
expect(keepOfflineShellFresh).not.toHaveBeenCalled();
|
||||
|
||||
vi.mocked(isNativeIos).mockReturnValue(false)
|
||||
vi.mocked(isEffectivelyOffline).mockReturnValue(false)
|
||||
startNativeApp()
|
||||
vi.advanceTimersByTime(15_000)
|
||||
expect(keepOfflineShellFresh).not.toHaveBeenCalled()
|
||||
})
|
||||
vi.mocked(isNativeIos).mockReturnValue(false);
|
||||
vi.mocked(isEffectivelyOffline).mockReturnValue(false);
|
||||
startNativeApp();
|
||||
vi.advanceTimersByTime(15_000);
|
||||
expect(keepOfflineShellFresh).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('logs a failed refresh instead of throwing', async () => {
|
||||
vi.mocked(isNativeIos).mockReturnValue(true)
|
||||
vi.mocked(keepOfflineShellFresh).mockRejectedValue(new Error('down'))
|
||||
const report = vi.fn()
|
||||
vi.stubGlobal('reportError', report)
|
||||
startNativeApp()
|
||||
vi.advanceTimersByTime(15_000)
|
||||
await vi.waitFor(() => expect(report).toHaveBeenCalledWith(expect.any(Error)))
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
})
|
||||
vi.mocked(isNativeIos).mockReturnValue(true);
|
||||
vi.mocked(keepOfflineShellFresh).mockRejectedValue(new Error('down'));
|
||||
const report = vi.fn();
|
||||
vi.stubGlobal('reportError', report);
|
||||
startNativeApp();
|
||||
vi.advanceTimersByTime(15_000);
|
||||
await vi.waitFor(() => expect(report).toHaveBeenCalledWith(expect.any(Error)));
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,41 +1,43 @@
|
||||
import { App } from '@capacitor/app'
|
||||
import { Keyboard } from '@capacitor/keyboard'
|
||||
import { SplashScreen } from '@capacitor/splash-screen'
|
||||
import { StatusBar, Style } from '@capacitor/status-bar'
|
||||
import { isNativeApp, isNativeIos } from './platform'
|
||||
import { keepOfflineShellFresh } from './offlineShell'
|
||||
import { reportNativeFailure } from './reportFailure'
|
||||
import { isEffectivelyOffline } from '../sync/networkMode'
|
||||
import { App } from '@capacitor/app';
|
||||
import { Keyboard } from '@capacitor/keyboard';
|
||||
import { SplashScreen } from '@capacitor/splash-screen';
|
||||
import { StatusBar, Style } from '@capacitor/status-bar';
|
||||
import { isEffectivelyOffline } from '../sync/networkMode';
|
||||
import { keepOfflineShellFresh } from './offlineShell';
|
||||
import { isNativeApp, isNativeIos } from './platform';
|
||||
import { reportNativeFailure } from './reportFailure';
|
||||
|
||||
/** Long enough that the warm-up never competes with the first screen's requests. */
|
||||
const OFFLINE_SHELL_DELAY_MS = 15_000
|
||||
const OFFLINE_SHELL_DELAY_MS = 15_000;
|
||||
|
||||
/**
|
||||
* What the UI does differently when it runs inside the iOS or Android app.
|
||||
* Everything else is the same UI a browser gets from this server.
|
||||
*/
|
||||
export function startNativeApp(): void {
|
||||
if (!isNativeApp()) return
|
||||
if (!isNativeApp()) return;
|
||||
|
||||
followThemeInStatusBar()
|
||||
followThemeInStatusBar();
|
||||
|
||||
// Android's back gesture: through the app's own history first, and only
|
||||
// then out of the app, the way a browser tab would behave.
|
||||
void App.addListener('backButton', ({ canGoBack }) => {
|
||||
if (canGoBack) window.history.back()
|
||||
else void App.minimizeApp()
|
||||
})
|
||||
if (canGoBack) window.history.back();
|
||||
else void App.minimizeApp();
|
||||
});
|
||||
|
||||
requestAnimationFrame(() => { void SplashScreen.hide() })
|
||||
requestAnimationFrame(() => {
|
||||
void SplashScreen.hide();
|
||||
});
|
||||
|
||||
if (isNativeIos()) {
|
||||
// The "‹ › Done" strip above the keyboard is a web form's, not an app's.
|
||||
void Keyboard.setAccessoryBarVisible({ isVisible: false })
|
||||
void Keyboard.setAccessoryBarVisible({ isVisible: false });
|
||||
window.setTimeout(() => {
|
||||
if (isEffectivelyOffline()) return
|
||||
if (isEffectivelyOffline()) return;
|
||||
// Not refreshed this time is no harm: the next launch tries again.
|
||||
keepOfflineShellFresh().catch(reportNativeFailure)
|
||||
}, OFFLINE_SHELL_DELAY_MS)
|
||||
keepOfflineShellFresh().catch(reportNativeFailure);
|
||||
}, OFFLINE_SHELL_DELAY_MS);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,10 +47,10 @@ export function startNativeApp(): void {
|
||||
* every way the scheme changes, including "follow the system".
|
||||
*/
|
||||
function followThemeInStatusBar(): void {
|
||||
const root = document.documentElement
|
||||
const root = document.documentElement;
|
||||
const apply = (): void => {
|
||||
void StatusBar.setStyle({ style: root.classList.contains('dark') ? Style.Dark : Style.Light })
|
||||
}
|
||||
apply()
|
||||
new MutationObserver(apply).observe(root, { attributes: true, attributeFilter: ['class'] })
|
||||
void StatusBar.setStyle({ style: root.classList.contains('dark') ? Style.Dark : Style.Light });
|
||||
};
|
||||
apply();
|
||||
new MutationObserver(apply).observe(root, { attributes: true, attributeFilter: ['class'] });
|
||||
}
|
||||
|
||||
@@ -1,49 +1,53 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { Directory, Filesystem } from '@capacitor/filesystem'
|
||||
import { Share } from '@capacitor/share'
|
||||
import { cacheFileName, fileNameFromUrl, shareFile } from './nativeFiles'
|
||||
import { Directory, Filesystem } from '@capacitor/filesystem';
|
||||
import { Share } from '@capacitor/share';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { cacheFileName, fileNameFromUrl, shareFile } from './nativeFiles';
|
||||
|
||||
vi.mock('@capacitor/filesystem', () => ({ Directory: { Cache: 'CACHE' }, Filesystem: { writeFile: vi.fn() } }))
|
||||
vi.mock('@capacitor/share', () => ({ Share: { share: vi.fn() } }))
|
||||
vi.mock('@capacitor/filesystem', () => ({ Directory: { Cache: 'CACHE' }, Filesystem: { writeFile: vi.fn() } }));
|
||||
vi.mock('@capacitor/share', () => ({ Share: { share: vi.fn() } }));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(Filesystem.writeFile).mockReset().mockResolvedValue({ uri: 'file:///cache/trip.pdf' })
|
||||
vi.mocked(Share.share).mockReset().mockResolvedValue({})
|
||||
})
|
||||
vi.mocked(Filesystem.writeFile).mockReset().mockResolvedValue({ uri: 'file:///cache/trip.pdf' });
|
||||
vi.mocked(Share.share).mockReset().mockResolvedValue({});
|
||||
});
|
||||
|
||||
describe('cacheFileName', () => {
|
||||
it('keeps a readable name but nothing that could leave the cache directory', () => {
|
||||
expect(cacheFileName('Lisbon 2026.pdf')).toBe('Lisbon 2026.pdf')
|
||||
expect(cacheFileName('../../etc/passwd')).toBe('_.._etc_passwd')
|
||||
expect(cacheFileName('a:b*c?"d"<e>|f\u0001.txt')).toBe('a_b_c__d__e__f_.txt')
|
||||
expect(cacheFileName('...hidden')).toBe('hidden')
|
||||
expect(cacheFileName(' ')).toBe('download')
|
||||
})
|
||||
})
|
||||
expect(cacheFileName('Lisbon 2026.pdf')).toBe('Lisbon 2026.pdf');
|
||||
expect(cacheFileName('../../etc/passwd')).toBe('_.._etc_passwd');
|
||||
expect(cacheFileName('a:b*c?"d"<e>|f\u0001.txt')).toBe('a_b_c__d__e__f_.txt');
|
||||
expect(cacheFileName('...hidden')).toBe('hidden');
|
||||
expect(cacheFileName(' ')).toBe('download');
|
||||
});
|
||||
});
|
||||
|
||||
describe('fileNameFromUrl', () => {
|
||||
it('takes the decoded last path segment', () => {
|
||||
expect(fileNameFromUrl('/api/trips/1/files/42/Boarding%20pass.pdf?token=x')).toBe('Boarding pass.pdf')
|
||||
expect(fileNameFromUrl('/uploads/files/')).toBe('files')
|
||||
expect(fileNameFromUrl('/bad/%E0%A4%A')).toBe('%E0%A4%A')
|
||||
})
|
||||
})
|
||||
expect(fileNameFromUrl('/api/trips/1/files/42/Boarding%20pass.pdf?token=x')).toBe('Boarding pass.pdf');
|
||||
expect(fileNameFromUrl('/uploads/files/')).toBe('files');
|
||||
expect(fileNameFromUrl('/bad/%E0%A4%A')).toBe('%E0%A4%A');
|
||||
});
|
||||
});
|
||||
|
||||
describe('shareFile', () => {
|
||||
it('writes the blob to the cache and hands it to the share sheet', async () => {
|
||||
await shareFile(new Blob(['hello'], { type: 'text/plain' }), 'note.txt')
|
||||
await shareFile(new Blob(['hello'], { type: 'text/plain' }), 'note.txt');
|
||||
|
||||
expect(Filesystem.writeFile).toHaveBeenCalledWith({ path: 'note.txt', data: btoa('hello'), directory: Directory.Cache })
|
||||
expect(Share.share).toHaveBeenCalledWith({ files: ['file:///cache/trip.pdf'] })
|
||||
})
|
||||
expect(Filesystem.writeFile).toHaveBeenCalledWith({
|
||||
path: 'note.txt',
|
||||
data: btoa('hello'),
|
||||
directory: Directory.Cache,
|
||||
});
|
||||
expect(Share.share).toHaveBeenCalledWith({ files: ['file:///cache/trip.pdf'] });
|
||||
});
|
||||
|
||||
it('treats a dismissed sheet as the user changing their mind', async () => {
|
||||
vi.mocked(Share.share).mockRejectedValue(new Error('Share canceled'))
|
||||
await expect(shareFile(new Blob(['x']), 'x.txt')).resolves.toBeUndefined()
|
||||
})
|
||||
vi.mocked(Share.share).mockRejectedValue(new Error('Share canceled'));
|
||||
await expect(shareFile(new Blob(['x']), 'x.txt')).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('passes a real failure on', async () => {
|
||||
vi.mocked(Share.share).mockRejectedValue(new Error('No activity found'))
|
||||
await expect(shareFile(new Blob(['x']), 'x.txt')).rejects.toThrow('No activity found')
|
||||
})
|
||||
})
|
||||
vi.mocked(Share.share).mockRejectedValue(new Error('No activity found'));
|
||||
await expect(shareFile(new Blob(['x']), 'x.txt')).rejects.toThrow('No activity found');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,28 +1,30 @@
|
||||
import { Directory, Filesystem } from '@capacitor/filesystem'
|
||||
import { Share } from '@capacitor/share'
|
||||
import { Directory, Filesystem } from '@capacitor/filesystem';
|
||||
import { Share } from '@capacitor/share';
|
||||
|
||||
function toBase64(blob: Blob): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader()
|
||||
reader.onload = () => resolve(String(reader.result).slice(String(reader.result).indexOf(',') + 1))
|
||||
reader.onerror = () => reject(reader.error)
|
||||
reader.readAsDataURL(blob)
|
||||
})
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(String(reader.result).slice(String(reader.result).indexOf(',') + 1));
|
||||
reader.onerror = () => reject(reader.error);
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
}
|
||||
|
||||
/** Readable, but safe as a single path segment inside the cache directory. */
|
||||
export function cacheFileName(filename: string): string {
|
||||
const cleaned = Array.from(filename, (ch) => (ch.charCodeAt(0) < 32 || '\\/:*?"<>|'.includes(ch) ? '_' : ch)).join('').trim()
|
||||
return cleaned.replace(/^\.+/, '') || 'download'
|
||||
const cleaned = Array.from(filename, (ch) => (ch.charCodeAt(0) < 32 || '\\/:*?"<>|'.includes(ch) ? '_' : ch))
|
||||
.join('')
|
||||
.trim();
|
||||
return cleaned.replace(/^\.+/, '') || 'download';
|
||||
}
|
||||
|
||||
export function fileNameFromUrl(url: string): string {
|
||||
const [path = ''] = url.split('?', 1)
|
||||
const last = path.split('/').filter(Boolean).pop() ?? ''
|
||||
const [path = ''] = url.split('?', 1);
|
||||
const last = path.split('/').filter(Boolean).pop() ?? '';
|
||||
try {
|
||||
return decodeURIComponent(last)
|
||||
return decodeURIComponent(last);
|
||||
} catch {
|
||||
return last
|
||||
return last;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,12 +38,12 @@ export async function shareFile(blob: Blob, filename: string): Promise<void> {
|
||||
path: cacheFileName(filename),
|
||||
data: await toBase64(blob),
|
||||
directory: Directory.Cache,
|
||||
})
|
||||
});
|
||||
try {
|
||||
await Share.share({ files: [uri] })
|
||||
await Share.share({ files: [uri] });
|
||||
} catch (err) {
|
||||
// Dismissing the sheet rejects; that is the user's choice, not a failure.
|
||||
if (/cancel/i.test(String((err as Error)?.message))) return
|
||||
throw err
|
||||
if (/cancel/i.test(String((err as Error)?.message))) return;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,23 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { keepOfflineShellFresh, manifestFiles } from './offlineShell'
|
||||
import { TrekShell } from './trekShell'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { keepOfflineShellFresh, manifestFiles } from './offlineShell';
|
||||
import { TrekShell } from './trekShell';
|
||||
|
||||
vi.mock('./trekShell', () => ({ TrekShell: { refreshOfflineCopy: vi.fn() } }))
|
||||
vi.mock('./trekShell', () => ({ TrekShell: { refreshOfflineCopy: vi.fn() } }));
|
||||
|
||||
const manifest = {
|
||||
'index.html': { file: 'assets/index-a1b2c3d4.js', css: ['assets/index-e5f6a7b8.css'], assets: ['assets/poppins-11223344.woff2'] },
|
||||
'index.html': {
|
||||
file: 'assets/index-a1b2c3d4.js',
|
||||
css: ['assets/index-e5f6a7b8.css'],
|
||||
assets: ['assets/poppins-11223344.woff2'],
|
||||
},
|
||||
'src/pages/AtlasPage.tsx': { file: 'assets/AtlasPage-99887766.js', css: ['assets/index-e5f6a7b8.css'] },
|
||||
_shared: { file: 'assets/shared-55443322.js', assets: 'not-a-list' },
|
||||
broken: null,
|
||||
}
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(TrekShell.refreshOfflineCopy).mockReset().mockResolvedValue({ saved: true })
|
||||
})
|
||||
vi.mocked(TrekShell.refreshOfflineCopy).mockReset().mockResolvedValue({ saved: true });
|
||||
});
|
||||
|
||||
describe('manifestFiles', () => {
|
||||
it('collects every chunk, stylesheet and asset once', () => {
|
||||
@@ -23,44 +27,44 @@ describe('manifestFiles', () => {
|
||||
'assets/index-e5f6a7b8.css',
|
||||
'assets/poppins-11223344.woff2',
|
||||
'assets/shared-55443322.js',
|
||||
])
|
||||
})
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns nothing for something that is not a manifest', () => {
|
||||
expect(manifestFiles(null)).toEqual([])
|
||||
expect(manifestFiles('x')).toEqual([])
|
||||
})
|
||||
})
|
||||
expect(manifestFiles(null)).toEqual([]);
|
||||
expect(manifestFiles('x')).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('keepOfflineShellFresh', () => {
|
||||
it('refreshes the stored start page and fetches every file of the build', async () => {
|
||||
const fetched: string[] = []
|
||||
const fetched: string[] = [];
|
||||
const fetchImpl = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = String(input)
|
||||
const url = String(input);
|
||||
if (url === '/asset-manifest.json') {
|
||||
expect(init).toEqual({ cache: 'no-store' })
|
||||
return new Response(JSON.stringify(manifest))
|
||||
expect(init).toEqual({ cache: 'no-store' });
|
||||
return new Response(JSON.stringify(manifest));
|
||||
}
|
||||
fetched.push(url)
|
||||
if (url.includes('shared')) throw new Error('offline for a moment')
|
||||
return new Response('x')
|
||||
}) as unknown as typeof fetch
|
||||
fetched.push(url);
|
||||
if (url.includes('shared')) throw new Error('offline for a moment');
|
||||
return new Response('x');
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
await keepOfflineShellFresh(fetchImpl)
|
||||
await keepOfflineShellFresh(fetchImpl);
|
||||
|
||||
expect(TrekShell.refreshOfflineCopy).toHaveBeenCalled()
|
||||
expect(TrekShell.refreshOfflineCopy).toHaveBeenCalled();
|
||||
expect(fetched.sort()).toEqual([
|
||||
'/assets/AtlasPage-99887766.js',
|
||||
'/assets/index-a1b2c3d4.js',
|
||||
'/assets/index-e5f6a7b8.css',
|
||||
'/assets/poppins-11223344.woff2',
|
||||
'/assets/shared-55443322.js',
|
||||
])
|
||||
})
|
||||
]);
|
||||
});
|
||||
|
||||
it('stops after the start page when the build has no manifest', async () => {
|
||||
const fetchImpl = vi.fn(async () => new Response('', { status: 404 })) as unknown as typeof fetch
|
||||
await keepOfflineShellFresh(fetchImpl)
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
const fetchImpl = vi.fn(async () => new Response('', { status: 404 })) as unknown as typeof fetch;
|
||||
await keepOfflineShellFresh(fetchImpl);
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { TrekShell } from './trekShell'
|
||||
import { TrekShell } from './trekShell';
|
||||
|
||||
/**
|
||||
* iOS only. WKWebView runs no service worker for a domain the app does not
|
||||
@@ -10,45 +10,45 @@ import { TrekShell } from './trekShell'
|
||||
* routes nobody has opened yet.
|
||||
*/
|
||||
|
||||
const MANIFEST_URL = '/asset-manifest.json'
|
||||
const CONCURRENCY = 4
|
||||
const MANIFEST_URL = '/asset-manifest.json';
|
||||
const CONCURRENCY = 4;
|
||||
|
||||
interface ManifestChunk {
|
||||
file?: string
|
||||
css?: string[]
|
||||
assets?: string[]
|
||||
file?: string;
|
||||
css?: string[];
|
||||
assets?: string[];
|
||||
}
|
||||
|
||||
export function manifestFiles(manifest: unknown): string[] {
|
||||
if (typeof manifest !== 'object' || manifest === null) return []
|
||||
const files = new Set<string>()
|
||||
if (typeof manifest !== 'object' || manifest === null) return [];
|
||||
const files = new Set<string>();
|
||||
for (const chunk of Object.values(manifest as Record<string, ManifestChunk>)) {
|
||||
if (typeof chunk?.file === 'string') files.add(chunk.file)
|
||||
if (typeof chunk?.file === 'string') files.add(chunk.file);
|
||||
for (const list of [chunk?.css, chunk?.assets]) {
|
||||
if (Array.isArray(list)) list.forEach((f) => typeof f === 'string' && files.add(f))
|
||||
if (Array.isArray(list)) list.forEach((f) => typeof f === 'string' && files.add(f));
|
||||
}
|
||||
}
|
||||
return [...files]
|
||||
return [...files];
|
||||
}
|
||||
|
||||
async function warmCache(files: string[], fetchFile: (path: string) => Promise<unknown>): Promise<void> {
|
||||
const queue = [...files]
|
||||
const queue = [...files];
|
||||
const worker = async (): Promise<void> => {
|
||||
for (let path = queue.shift(); path !== undefined; path = queue.shift()) {
|
||||
try {
|
||||
await fetchFile(`/${path}`)
|
||||
await fetchFile(`/${path}`);
|
||||
} catch {
|
||||
// One missing chunk must not stop the rest; the next launch tries again.
|
||||
}
|
||||
}
|
||||
}
|
||||
await Promise.all(Array.from({ length: CONCURRENCY }, worker))
|
||||
};
|
||||
await Promise.all(Array.from({ length: CONCURRENCY }, worker));
|
||||
}
|
||||
|
||||
export async function keepOfflineShellFresh(fetchImpl: typeof fetch = fetch): Promise<void> {
|
||||
await TrekShell.refreshOfflineCopy()
|
||||
const response = await fetchImpl(MANIFEST_URL, { cache: 'no-store' })
|
||||
if (!response.ok) return
|
||||
const files = manifestFiles(await response.json())
|
||||
await warmCache(files, (path) => fetchImpl(path).then((r) => r.blob()))
|
||||
await TrekShell.refreshOfflineCopy();
|
||||
const response = await fetchImpl(MANIFEST_URL, { cache: 'no-store' });
|
||||
if (!response.ok) return;
|
||||
const files = manifestFiles(await response.json());
|
||||
await warmCache(files, (path) => fetchImpl(path).then((r) => r.blob()));
|
||||
}
|
||||
|
||||
@@ -1,61 +1,72 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
fromOfflineUrl, installOfflineProtocol, offlineProtocol, offlineStyle, rewriteDocument, toOfflineUrl,
|
||||
} from './offlineTiles'
|
||||
import { isNativeIos } from './platform'
|
||||
fromOfflineUrl,
|
||||
installOfflineProtocol,
|
||||
offlineProtocol,
|
||||
offlineStyle,
|
||||
rewriteDocument,
|
||||
toOfflineUrl,
|
||||
} from './offlineTiles';
|
||||
import { isNativeIos } from './platform';
|
||||
|
||||
vi.mock('./platform', () => ({ isNativeIos: vi.fn() }))
|
||||
vi.mock('./platform', () => ({ isNativeIos: vi.fn() }));
|
||||
|
||||
const cached = new Map<string, Response>()
|
||||
const cache = { match: vi.fn(async (url: string) => cached.get(url)?.clone()) }
|
||||
const cached = new Map<string, Response>();
|
||||
const cache = { match: vi.fn(async (url: string) => cached.get(url)?.clone()) };
|
||||
|
||||
beforeEach(() => {
|
||||
cached.clear()
|
||||
vi.mocked(isNativeIos).mockReturnValue(true)
|
||||
vi.stubGlobal('caches', { open: vi.fn(async () => cache) })
|
||||
})
|
||||
cached.clear();
|
||||
vi.mocked(isNativeIos).mockReturnValue(true);
|
||||
vi.stubGlobal('caches', { open: vi.fn(async () => cache) });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
function params(url: string, type: 'json' | 'arrayBuffer' | 'image' | 'string') {
|
||||
return { url, type }
|
||||
return { url, type };
|
||||
}
|
||||
|
||||
describe('URL rewriting', () => {
|
||||
it('moves https URLs onto the protocol and back, and leaves everything else', () => {
|
||||
expect(toOfflineUrl('https://tiles.openfreemap.org/styles/positron')).toBe('trek-offline://tiles.openfreemap.org/styles/positron')
|
||||
expect(fromOfflineUrl('trek-offline://tiles.openfreemap.org/styles/positron')).toBe('https://tiles.openfreemap.org/styles/positron')
|
||||
expect(toOfflineUrl('mapbox://styles/mapbox/streets-v12')).toBe('mapbox://styles/mapbox/streets-v12')
|
||||
expect(fromOfflineUrl('https://x.test/a')).toBe('https://x.test/a')
|
||||
})
|
||||
expect(toOfflineUrl('https://tiles.openfreemap.org/styles/positron')).toBe(
|
||||
'trek-offline://tiles.openfreemap.org/styles/positron'
|
||||
);
|
||||
expect(fromOfflineUrl('trek-offline://tiles.openfreemap.org/styles/positron')).toBe(
|
||||
'https://tiles.openfreemap.org/styles/positron'
|
||||
);
|
||||
expect(toOfflineUrl('mapbox://styles/mapbox/streets-v12')).toBe('mapbox://styles/mapbox/streets-v12');
|
||||
expect(fromOfflineUrl('https://x.test/a')).toBe('https://x.test/a');
|
||||
});
|
||||
|
||||
it('rewrites the style only inside the iOS app with Cache Storage', () => {
|
||||
const style = 'https://tiles.openfreemap.org/styles/liberty?key=abc'
|
||||
expect(offlineStyle(style)).toBe('trek-offline://tiles.openfreemap.org/styles/liberty?key=abc')
|
||||
expect(offlineStyle({ version: 8 })).toEqual({ version: 8 })
|
||||
const style = 'https://tiles.openfreemap.org/styles/liberty?key=abc';
|
||||
expect(offlineStyle(style)).toBe('trek-offline://tiles.openfreemap.org/styles/liberty?key=abc');
|
||||
expect(offlineStyle({ version: 8 })).toEqual({ version: 8 });
|
||||
|
||||
vi.mocked(isNativeIos).mockReturnValue(false)
|
||||
expect(offlineStyle(style)).toBe(style)
|
||||
vi.mocked(isNativeIos).mockReturnValue(false);
|
||||
expect(offlineStyle(style)).toBe(style);
|
||||
|
||||
vi.mocked(isNativeIos).mockReturnValue(true)
|
||||
vi.stubGlobal('caches', undefined)
|
||||
expect(offlineStyle(style)).toBe(style)
|
||||
})
|
||||
vi.mocked(isNativeIos).mockReturnValue(true);
|
||||
vi.stubGlobal('caches', undefined);
|
||||
expect(offlineStyle(style)).toBe(style);
|
||||
});
|
||||
|
||||
it('points sources, tiles, glyphs and sprites of a style at the protocol', () => {
|
||||
expect(rewriteDocument({
|
||||
version: 8,
|
||||
glyphs: 'https://tiles.openfreemap.org/fonts/{fontstack}/{range}.pbf',
|
||||
sprite: [{ id: 'default', url: 'https://tiles.openfreemap.org/sprites/ofm' }, 'odd'],
|
||||
sources: {
|
||||
openmaptiles: { type: 'vector', url: 'https://tiles.openfreemap.org/planet' },
|
||||
inline: { type: 'raster', tiles: ['https://a.test/{z}/{x}/{y}.png', 7] },
|
||||
broken: null,
|
||||
},
|
||||
layers: [],
|
||||
})).toEqual({
|
||||
expect(
|
||||
rewriteDocument({
|
||||
version: 8,
|
||||
glyphs: 'https://tiles.openfreemap.org/fonts/{fontstack}/{range}.pbf',
|
||||
sprite: [{ id: 'default', url: 'https://tiles.openfreemap.org/sprites/ofm' }, 'odd'],
|
||||
sources: {
|
||||
openmaptiles: { type: 'vector', url: 'https://tiles.openfreemap.org/planet' },
|
||||
inline: { type: 'raster', tiles: ['https://a.test/{z}/{x}/{y}.png', 7] },
|
||||
broken: null,
|
||||
},
|
||||
layers: [],
|
||||
})
|
||||
).toEqual({
|
||||
version: 8,
|
||||
glyphs: 'trek-offline://tiles.openfreemap.org/fonts/{fontstack}/{range}.pbf',
|
||||
sprite: [{ id: 'default', url: 'trek-offline://tiles.openfreemap.org/sprites/ofm' }, 'odd'],
|
||||
@@ -65,76 +76,108 @@ describe('URL rewriting', () => {
|
||||
broken: null,
|
||||
},
|
||||
layers: [],
|
||||
})
|
||||
})
|
||||
});
|
||||
});
|
||||
|
||||
it('handles a TileJSON, a single sprite URL and things that are not documents', () => {
|
||||
expect(rewriteDocument({ tiles: ['https://t.test/20250101/{z}/{x}/{y}.pbf'] })).toEqual({ tiles: ['trek-offline://t.test/20250101/{z}/{x}/{y}.pbf'] })
|
||||
expect(rewriteDocument({ sprite: 'https://s.test/sprite' })).toEqual({ sprite: 'trek-offline://s.test/sprite' })
|
||||
expect(rewriteDocument('x')).toBe('x')
|
||||
expect(rewriteDocument([1])).toEqual([1])
|
||||
})
|
||||
})
|
||||
expect(rewriteDocument({ tiles: ['https://t.test/20250101/{z}/{x}/{y}.pbf'] })).toEqual({
|
||||
tiles: ['trek-offline://t.test/20250101/{z}/{x}/{y}.pbf'],
|
||||
});
|
||||
expect(rewriteDocument({ sprite: 'https://s.test/sprite' })).toEqual({ sprite: 'trek-offline://s.test/sprite' });
|
||||
expect(rewriteDocument('x')).toBe('x');
|
||||
expect(rewriteDocument([1])).toEqual([1]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('offlineProtocol', () => {
|
||||
it('answers a document from the network and rewrites it', async () => {
|
||||
const fetchMock = vi.fn(async () => new Response(JSON.stringify({ tiles: ['https://t.test/{z}/{x}/{y}.pbf'] })))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const result = await offlineProtocol(params('trek-offline://t.test/planet', 'json'), new AbortController())
|
||||
expect(fetchMock).toHaveBeenCalledWith('https://t.test/planet', expect.objectContaining({ mode: 'cors' }))
|
||||
expect(result.data).toEqual({ tiles: ['trek-offline://t.test/{z}/{x}/{y}.pbf'] })
|
||||
})
|
||||
const fetchMock = vi.fn(async () => new Response(JSON.stringify({ tiles: ['https://t.test/{z}/{x}/{y}.pbf'] })));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const result = await offlineProtocol(params('trek-offline://t.test/planet', 'json'), new AbortController());
|
||||
expect(fetchMock).toHaveBeenCalledWith('https://t.test/planet', expect.objectContaining({ mode: 'cors' }));
|
||||
expect(result.data).toEqual({ tiles: ['trek-offline://t.test/{z}/{x}/{y}.pbf'] });
|
||||
});
|
||||
|
||||
it('falls back to the cached document when the network is gone', async () => {
|
||||
cached.set('https://t.test/style', new Response(JSON.stringify({ version: 8 })))
|
||||
vi.stubGlobal('fetch', vi.fn(async () => { throw new TypeError('offline') }))
|
||||
const result = await offlineProtocol(params('trek-offline://t.test/style', 'json'), new AbortController())
|
||||
expect(result.data).toEqual({ version: 8 })
|
||||
})
|
||||
cached.set('https://t.test/style', new Response(JSON.stringify({ version: 8 })));
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async () => {
|
||||
throw new TypeError('offline');
|
||||
})
|
||||
);
|
||||
const result = await offlineProtocol(params('trek-offline://t.test/style', 'json'), new AbortController());
|
||||
expect(result.data).toEqual({ version: 8 });
|
||||
});
|
||||
|
||||
it('serves tiles from the cache without asking the network', async () => {
|
||||
cached.set('https://t.test/1/2/3.pbf', new Response(new Uint8Array([1, 2, 3])))
|
||||
const fetchMock = vi.fn()
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const result = await offlineProtocol(params('trek-offline://t.test/1/2/3.pbf', 'arrayBuffer'), new AbortController())
|
||||
expect(new Uint8Array(result.data as ArrayBuffer)).toEqual(new Uint8Array([1, 2, 3]))
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
cached.set('https://t.test/1/2/3.pbf', new Response(new Uint8Array([1, 2, 3])));
|
||||
const fetchMock = vi.fn();
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const result = await offlineProtocol(
|
||||
params('trek-offline://t.test/1/2/3.pbf', 'arrayBuffer'),
|
||||
new AbortController()
|
||||
);
|
||||
expect(new Uint8Array(result.data as ArrayBuffer)).toEqual(new Uint8Array([1, 2, 3]));
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('fetches an uncached tile, and returns text for string requests', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn(async () => new Response('hello')))
|
||||
const tile = await offlineProtocol(params('trek-offline://t.test/9/9/9.png', 'image'), new AbortController())
|
||||
expect(new TextDecoder().decode(tile.data as ArrayBuffer)).toBe('hello')
|
||||
const text = await offlineProtocol(params('trek-offline://t.test/a.txt', 'string'), new AbortController())
|
||||
expect(text.data).toBe('hello')
|
||||
})
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async () => new Response('hello'))
|
||||
);
|
||||
const tile = await offlineProtocol(params('trek-offline://t.test/9/9/9.png', 'image'), new AbortController());
|
||||
expect(new TextDecoder().decode(tile.data as ArrayBuffer)).toBe('hello');
|
||||
const text = await offlineProtocol(params('trek-offline://t.test/a.txt', 'string'), new AbortController());
|
||||
expect(text.data).toBe('hello');
|
||||
});
|
||||
|
||||
it('fails loudly on an uncached tile offline or an HTTP error', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn(async () => { throw new TypeError('offline') }))
|
||||
await expect(offlineProtocol(params('trek-offline://t.test/0/0/0.pbf', 'arrayBuffer'), new AbortController())).rejects.toThrow('offline')
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async () => {
|
||||
throw new TypeError('offline');
|
||||
})
|
||||
);
|
||||
await expect(
|
||||
offlineProtocol(params('trek-offline://t.test/0/0/0.pbf', 'arrayBuffer'), new AbortController())
|
||||
).rejects.toThrow('offline');
|
||||
|
||||
vi.stubGlobal('fetch', vi.fn(async () => new Response('nope', { status: 404 })))
|
||||
await expect(offlineProtocol(params('trek-offline://t.test/0/0/0.pbf', 'arrayBuffer'), new AbortController())).rejects.toThrow('HTTP 404')
|
||||
await expect(offlineProtocol(params('trek-offline://t.test/style', 'json'), new AbortController())).rejects.toThrow('Not available offline')
|
||||
})
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async () => new Response('nope', { status: 404 }))
|
||||
);
|
||||
await expect(
|
||||
offlineProtocol(params('trek-offline://t.test/0/0/0.pbf', 'arrayBuffer'), new AbortController())
|
||||
).rejects.toThrow('HTTP 404');
|
||||
await expect(offlineProtocol(params('trek-offline://t.test/style', 'json'), new AbortController())).rejects.toThrow(
|
||||
'Not available offline'
|
||||
);
|
||||
});
|
||||
|
||||
it('passes an abort straight through for documents', async () => {
|
||||
const controller = new AbortController()
|
||||
controller.abort()
|
||||
vi.stubGlobal('fetch', vi.fn(async () => { throw new DOMException('aborted', 'AbortError') }))
|
||||
await expect(offlineProtocol(params('trek-offline://t.test/style', 'json'), controller)).rejects.toThrow('aborted')
|
||||
})
|
||||
})
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async () => {
|
||||
throw new DOMException('aborted', 'AbortError');
|
||||
})
|
||||
);
|
||||
await expect(offlineProtocol(params('trek-offline://t.test/style', 'json'), controller)).rejects.toThrow('aborted');
|
||||
});
|
||||
});
|
||||
|
||||
describe('installOfflineProtocol', () => {
|
||||
it('registers only inside the iOS app', () => {
|
||||
const addProtocol = vi.fn()
|
||||
installOfflineProtocol({ addProtocol })
|
||||
expect(addProtocol).toHaveBeenCalledWith('trek-offline', offlineProtocol)
|
||||
const addProtocol = vi.fn();
|
||||
installOfflineProtocol({ addProtocol });
|
||||
expect(addProtocol).toHaveBeenCalledWith('trek-offline', offlineProtocol);
|
||||
|
||||
addProtocol.mockClear()
|
||||
vi.mocked(isNativeIos).mockReturnValue(false)
|
||||
installOfflineProtocol({ addProtocol })
|
||||
expect(addProtocol).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
addProtocol.mockClear();
|
||||
vi.mocked(isNativeIos).mockReturnValue(false);
|
||||
installOfflineProtocol({ addProtocol });
|
||||
expect(addProtocol).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { AddProtocolAction, GetResourceResponse, RequestParameters } from 'maplibre-gl'
|
||||
import { VECTOR_CACHE } from '../sync/glPrefetcher'
|
||||
import { isNativeIos } from './platform'
|
||||
import type { AddProtocolAction, GetResourceResponse, RequestParameters } from 'maplibre-gl';
|
||||
import { VECTOR_CACHE } from '../sync/glPrefetcher';
|
||||
import { isNativeIos } from './platform';
|
||||
|
||||
/**
|
||||
* Offline vector maps for the iOS app.
|
||||
@@ -16,32 +16,33 @@ import { isNativeIos } from './platform'
|
||||
* the app.
|
||||
*/
|
||||
|
||||
const OFFLINE_SCHEME = 'trek-offline'
|
||||
const PREFIX = `${OFFLINE_SCHEME}://`
|
||||
const OFFLINE_SCHEME = 'trek-offline';
|
||||
const PREFIX = `${OFFLINE_SCHEME}://`;
|
||||
|
||||
function offlineTilesActive(): boolean {
|
||||
return isNativeIos() && typeof caches !== 'undefined'
|
||||
return isNativeIos() && typeof caches !== 'undefined';
|
||||
}
|
||||
|
||||
export function toOfflineUrl(url: string): string {
|
||||
return url.startsWith('https://') ? PREFIX + url.slice('https://'.length) : url
|
||||
return url.startsWith('https://') ? PREFIX + url.slice('https://'.length) : url;
|
||||
}
|
||||
|
||||
export function fromOfflineUrl(url: string): string {
|
||||
return url.startsWith(PREFIX) ? 'https://' + url.slice(PREFIX.length) : url
|
||||
return url.startsWith(PREFIX) ? 'https://' + url.slice(PREFIX.length) : url;
|
||||
}
|
||||
|
||||
/** The style URL to hand MapLibre: rewritten inside the iOS app, untouched anywhere else. */
|
||||
export function offlineStyle<T>(style: T): T {
|
||||
return offlineTilesActive() && typeof style === 'string' ? (toOfflineUrl(style) as T) : style
|
||||
return offlineTilesActive() && typeof style === 'string' ? (toOfflineUrl(style) as T) : style;
|
||||
}
|
||||
|
||||
type Doc = Record<string, unknown>
|
||||
type Doc = Record<string, unknown>;
|
||||
/** What a protocol handler may hand MapLibre back. */
|
||||
type ProtocolData = Awaited<ReturnType<AddProtocolAction>>['data']
|
||||
type ProtocolData = Awaited<ReturnType<AddProtocolAction>>['data'];
|
||||
|
||||
const isDoc = (value: unknown): value is Doc => typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
const rewriteList = (value: unknown): unknown => (Array.isArray(value) ? value.map((v) => (typeof v === 'string' ? toOfflineUrl(v) : v)) : value)
|
||||
const isDoc = (value: unknown): value is Doc => typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
const rewriteList = (value: unknown): unknown =>
|
||||
Array.isArray(value) ? value.map((v) => (typeof v === 'string' ? toOfflineUrl(v) : v)) : value;
|
||||
|
||||
/**
|
||||
* Points the URLs inside a style document or a TileJSON at the protocol, so
|
||||
@@ -49,24 +50,28 @@ const rewriteList = (value: unknown): unknown => (Array.isArray(value) ? value.m
|
||||
* the tiles as well, not only for the style.
|
||||
*/
|
||||
export function rewriteDocument(doc: unknown): unknown {
|
||||
if (!isDoc(doc)) return doc
|
||||
const out: Doc = { ...doc }
|
||||
if ('tiles' in out) out.tiles = rewriteList(out.tiles)
|
||||
if (typeof out.glyphs === 'string') out.glyphs = toOfflineUrl(out.glyphs)
|
||||
if (typeof out.sprite === 'string') out.sprite = toOfflineUrl(out.sprite)
|
||||
if (!isDoc(doc)) return doc;
|
||||
const out: Doc = { ...doc };
|
||||
if ('tiles' in out) out.tiles = rewriteList(out.tiles);
|
||||
if (typeof out.glyphs === 'string') out.glyphs = toOfflineUrl(out.glyphs);
|
||||
if (typeof out.sprite === 'string') out.sprite = toOfflineUrl(out.sprite);
|
||||
else if (Array.isArray(out.sprite)) {
|
||||
out.sprite = out.sprite.map((entry) => (isDoc(entry) && typeof entry.url === 'string' ? { ...entry, url: toOfflineUrl(entry.url) } : entry))
|
||||
out.sprite = out.sprite.map((entry) =>
|
||||
isDoc(entry) && typeof entry.url === 'string' ? { ...entry, url: toOfflineUrl(entry.url) } : entry
|
||||
);
|
||||
}
|
||||
if (isDoc(out.sources)) {
|
||||
out.sources = Object.fromEntries(Object.entries(out.sources).map(([id, source]) => {
|
||||
if (!isDoc(source)) return [id, source]
|
||||
const rewritten: Doc = { ...source }
|
||||
if (typeof rewritten.url === 'string') rewritten.url = toOfflineUrl(rewritten.url)
|
||||
if ('tiles' in rewritten) rewritten.tiles = rewriteList(rewritten.tiles)
|
||||
return [id, rewritten]
|
||||
}))
|
||||
out.sources = Object.fromEntries(
|
||||
Object.entries(out.sources).map(([id, source]) => {
|
||||
if (!isDoc(source)) return [id, source];
|
||||
const rewritten: Doc = { ...source };
|
||||
if (typeof rewritten.url === 'string') rewritten.url = toOfflineUrl(rewritten.url);
|
||||
if ('tiles' in rewritten) rewritten.tiles = rewriteList(rewritten.tiles);
|
||||
return [id, rewritten];
|
||||
})
|
||||
);
|
||||
}
|
||||
return out
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -75,32 +80,37 @@ export function rewriteDocument(doc: unknown): unknown {
|
||||
* their URL, so the cache goes first and saves the round trip.
|
||||
*/
|
||||
async function load(url: string, networkFirst: boolean, signal: AbortSignal): Promise<Response> {
|
||||
const cache = await caches.open(VECTOR_CACHE)
|
||||
const cache = await caches.open(VECTOR_CACHE);
|
||||
if (!networkFirst) {
|
||||
const cached = await cache.match(url)
|
||||
if (cached) return cached
|
||||
const cached = await cache.match(url);
|
||||
if (cached) return cached;
|
||||
}
|
||||
try {
|
||||
const response = await fetch(url, { mode: 'cors', signal })
|
||||
if (response.ok) return response
|
||||
if (!networkFirst) return response
|
||||
const response = await fetch(url, { mode: 'cors', signal });
|
||||
if (response.ok) return response;
|
||||
if (!networkFirst) return response;
|
||||
} catch (err) {
|
||||
if (signal.aborted || !networkFirst) throw err
|
||||
if (signal.aborted || !networkFirst) throw err;
|
||||
}
|
||||
const cached = await cache.match(url)
|
||||
if (cached) return cached
|
||||
throw new Error(`Not available offline: ${url}`)
|
||||
const cached = await cache.match(url);
|
||||
if (cached) return cached;
|
||||
throw new Error(`Not available offline: ${url}`);
|
||||
}
|
||||
|
||||
export const offlineProtocol: AddProtocolAction = async (params: RequestParameters, abortController: AbortController): Promise<GetResourceResponse<ProtocolData>> => {
|
||||
const url = fromOfflineUrl(params.url)
|
||||
const response = await load(url, params.type === 'json', abortController.signal)
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status} for ${url}`)
|
||||
if (params.type === 'json') return { data: rewriteDocument(await response.json()) as ProtocolData }
|
||||
if (params.type === 'string') return { data: await response.text() }
|
||||
return { data: await response.arrayBuffer() }
|
||||
}
|
||||
export const offlineProtocol: AddProtocolAction = async (
|
||||
params: RequestParameters,
|
||||
abortController: AbortController
|
||||
): Promise<GetResourceResponse<ProtocolData>> => {
|
||||
const url = fromOfflineUrl(params.url);
|
||||
const response = await load(url, params.type === 'json', abortController.signal);
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status} for ${url}`);
|
||||
if (params.type === 'json') return { data: rewriteDocument(await response.json()) as ProtocolData };
|
||||
if (params.type === 'string') return { data: await response.text() };
|
||||
return { data: await response.arrayBuffer() };
|
||||
};
|
||||
|
||||
export function installOfflineProtocol(maplibre: { addProtocol: (name: string, action: AddProtocolAction) => void }): void {
|
||||
if (offlineTilesActive()) maplibre.addProtocol(OFFLINE_SCHEME, offlineProtocol)
|
||||
export function installOfflineProtocol(maplibre: {
|
||||
addProtocol: (name: string, action: AddProtocolAction) => void;
|
||||
}): void {
|
||||
if (offlineTilesActive()) maplibre.addProtocol(OFFLINE_SCHEME, offlineProtocol);
|
||||
}
|
||||
|
||||
@@ -1,33 +1,33 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { Capacitor } from '@capacitor/core'
|
||||
import { isNativeApp, isNativeIos, nativeServerHost } from './platform'
|
||||
import { Capacitor } from '@capacitor/core';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { isNativeApp, isNativeIos, nativeServerHost } from './platform';
|
||||
|
||||
vi.mock('@capacitor/core', () => ({ Capacitor: { isNativePlatform: vi.fn(), getPlatform: vi.fn() } }))
|
||||
vi.mock('@capacitor/core', () => ({ Capacitor: { isNativePlatform: vi.fn(), getPlatform: vi.fn() } }));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(Capacitor.isNativePlatform).mockReturnValue(true)
|
||||
vi.mocked(Capacitor.getPlatform).mockReturnValue('ios')
|
||||
})
|
||||
vi.mocked(Capacitor.isNativePlatform).mockReturnValue(true);
|
||||
vi.mocked(Capacitor.getPlatform).mockReturnValue('ios');
|
||||
});
|
||||
|
||||
describe('platform', () => {
|
||||
it('tells the app from a browser', () => {
|
||||
expect(isNativeApp()).toBe(true)
|
||||
vi.mocked(Capacitor.isNativePlatform).mockReturnValue(false)
|
||||
expect(isNativeApp()).toBe(false)
|
||||
})
|
||||
expect(isNativeApp()).toBe(true);
|
||||
vi.mocked(Capacitor.isNativePlatform).mockReturnValue(false);
|
||||
expect(isNativeApp()).toBe(false);
|
||||
});
|
||||
|
||||
it('narrows to iOS', () => {
|
||||
expect(isNativeIos()).toBe(true)
|
||||
vi.mocked(Capacitor.getPlatform).mockReturnValue('android')
|
||||
expect(isNativeIos()).toBe(false)
|
||||
vi.mocked(Capacitor.getPlatform).mockReturnValue('ios')
|
||||
vi.mocked(Capacitor.isNativePlatform).mockReturnValue(false)
|
||||
expect(isNativeIos()).toBe(false)
|
||||
})
|
||||
expect(isNativeIos()).toBe(true);
|
||||
vi.mocked(Capacitor.getPlatform).mockReturnValue('android');
|
||||
expect(isNativeIos()).toBe(false);
|
||||
vi.mocked(Capacitor.getPlatform).mockReturnValue('ios');
|
||||
vi.mocked(Capacitor.isNativePlatform).mockReturnValue(false);
|
||||
expect(isNativeIos()).toBe(false);
|
||||
});
|
||||
|
||||
it('names the server the WebView sits on, only inside the app', () => {
|
||||
expect(nativeServerHost()).toBe(window.location.host)
|
||||
vi.mocked(Capacitor.isNativePlatform).mockReturnValue(false)
|
||||
expect(nativeServerHost()).toBeNull()
|
||||
})
|
||||
})
|
||||
expect(nativeServerHost()).toBe(window.location.host);
|
||||
vi.mocked(Capacitor.isNativePlatform).mockReturnValue(false);
|
||||
expect(nativeServerHost()).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import { Capacitor } from '@capacitor/core'
|
||||
import { Capacitor } from '@capacitor/core';
|
||||
|
||||
/** True inside the iOS and Android apps, where the WebView shows this server's UI. */
|
||||
export function isNativeApp(): boolean {
|
||||
return Capacitor.isNativePlatform()
|
||||
return Capacitor.isNativePlatform();
|
||||
}
|
||||
|
||||
export function isNativeIos(): boolean {
|
||||
return isNativeApp() && Capacitor.getPlatform() === 'ios'
|
||||
return isNativeApp() && Capacitor.getPlatform() === 'ios';
|
||||
}
|
||||
|
||||
/** The server the app is connected to: the WebView sits on its origin. */
|
||||
export function nativeServerHost(): string | null {
|
||||
return isNativeApp() ? window.location.host : null
|
||||
return isNativeApp() ? window.location.host : null;
|
||||
}
|
||||
|
||||
@@ -1,73 +1,85 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { candidateUrls, probeServer, type ProbeResponse } from './serverAddress'
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { candidateUrls, probeServer, type ProbeResponse } from './serverAddress';
|
||||
|
||||
const features = (url: string, data: unknown = { bookingImport: false, aiParsing: false, nativeApp: true }): ProbeResponse =>
|
||||
({ status: 200, data, url })
|
||||
const features = (
|
||||
url: string,
|
||||
data: unknown = { bookingImport: false, aiParsing: false, nativeApp: true }
|
||||
): ProbeResponse => ({ status: 200, data, url });
|
||||
|
||||
describe('candidateUrls', () => {
|
||||
it('tries https before http when no scheme was typed', () => {
|
||||
expect(candidateUrls('trek.example.com')).toEqual(['https://trek.example.com', 'http://trek.example.com'])
|
||||
expect(candidateUrls(' 192.168.1.10:3001/ ')).toEqual(['https://192.168.1.10:3001', 'http://192.168.1.10:3001'])
|
||||
})
|
||||
expect(candidateUrls('trek.example.com')).toEqual(['https://trek.example.com', 'http://trek.example.com']);
|
||||
expect(candidateUrls(' 192.168.1.10:3001/ ')).toEqual(['https://192.168.1.10:3001', 'http://192.168.1.10:3001']);
|
||||
});
|
||||
|
||||
it('keeps an explicit scheme and path, without query, hash or trailing slashes', () => {
|
||||
expect(candidateUrls('http://nas.local:3001/trek/?x=1#y')).toEqual(['http://nas.local:3001/trek'])
|
||||
expect(candidateUrls('HTTPS://Trek.Example.com//')).toEqual(['https://trek.example.com'])
|
||||
})
|
||||
expect(candidateUrls('http://nas.local:3001/trek/?x=1#y')).toEqual(['http://nas.local:3001/trek']);
|
||||
expect(candidateUrls('HTTPS://Trek.Example.com//')).toEqual(['https://trek.example.com']);
|
||||
});
|
||||
|
||||
it('returns nothing for empty input or other schemes', () => {
|
||||
expect(candidateUrls(' ')).toEqual([])
|
||||
expect(candidateUrls('ftp://trek.example.com')).toEqual([])
|
||||
expect(candidateUrls('javascript://alert(1)')).toEqual([])
|
||||
})
|
||||
})
|
||||
expect(candidateUrls(' ')).toEqual([]);
|
||||
expect(candidateUrls('ftp://trek.example.com')).toEqual([]);
|
||||
expect(candidateUrls('javascript://alert(1)')).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('probeServer', () => {
|
||||
it('accepts a server that reports nativeApp and follows its redirect', async () => {
|
||||
const get = vi.fn().mockResolvedValue(features('https://trek.example.com/api/health/features'))
|
||||
expect(await probeServer('http://trek.example.com', get)).toEqual({ ok: true, url: 'https://trek.example.com' })
|
||||
expect(get).toHaveBeenCalledWith('http://trek.example.com/api/health/features')
|
||||
})
|
||||
const get = vi.fn().mockResolvedValue(features('https://trek.example.com/api/health/features'));
|
||||
expect(await probeServer('http://trek.example.com', get)).toEqual({ ok: true, url: 'https://trek.example.com' });
|
||||
expect(get).toHaveBeenCalledWith('http://trek.example.com/api/health/features');
|
||||
});
|
||||
|
||||
it('falls back to the candidate itself when the final URL is not the probe path', async () => {
|
||||
const get = vi.fn().mockResolvedValue(features('https://sso.example.com/login'))
|
||||
expect(await probeServer('https://trek.example.com', get)).toEqual({ ok: true, url: 'https://trek.example.com' })
|
||||
})
|
||||
const get = vi.fn().mockResolvedValue(features('https://sso.example.com/login'));
|
||||
expect(await probeServer('https://trek.example.com', get)).toEqual({ ok: true, url: 'https://trek.example.com' });
|
||||
});
|
||||
|
||||
it('moves on to plain http when https cannot be reached', async () => {
|
||||
const get = vi.fn()
|
||||
const get = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new Error('ECONNREFUSED'))
|
||||
.mockResolvedValueOnce(features('http://192.168.1.10:3001/api/health/features'))
|
||||
expect(await probeServer('192.168.1.10:3001', get)).toEqual({ ok: true, url: 'http://192.168.1.10:3001' })
|
||||
expect(get).toHaveBeenNthCalledWith(2, 'http://192.168.1.10:3001/api/health/features')
|
||||
})
|
||||
.mockResolvedValueOnce(features('http://192.168.1.10:3001/api/health/features'));
|
||||
expect(await probeServer('192.168.1.10:3001', get)).toEqual({ ok: true, url: 'http://192.168.1.10:3001' });
|
||||
expect(get).toHaveBeenNthCalledWith(2, 'http://192.168.1.10:3001/api/health/features');
|
||||
});
|
||||
|
||||
it('names a TREK server without the native flag as too old', async () => {
|
||||
const get = vi.fn().mockResolvedValue(features('https://old.example.com/api/health/features', { bookingImport: true, aiParsing: false }))
|
||||
expect(await probeServer('https://old.example.com', get)).toEqual({ ok: false, reason: 'tooOld' })
|
||||
})
|
||||
const get = vi
|
||||
.fn()
|
||||
.mockResolvedValue(
|
||||
features('https://old.example.com/api/health/features', { bookingImport: true, aiParsing: false })
|
||||
);
|
||||
expect(await probeServer('https://old.example.com', get)).toEqual({ ok: false, reason: 'tooOld' });
|
||||
});
|
||||
|
||||
it('tells a server that is not TREK apart from one that is not there', async () => {
|
||||
const html = vi.fn().mockResolvedValue({ status: 200, data: '<html>', url: 'https://x.example.com/api/health/features' })
|
||||
expect(await probeServer('https://x.example.com', html)).toEqual({ ok: false, reason: 'notTrek' })
|
||||
const html = vi
|
||||
.fn()
|
||||
.mockResolvedValue({ status: 200, data: '<html>', url: 'https://x.example.com/api/health/features' });
|
||||
expect(await probeServer('https://x.example.com', html)).toEqual({ ok: false, reason: 'notTrek' });
|
||||
|
||||
const missing = vi.fn().mockResolvedValue({ status: 404, data: {}, url: 'https://x.example.com/api/health/features' })
|
||||
expect(await probeServer('https://x.example.com', missing)).toEqual({ ok: false, reason: 'notTrek' })
|
||||
const missing = vi
|
||||
.fn()
|
||||
.mockResolvedValue({ status: 404, data: {}, url: 'https://x.example.com/api/health/features' });
|
||||
expect(await probeServer('https://x.example.com', missing)).toEqual({ ok: false, reason: 'notTrek' });
|
||||
|
||||
const down = vi.fn().mockRejectedValue(new Error('timeout'))
|
||||
expect(await probeServer('x.example.com', down)).toEqual({ ok: false, reason: 'unreachable' })
|
||||
})
|
||||
const down = vi.fn().mockRejectedValue(new Error('timeout'));
|
||||
expect(await probeServer('x.example.com', down)).toEqual({ ok: false, reason: 'unreachable' });
|
||||
});
|
||||
|
||||
it('keeps the most telling failure across candidates', async () => {
|
||||
const get = vi.fn()
|
||||
const get = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(features('https://nas.local/api/health/features', { bookingImport: false }))
|
||||
.mockRejectedValueOnce(new Error('ECONNREFUSED'))
|
||||
expect(await probeServer('nas.local', get)).toEqual({ ok: false, reason: 'tooOld' })
|
||||
})
|
||||
.mockRejectedValueOnce(new Error('ECONNREFUSED'));
|
||||
expect(await probeServer('nas.local', get)).toEqual({ ok: false, reason: 'tooOld' });
|
||||
});
|
||||
|
||||
it('refuses input that is not an address', async () => {
|
||||
const get = vi.fn()
|
||||
expect(await probeServer('', get)).toEqual({ ok: false, reason: 'invalid' })
|
||||
expect(get).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
const get = vi.fn();
|
||||
expect(await probeServer('', get)).toEqual({ ok: false, reason: 'invalid' });
|
||||
expect(get).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,30 +3,28 @@
|
||||
* can load, or a reason it cannot.
|
||||
*/
|
||||
|
||||
export type ProbeFailure = 'invalid' | 'unreachable' | 'notTrek' | 'tooOld'
|
||||
type ProbeResult =
|
||||
| { ok: true; url: string; reason?: undefined }
|
||||
| { ok: false; reason: ProbeFailure; url?: undefined }
|
||||
export type ProbeFailure = 'invalid' | 'unreachable' | 'notTrek' | 'tooOld';
|
||||
type ProbeResult = { ok: true; url: string; reason?: undefined } | { ok: false; reason: ProbeFailure; url?: undefined };
|
||||
|
||||
export interface ProbeResponse {
|
||||
status: number
|
||||
data: unknown
|
||||
status: number;
|
||||
data: unknown;
|
||||
/** The URL after redirects. */
|
||||
url: string
|
||||
url: string;
|
||||
}
|
||||
export type ProbeGet = (url: string) => Promise<ProbeResponse>
|
||||
export type ProbeGet = (url: string) => Promise<ProbeResponse>;
|
||||
|
||||
const FEATURES_PATH = '/api/health/features'
|
||||
const FEATURES_PATH = '/api/health/features';
|
||||
|
||||
function normalize(raw: string): string | null {
|
||||
let parsed: URL
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(raw)
|
||||
parsed = new URL(raw);
|
||||
} catch {
|
||||
return null
|
||||
return null;
|
||||
}
|
||||
if ((parsed.protocol !== 'https:' && parsed.protocol !== 'http:') || !parsed.hostname) return null
|
||||
return parsed.origin + parsed.pathname.replace(/\/+$/, '')
|
||||
if ((parsed.protocol !== 'https:' && parsed.protocol !== 'http:') || !parsed.hostname) return null;
|
||||
return parsed.origin + parsed.pathname.replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -34,45 +32,45 @@ function normalize(raw: string): string | null {
|
||||
* home network is often reached as a bare IP and port without TLS.
|
||||
*/
|
||||
export function candidateUrls(input: string): string[] {
|
||||
const trimmed = input.trim()
|
||||
if (!trimmed) return []
|
||||
const trimmed = input.trim();
|
||||
if (!trimmed) return [];
|
||||
const candidates = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)
|
||||
? [normalize(trimmed)]
|
||||
: [normalize(`https://${trimmed}`), normalize(`http://${trimmed}`)]
|
||||
return candidates.filter((url): url is string => url !== null)
|
||||
: [normalize(`https://${trimmed}`), normalize(`http://${trimmed}`)];
|
||||
return candidates.filter((url): url is string => url !== null);
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null
|
||||
return typeof value === 'object' && value !== null;
|
||||
}
|
||||
|
||||
function judge(response: ProbeResponse): ProbeResult {
|
||||
if (response.status !== 200 || !isRecord(response.data)) return { ok: false, reason: 'notTrek' }
|
||||
if (response.status !== 200 || !isRecord(response.data)) return { ok: false, reason: 'notTrek' };
|
||||
if (response.data.nativeApp === true) {
|
||||
// Follow a redirect (http to https, a canonical host) so the app loads the
|
||||
// address the server actually answers on.
|
||||
const base = response.url.endsWith(FEATURES_PATH) ? response.url.slice(0, -FEATURES_PATH.length) : null
|
||||
return { ok: true, url: (base && normalize(base)) || '' }
|
||||
const base = response.url.endsWith(FEATURES_PATH) ? response.url.slice(0, -FEATURES_PATH.length) : null;
|
||||
return { ok: true, url: (base && normalize(base)) || '' };
|
||||
}
|
||||
return 'bookingImport' in response.data ? { ok: false, reason: 'tooOld' } : { ok: false, reason: 'notTrek' }
|
||||
return 'bookingImport' in response.data ? { ok: false, reason: 'tooOld' } : { ok: false, reason: 'notTrek' };
|
||||
}
|
||||
|
||||
const FAILURE_RANK: Record<ProbeFailure, number> = { invalid: 0, unreachable: 1, notTrek: 2, tooOld: 3 }
|
||||
const FAILURE_RANK: Record<ProbeFailure, number> = { invalid: 0, unreachable: 1, notTrek: 2, tooOld: 3 };
|
||||
|
||||
export async function probeServer(input: string, get: ProbeGet): Promise<ProbeResult> {
|
||||
const candidates = candidateUrls(input)
|
||||
if (!candidates.length) return { ok: false, reason: 'invalid' }
|
||||
const candidates = candidateUrls(input);
|
||||
if (!candidates.length) return { ok: false, reason: 'invalid' };
|
||||
|
||||
let failure: ProbeFailure = 'unreachable'
|
||||
let failure: ProbeFailure = 'unreachable';
|
||||
for (const candidate of candidates) {
|
||||
let verdict: ProbeResult
|
||||
let verdict: ProbeResult;
|
||||
try {
|
||||
verdict = judge(await get(candidate + FEATURES_PATH))
|
||||
verdict = judge(await get(candidate + FEATURES_PATH));
|
||||
} catch {
|
||||
continue
|
||||
continue;
|
||||
}
|
||||
if (verdict.ok) return { ok: true, url: verdict.url || candidate }
|
||||
if (FAILURE_RANK[verdict.reason] > FAILURE_RANK[failure]) failure = verdict.reason
|
||||
if (verdict.ok) return { ok: true, url: verdict.url || candidate };
|
||||
if (FAILURE_RANK[verdict.reason] > FAILURE_RANK[failure]) failure = verdict.reason;
|
||||
}
|
||||
return { ok: false, reason: failure }
|
||||
return { ok: false, reason: failure };
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { registerPlugin } from '@capacitor/core'
|
||||
import { registerPlugin } from '@capacitor/core';
|
||||
|
||||
/**
|
||||
* The app's own native plugin, implemented in
|
||||
@@ -12,25 +12,25 @@ import { registerPlugin } from '@capacitor/core'
|
||||
* worker.
|
||||
*/
|
||||
export interface TrekShellPlugin {
|
||||
getServer(): Promise<{ url: string | null }>
|
||||
getServer(): Promise<{ url: string | null }>;
|
||||
/** Remembers the server and loads it. The current page is gone afterwards. */
|
||||
setServer(options: { url: string }): Promise<void>
|
||||
setServer(options: { url: string }): Promise<void>;
|
||||
/** Forgets the server and returns to the address screen. */
|
||||
resetServer(): Promise<void>
|
||||
resetServer(): Promise<void>;
|
||||
/** Loads the remembered server again, after it could not be reached. */
|
||||
reload(): Promise<void>
|
||||
reload(): Promise<void>;
|
||||
/**
|
||||
* Opens `url` in the system browser and resolves with the URL it was sent
|
||||
* back to under `callbackScheme`. Rejects with code `CANCELLED` when the
|
||||
* user closes the browser.
|
||||
*/
|
||||
authenticate(options: { url: string; callbackScheme: string }): Promise<{ url: string }>
|
||||
authenticate(options: { url: string; callbackScheme: string }): Promise<{ url: string }>;
|
||||
/** iOS: stores the server's start page for a cold start without network. */
|
||||
refreshOfflineCopy(): Promise<{ saved: boolean }>
|
||||
refreshOfflineCopy(): Promise<{ saved: boolean }>;
|
||||
/** iOS: loads that copy under the server's origin. False when there is none. */
|
||||
openOfflineCopy(): Promise<{ opened: boolean }>
|
||||
openOfflineCopy(): Promise<{ opened: boolean }>;
|
||||
}
|
||||
|
||||
export const TrekShell = registerPlugin<TrekShellPlugin>('TrekShell')
|
||||
export const TrekShell = registerPlugin<TrekShellPlugin>('TrekShell');
|
||||
|
||||
export const APP_URL_SCHEME = 'com.liketrek.trek'
|
||||
export const APP_URL_SCHEME = 'com.liketrek.trek';
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
// FE-NATIVE-HANDOFF-PAGE-001 to FE-NATIVE-HANDOFF-PAGE-004
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent } from '../../tests/helpers/render'
|
||||
import NativeHandoffPage from './NativeHandoffPage'
|
||||
import { useNativeHandoff } from './nativeHandoff/useNativeHandoff'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen } from '../../tests/helpers/render';
|
||||
import NativeHandoffPage from './NativeHandoffPage';
|
||||
import { useNativeHandoff } from './nativeHandoff/useNativeHandoff';
|
||||
|
||||
vi.mock('./nativeHandoff/useNativeHandoff', () => ({ useNativeHandoff: vi.fn() }))
|
||||
vi.mock('./nativeHandoff/useNativeHandoff', () => ({ useNativeHandoff: vi.fn() }));
|
||||
|
||||
const base = {
|
||||
valid: true,
|
||||
@@ -13,41 +13,43 @@ const base = {
|
||||
status: 'idle' as const,
|
||||
openApp: vi.fn(),
|
||||
switchAccount: vi.fn(),
|
||||
}
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(useNativeHandoff).mockReturnValue({ ...base })
|
||||
})
|
||||
vi.mocked(useNativeHandoff).mockReturnValue({ ...base });
|
||||
});
|
||||
|
||||
describe('NativeHandoffPage', () => {
|
||||
it('FE-NATIVE-HANDOFF-PAGE-001: asks before handing the session to the app', () => {
|
||||
render(<NativeHandoffPage />)
|
||||
expect(screen.getByText('You are signed in as maria. Open the TREK app to finish signing in there.')).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Open the TREK app' }))
|
||||
expect(base.openApp).toHaveBeenCalled()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Use a different account' }))
|
||||
expect(base.switchAccount).toHaveBeenCalled()
|
||||
})
|
||||
render(<NativeHandoffPage />);
|
||||
expect(
|
||||
screen.getByText('You are signed in as maria. Open the TREK app to finish signing in there.')
|
||||
).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Open the TREK app' }));
|
||||
expect(base.openApp).toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Use a different account' }));
|
||||
expect(base.switchAccount).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-NATIVE-HANDOFF-PAGE-002: shows the failure and keeps the button while sending disabled', () => {
|
||||
vi.mocked(useNativeHandoff).mockReturnValue({ ...base, status: 'failed' })
|
||||
const { rerender } = render(<NativeHandoffPage />)
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Signing in did not work. Please try again.')
|
||||
vi.mocked(useNativeHandoff).mockReturnValue({ ...base, status: 'failed' });
|
||||
const { rerender } = render(<NativeHandoffPage />);
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Signing in did not work. Please try again.');
|
||||
|
||||
vi.mocked(useNativeHandoff).mockReturnValue({ ...base, status: 'sending' })
|
||||
rerender(<NativeHandoffPage />)
|
||||
expect(screen.getByRole('button', { name: 'Open the TREK app' })).toBeDisabled()
|
||||
})
|
||||
vi.mocked(useNativeHandoff).mockReturnValue({ ...base, status: 'sending' });
|
||||
rerender(<NativeHandoffPage />);
|
||||
expect(screen.getByRole('button', { name: 'Open the TREK app' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-NATIVE-HANDOFF-PAGE-003: spins while the session is being checked', () => {
|
||||
vi.mocked(useNativeHandoff).mockReturnValue({ ...base, ready: false })
|
||||
render(<NativeHandoffPage />)
|
||||
expect(screen.queryByRole('button')).not.toBeInTheDocument()
|
||||
})
|
||||
vi.mocked(useNativeHandoff).mockReturnValue({ ...base, ready: false });
|
||||
render(<NativeHandoffPage />);
|
||||
expect(screen.queryByRole('button')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-NATIVE-HANDOFF-PAGE-004: says so when the link is broken', () => {
|
||||
vi.mocked(useNativeHandoff).mockReturnValue({ ...base, valid: false, ready: false })
|
||||
render(<NativeHandoffPage />)
|
||||
expect(screen.getByText('Signing in did not work. Please try again.')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
vi.mocked(useNativeHandoff).mockReturnValue({ ...base, valid: false, ready: false });
|
||||
render(<NativeHandoffPage />);
|
||||
expect(screen.getByText('Signing in did not work. Please try again.')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,38 +1,53 @@
|
||||
import { Smartphone } from 'lucide-react'
|
||||
import { useTranslation } from '../i18n'
|
||||
import { useNativeHandoff } from './nativeHandoff/useNativeHandoff'
|
||||
import { Smartphone } from 'lucide-react';
|
||||
import { useTranslation } from '../i18n';
|
||||
import { useNativeHandoff } from './nativeHandoff/useNativeHandoff';
|
||||
|
||||
export default function NativeHandoffPage() {
|
||||
const { t } = useTranslation()
|
||||
const { valid, ready, userName, status, openApp, switchAccount } = useNativeHandoff()
|
||||
const { t } = useTranslation();
|
||||
const { valid, ready, userName, status, openApp, switchAccount } = useNativeHandoff();
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-surface-secondary p-6">
|
||||
<div className="w-full max-w-sm rounded-xl bg-surface-card border border-edge p-7 flex flex-col gap-4 text-center">
|
||||
<div className="flex min-h-screen items-center justify-center bg-surface-secondary p-6">
|
||||
<div className="flex w-full max-w-sm flex-col gap-4 rounded-xl border border-edge bg-surface-card p-7 text-center">
|
||||
<Smartphone className="mx-auto text-content-muted" size={32} aria-hidden />
|
||||
{!valid ? (
|
||||
<p className="text-body text-content">{t('native.login.failed')}</p>
|
||||
) : !ready ? (
|
||||
<div className="mx-auto w-8 h-8 border-4 border-edge border-t-accent rounded-full animate-spin" aria-label={t('common.loading')} />
|
||||
<div
|
||||
className="mx-auto h-8 w-8 animate-spin rounded-full border-4 border-edge border-t-accent"
|
||||
aria-label={t('common.loading')}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<h1 className="text-title font-semibold text-content">{t('native.handoff.title')}</h1>
|
||||
<p className="text-body text-content-muted">{t('native.handoff.hint', { name: userName })}</p>
|
||||
{status === 'failed' && <p role="alert" className="text-body text-danger">{t('native.login.failed')}</p>}
|
||||
{status === 'failed' && (
|
||||
<p role="alert" className="text-body text-danger">
|
||||
{t('native.login.failed')}
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { void openApp() }}
|
||||
onClick={() => {
|
||||
void openApp();
|
||||
}}
|
||||
disabled={status === 'sending'}
|
||||
className="w-full rounded-lg bg-accent text-accent-on py-3 font-semibold disabled:opacity-60"
|
||||
className="w-full rounded-lg bg-accent py-3 font-semibold text-accent-on disabled:opacity-60"
|
||||
>
|
||||
{t('native.handoff.open')}
|
||||
</button>
|
||||
<button type="button" onClick={() => { void switchAccount() }} className="text-caption text-content-muted py-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
void switchAccount();
|
||||
}}
|
||||
className="py-1 text-caption text-content-muted"
|
||||
>
|
||||
{t('native.handoff.switchAccount')}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
// FE-LOGIN-NATIVE-001 to FE-LOGIN-NATIVE-006: useLogin inside the iOS/Android app
|
||||
import React from 'react';
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { renderHook, act, waitFor } from '../../../tests/helpers/render';
|
||||
import { MemoryRouter } from 'react-router';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { resetAllStores } from '../../../tests/helpers/store';
|
||||
import { buildAppConfig } from '../../../tests/helpers/factories';
|
||||
import { TranslationProvider } from '../../i18n/TranslationContext';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { startAuthentication } from '@simplewebauthn/browser';
|
||||
import { markSignedOut, wasSignedOut } from '../../utils/signedOut';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import React from 'react';
|
||||
import { MemoryRouter } from 'react-router';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { buildAppConfig } from '../../../tests/helpers/factories';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { act, renderHook, waitFor } from '../../../tests/helpers/render';
|
||||
import { resetAllStores } from '../../../tests/helpers/store';
|
||||
import { TranslationProvider } from '../../i18n/TranslationContext';
|
||||
import { BrowserSignInCancelled, signInThroughBrowser } from '../../native/browserSignIn';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { markSignedOut, wasSignedOut } from '../../utils/signedOut';
|
||||
import { useLogin } from './useLogin';
|
||||
|
||||
// Stable across renders: useLogin's config effect depends on navigate.
|
||||
@@ -72,8 +72,8 @@ describe('useLogin in the native app', () => {
|
||||
it('FE-LOGIN-NATIVE-002: does not bounce an OIDC-only install to the IdP inside the WebView', async () => {
|
||||
server.use(
|
||||
http.get('/api/auth/app-config', () =>
|
||||
HttpResponse.json(buildAppConfig({ password_login: false, oidc_configured: true, oidc_login: true })),
|
||||
),
|
||||
HttpResponse.json(buildAppConfig({ password_login: false, oidc_configured: true, oidc_login: true }))
|
||||
)
|
||||
);
|
||||
const { result } = renderLogin();
|
||||
await waitFor(() => expect(result.current.appConfig).not.toBeNull());
|
||||
@@ -87,7 +87,9 @@ describe('useLogin in the native app', () => {
|
||||
const { result } = renderLogin();
|
||||
const event = clickEvent();
|
||||
|
||||
await act(async () => { result.current.handleSsoClick(event); });
|
||||
await act(async () => {
|
||||
result.current.handleSsoClick(event);
|
||||
});
|
||||
|
||||
expect(event.preventDefault).toHaveBeenCalled();
|
||||
expect(wasSignedOut()).toBe(false);
|
||||
@@ -100,7 +102,9 @@ describe('useLogin in the native app', () => {
|
||||
vi.mocked(signInThroughBrowser).mockResolvedValue();
|
||||
const { result } = renderLogin();
|
||||
|
||||
await act(async () => { await result.current.handlePasskeyLogin(); });
|
||||
await act(async () => {
|
||||
await result.current.handlePasskeyLogin();
|
||||
});
|
||||
|
||||
expect(signInThroughBrowser).toHaveBeenCalledWith(undefined);
|
||||
expect(startAuthentication).not.toHaveBeenCalled();
|
||||
@@ -110,7 +114,9 @@ describe('useLogin in the native app', () => {
|
||||
vi.mocked(signInThroughBrowser).mockRejectedValue(new BrowserSignInCancelled());
|
||||
const { result } = renderLogin();
|
||||
|
||||
await act(async () => { await result.current.handlePasskeyLogin(); });
|
||||
await act(async () => {
|
||||
await result.current.handlePasskeyLogin();
|
||||
});
|
||||
|
||||
expect(result.current.error).toBe('');
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
@@ -120,7 +126,9 @@ describe('useLogin in the native app', () => {
|
||||
vi.mocked(signInThroughBrowser).mockRejectedValue(new Error('exchange failed'));
|
||||
const { result } = renderLogin();
|
||||
|
||||
await act(async () => { await result.current.handlePasskeyLogin(); });
|
||||
await act(async () => {
|
||||
await result.current.handlePasskeyLogin();
|
||||
});
|
||||
|
||||
expect(result.current.error).toBe('Signing in did not work. Please try again.');
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
|
||||
@@ -1,119 +1,132 @@
|
||||
// FE-NATIVE-HANDOFF-001 to FE-NATIVE-HANDOFF-008
|
||||
import React from 'react'
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { renderHook, act, waitFor } from '../../../tests/helpers/render'
|
||||
import { MemoryRouter } from 'react-router'
|
||||
import { resetAllStores } from '../../../tests/helpers/store'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { requestHandoffCode } from '../../native/browserSignIn'
|
||||
import { useNativeHandoff } from './useNativeHandoff'
|
||||
import React from 'react';
|
||||
import { MemoryRouter } from 'react-router';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, renderHook, waitFor } from '../../../tests/helpers/render';
|
||||
import { resetAllStores } from '../../../tests/helpers/store';
|
||||
import { requestHandoffCode } from '../../native/browserSignIn';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useNativeHandoff } from './useNativeHandoff';
|
||||
|
||||
const mockNavigate = vi.fn()
|
||||
const mockNavigate = vi.fn();
|
||||
vi.mock('react-router', async () => {
|
||||
const actual = await vi.importActual<typeof import('react-router')>('react-router')
|
||||
return { ...actual, useNavigate: () => mockNavigate }
|
||||
})
|
||||
vi.mock('../../native/browserSignIn', () => ({ HANDOFF_PATH: '/native-handoff', requestHandoffCode: vi.fn() }))
|
||||
const actual = await vi.importActual<typeof import('react-router')>('react-router');
|
||||
return { ...actual, useNavigate: () => mockNavigate };
|
||||
});
|
||||
vi.mock('../../native/browserSignIn', () => ({ HANDOFF_PATH: '/native-handoff', requestHandoffCode: vi.fn() }));
|
||||
|
||||
const challenge = 'ab'.repeat(32)
|
||||
const realLocation = window.location
|
||||
const logout = vi.fn(async () => {})
|
||||
const challenge = 'ab'.repeat(32);
|
||||
const realLocation = window.location;
|
||||
const logout = vi.fn(async () => {});
|
||||
|
||||
function setSearch(search: string) {
|
||||
Object.defineProperty(window, 'location', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: { ...realLocation, search, href: 'http://localhost/native-handoff' + search, replace: vi.fn() },
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
function renderHandoff() {
|
||||
return renderHook(() => useNativeHandoff(), {
|
||||
wrapper: ({ children }: { children: React.ReactNode }) => <MemoryRouter>{children}</MemoryRouter>,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores()
|
||||
mockNavigate.mockClear()
|
||||
logout.mockClear()
|
||||
vi.mocked(requestHandoffCode).mockReset()
|
||||
sessionStorage.clear()
|
||||
setSearch(`?challenge=${challenge}`)
|
||||
useAuthStore.setState({ isLoading: false, isAuthenticated: true, user: { id: 1, username: 'maria' } as never, logout })
|
||||
})
|
||||
resetAllStores();
|
||||
mockNavigate.mockClear();
|
||||
logout.mockClear();
|
||||
vi.mocked(requestHandoffCode).mockReset();
|
||||
sessionStorage.clear();
|
||||
setSearch(`?challenge=${challenge}`);
|
||||
useAuthStore.setState({
|
||||
isLoading: false,
|
||||
isAuthenticated: true,
|
||||
user: { id: 1, username: 'maria' } as never,
|
||||
logout,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
Object.defineProperty(window, 'location', { configurable: true, writable: true, value: realLocation })
|
||||
})
|
||||
Object.defineProperty(window, 'location', { configurable: true, writable: true, value: realLocation });
|
||||
});
|
||||
|
||||
describe('useNativeHandoff', () => {
|
||||
it('FE-NATIVE-HANDOFF-001: is ready for a signed-in user with a valid challenge', () => {
|
||||
const { result } = renderHandoff()
|
||||
expect(result.current.valid).toBe(true)
|
||||
expect(result.current.ready).toBe(true)
|
||||
expect(result.current.userName).toBe('maria')
|
||||
expect(mockNavigate).not.toHaveBeenCalled()
|
||||
})
|
||||
const { result } = renderHandoff();
|
||||
expect(result.current.valid).toBe(true);
|
||||
expect(result.current.ready).toBe(true);
|
||||
expect(result.current.userName).toBe('maria');
|
||||
expect(mockNavigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-NATIVE-HANDOFF-002: rejects a malformed challenge and does nothing with it', () => {
|
||||
setSearch('?challenge=nope')
|
||||
useAuthStore.setState({ isAuthenticated: false })
|
||||
const { result } = renderHandoff()
|
||||
expect(result.current.valid).toBe(false)
|
||||
expect(result.current.ready).toBe(false)
|
||||
expect(mockNavigate).not.toHaveBeenCalled()
|
||||
})
|
||||
setSearch('?challenge=nope');
|
||||
useAuthStore.setState({ isAuthenticated: false });
|
||||
const { result } = renderHandoff();
|
||||
expect(result.current.valid).toBe(false);
|
||||
expect(result.current.ready).toBe(false);
|
||||
expect(mockNavigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-NATIVE-HANDOFF-003: sends a visitor to the login page and back here afterwards', () => {
|
||||
useAuthStore.setState({ isAuthenticated: false })
|
||||
renderHandoff()
|
||||
useAuthStore.setState({ isAuthenticated: false });
|
||||
renderHandoff();
|
||||
expect(mockNavigate).toHaveBeenCalledWith(
|
||||
`/login?redirect=${encodeURIComponent(`/native-handoff?challenge=${challenge}`)}`,
|
||||
{ replace: true },
|
||||
)
|
||||
})
|
||||
{ replace: true }
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-NATIVE-HANDOFF-004: starts SSO straight away when the app asked for it, without looping', () => {
|
||||
setSearch(`?challenge=${challenge}&start=oidc`)
|
||||
useAuthStore.setState({ isAuthenticated: false })
|
||||
renderHandoff()
|
||||
expect(window.location.replace).toHaveBeenCalledWith('/api/auth/oidc/login?remember=1')
|
||||
expect(sessionStorage.getItem('oidc_redirect')).toBe(`/native-handoff?challenge=${challenge}`)
|
||||
})
|
||||
setSearch(`?challenge=${challenge}&start=oidc`);
|
||||
useAuthStore.setState({ isAuthenticated: false });
|
||||
renderHandoff();
|
||||
expect(window.location.replace).toHaveBeenCalledWith('/api/auth/oidc/login?remember=1');
|
||||
expect(sessionStorage.getItem('oidc_redirect')).toBe(`/native-handoff?challenge=${challenge}`);
|
||||
});
|
||||
|
||||
it('FE-NATIVE-HANDOFF-005: waits while the session is still being checked', () => {
|
||||
useAuthStore.setState({ isAuthenticated: false, isLoading: true })
|
||||
const { result } = renderHandoff()
|
||||
expect(result.current.ready).toBe(false)
|
||||
expect(mockNavigate).not.toHaveBeenCalled()
|
||||
})
|
||||
useAuthStore.setState({ isAuthenticated: false, isLoading: true });
|
||||
const { result } = renderHandoff();
|
||||
expect(result.current.ready).toBe(false);
|
||||
expect(mockNavigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-NATIVE-HANDOFF-006: only mints the code on the tap, then hands it to the app scheme', async () => {
|
||||
vi.mocked(requestHandoffCode).mockResolvedValue('c/1')
|
||||
const { result } = renderHandoff()
|
||||
expect(requestHandoffCode).not.toHaveBeenCalled()
|
||||
vi.mocked(requestHandoffCode).mockResolvedValue('c/1');
|
||||
const { result } = renderHandoff();
|
||||
expect(requestHandoffCode).not.toHaveBeenCalled();
|
||||
|
||||
await act(async () => { await result.current.openApp() })
|
||||
await act(async () => {
|
||||
await result.current.openApp();
|
||||
});
|
||||
|
||||
expect(requestHandoffCode).toHaveBeenCalledWith(challenge)
|
||||
expect(window.location.href).toBe('com.liketrek.trek://auth?code=c%2F1')
|
||||
})
|
||||
expect(requestHandoffCode).toHaveBeenCalledWith(challenge);
|
||||
expect(window.location.href).toBe('com.liketrek.trek://auth?code=c%2F1');
|
||||
});
|
||||
|
||||
it('FE-NATIVE-HANDOFF-007: reports a failed hand-off', async () => {
|
||||
vi.mocked(requestHandoffCode).mockRejectedValue(new Error('401'))
|
||||
const { result } = renderHandoff()
|
||||
await act(async () => { await result.current.openApp() })
|
||||
expect(result.current.status).toBe('failed')
|
||||
})
|
||||
vi.mocked(requestHandoffCode).mockRejectedValue(new Error('401'));
|
||||
const { result } = renderHandoff();
|
||||
await act(async () => {
|
||||
await result.current.openApp();
|
||||
});
|
||||
expect(result.current.status).toBe('failed');
|
||||
});
|
||||
|
||||
it('FE-NATIVE-HANDOFF-008: lets the user switch accounts and come back', async () => {
|
||||
const { result } = renderHandoff()
|
||||
await act(async () => { await result.current.switchAccount() })
|
||||
expect(logout).toHaveBeenCalled()
|
||||
await waitFor(() => expect(mockNavigate).toHaveBeenCalledWith(
|
||||
`/login?redirect=${encodeURIComponent(`/native-handoff?challenge=${challenge}`)}`,
|
||||
{ replace: true },
|
||||
))
|
||||
})
|
||||
})
|
||||
const { result } = renderHandoff();
|
||||
await act(async () => {
|
||||
await result.current.switchAccount();
|
||||
});
|
||||
expect(logout).toHaveBeenCalled();
|
||||
await waitFor(() =>
|
||||
expect(mockNavigate).toHaveBeenCalledWith(
|
||||
`/login?redirect=${encodeURIComponent(`/native-handoff?challenge=${challenge}`)}`,
|
||||
{ replace: true }
|
||||
)
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import { useShallow } from 'zustand/react/shallow'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { APP_URL_SCHEME } from '../../native/trekShell'
|
||||
import { HANDOFF_PATH, requestHandoffCode } from '../../native/browserSignIn'
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { useShallow } from 'zustand/react/shallow';
|
||||
import { HANDOFF_PATH, requestHandoffCode } from '../../native/browserSignIn';
|
||||
import { APP_URL_SCHEME } from '../../native/trekShell';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
|
||||
const CHALLENGE = /^[0-9a-f]{64}$/
|
||||
const CHALLENGE = /^[0-9a-f]{64}$/;
|
||||
|
||||
/**
|
||||
* The system-browser end of the app's sign-in (see native/browserSignIn.ts).
|
||||
@@ -14,45 +14,47 @@ const CHALLENGE = /^[0-9a-f]{64}$/
|
||||
* must not be able to pass a session on silently.
|
||||
*/
|
||||
export function useNativeHandoff() {
|
||||
const navigate = useNavigate()
|
||||
const { isAuthenticated, isLoading, userName, logout } = useAuthStore(useShallow((s) => ({
|
||||
isAuthenticated: s.isAuthenticated,
|
||||
isLoading: s.isLoading,
|
||||
userName: s.user?.username ?? '',
|
||||
logout: s.logout,
|
||||
})))
|
||||
const [params] = useState(() => new URLSearchParams(window.location.search))
|
||||
const challenge = params.get('challenge') ?? ''
|
||||
const valid = CHALLENGE.test(challenge)
|
||||
const [status, setStatus] = useState<'idle' | 'sending' | 'failed'>('idle')
|
||||
const navigate = useNavigate();
|
||||
const { isAuthenticated, isLoading, userName, logout } = useAuthStore(
|
||||
useShallow((s) => ({
|
||||
isAuthenticated: s.isAuthenticated,
|
||||
isLoading: s.isLoading,
|
||||
userName: s.user?.username ?? '',
|
||||
logout: s.logout,
|
||||
}))
|
||||
);
|
||||
const [params] = useState(() => new URLSearchParams(window.location.search));
|
||||
const challenge = params.get('challenge') ?? '';
|
||||
const valid = CHALLENGE.test(challenge);
|
||||
const [status, setStatus] = useState<'idle' | 'sending' | 'failed'>('idle');
|
||||
|
||||
// Back here once signed in, without `start`, so an SSO round trip cannot loop.
|
||||
const returnPath = `${HANDOFF_PATH}?challenge=${challenge}`
|
||||
const returnPath = `${HANDOFF_PATH}?challenge=${challenge}`;
|
||||
|
||||
useEffect(() => {
|
||||
if (!valid || isLoading || isAuthenticated) return
|
||||
if (!valid || isLoading || isAuthenticated) return;
|
||||
if (params.get('start') === 'oidc') {
|
||||
sessionStorage.setItem('oidc_redirect', returnPath)
|
||||
window.location.replace('/api/auth/oidc/login?remember=1')
|
||||
return
|
||||
sessionStorage.setItem('oidc_redirect', returnPath);
|
||||
window.location.replace('/api/auth/oidc/login?remember=1');
|
||||
return;
|
||||
}
|
||||
void navigate(`/login?redirect=${encodeURIComponent(returnPath)}`, { replace: true })
|
||||
}, [valid, isLoading, isAuthenticated, params, returnPath, navigate])
|
||||
void navigate(`/login?redirect=${encodeURIComponent(returnPath)}`, { replace: true });
|
||||
}, [valid, isLoading, isAuthenticated, params, returnPath, navigate]);
|
||||
|
||||
const openApp = async (): Promise<void> => {
|
||||
setStatus('sending')
|
||||
setStatus('sending');
|
||||
try {
|
||||
const code = await requestHandoffCode(challenge)
|
||||
window.location.href = `${APP_URL_SCHEME}://auth?code=${encodeURIComponent(code)}`
|
||||
const code = await requestHandoffCode(challenge);
|
||||
window.location.href = `${APP_URL_SCHEME}://auth?code=${encodeURIComponent(code)}`;
|
||||
} catch {
|
||||
setStatus('failed')
|
||||
setStatus('failed');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const switchAccount = async (): Promise<void> => {
|
||||
await logout()
|
||||
void navigate(`/login?redirect=${encodeURIComponent(returnPath)}`, { replace: true })
|
||||
}
|
||||
await logout();
|
||||
void navigate(`/login?redirect=${encodeURIComponent(returnPath)}`, { replace: true });
|
||||
};
|
||||
|
||||
return {
|
||||
valid,
|
||||
@@ -61,5 +63,5 @@ export function useNativeHandoff() {
|
||||
status,
|
||||
openApp,
|
||||
switchAccount,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,47 +1,49 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { downloadBlob, downloadFile, openFile } from '../../../src/utils/fileDownload'
|
||||
import { shareFile } from '../../../src/native/nativeFiles'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { shareFile } from '../../../src/native/nativeFiles';
|
||||
import { downloadBlob, downloadFile, openFile } from '../../../src/utils/fileDownload';
|
||||
|
||||
vi.mock('../../../src/db/offlineDb', () => ({ getCachedBlob: vi.fn() }))
|
||||
vi.mock('../../../src/native/platform', () => ({ isNativeApp: () => true }))
|
||||
vi.mock('../../../src/db/offlineDb', () => ({ getCachedBlob: vi.fn() }));
|
||||
vi.mock('../../../src/native/platform', () => ({ isNativeApp: () => true }));
|
||||
vi.mock('../../../src/native/nativeFiles', async () => {
|
||||
const actual = await vi.importActual<typeof import('../../../src/native/nativeFiles')>('../../../src/native/nativeFiles')
|
||||
return { ...actual, shareFile: vi.fn() }
|
||||
})
|
||||
const actual = await vi.importActual<typeof import('../../../src/native/nativeFiles')>(
|
||||
'../../../src/native/nativeFiles'
|
||||
);
|
||||
return { ...actual, shareFile: vi.fn() };
|
||||
});
|
||||
|
||||
const pdf = new Blob(['%PDF'], { type: 'application/pdf' })
|
||||
const pdf = new Blob(['%PDF'], { type: 'application/pdf' });
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(shareFile).mockReset().mockResolvedValue()
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, status: 200, blob: () => Promise.resolve(pdf) }))
|
||||
})
|
||||
vi.mocked(shareFile).mockReset().mockResolvedValue();
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, status: 200, blob: () => Promise.resolve(pdf) }));
|
||||
});
|
||||
|
||||
describe('fileDownload inside the native app', () => {
|
||||
it('hands an in-memory blob to the share sheet instead of an anchor', () => {
|
||||
const click = vi.spyOn(HTMLAnchorElement.prototype, 'click')
|
||||
downloadBlob(pdf, 'report.pdf')
|
||||
expect(shareFile).toHaveBeenCalledWith(pdf, 'report.pdf')
|
||||
expect(click).not.toHaveBeenCalled()
|
||||
})
|
||||
const click = vi.spyOn(HTMLAnchorElement.prototype, 'click');
|
||||
downloadBlob(pdf, 'report.pdf');
|
||||
expect(shareFile).toHaveBeenCalledWith(pdf, 'report.pdf');
|
||||
expect(click).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('logs a share that failed rather than losing it', async () => {
|
||||
const report = vi.fn()
|
||||
vi.stubGlobal('reportError', report)
|
||||
vi.mocked(shareFile).mockRejectedValue(new Error('no space'))
|
||||
downloadBlob(pdf, 'report.pdf')
|
||||
await vi.waitFor(() => expect(report).toHaveBeenCalledWith(expect.any(Error)))
|
||||
})
|
||||
const report = vi.fn();
|
||||
vi.stubGlobal('reportError', report);
|
||||
vi.mocked(shareFile).mockRejectedValue(new Error('no space'));
|
||||
downloadBlob(pdf, 'report.pdf');
|
||||
await vi.waitFor(() => expect(report).toHaveBeenCalledWith(expect.any(Error)));
|
||||
});
|
||||
|
||||
it('shares a protected file under its given name, or the one from its URL', async () => {
|
||||
await downloadFile('/api/trips/1/files/2/download', 'Boarding pass.pdf')
|
||||
expect(shareFile).toHaveBeenLastCalledWith(pdf, 'Boarding pass.pdf')
|
||||
await downloadFile('/api/trips/1/files/2/download', 'Boarding pass.pdf');
|
||||
expect(shareFile).toHaveBeenLastCalledWith(pdf, 'Boarding pass.pdf');
|
||||
|
||||
await downloadFile('/uploads/files/ticket%20A.pdf')
|
||||
expect(shareFile).toHaveBeenLastCalledWith(pdf, 'ticket A.pdf')
|
||||
})
|
||||
await downloadFile('/uploads/files/ticket%20A.pdf');
|
||||
expect(shareFile).toHaveBeenLastCalledWith(pdf, 'ticket A.pdf');
|
||||
});
|
||||
|
||||
it('opens files through the share sheet too, since there is no tab to open them in', async () => {
|
||||
await openFile('/api/trips/1/files/2/download')
|
||||
expect(shareFile).toHaveBeenLastCalledWith(pdf, 'download')
|
||||
})
|
||||
})
|
||||
await openFile('/api/trips/1/files/2/download');
|
||||
expect(shareFile).toHaveBeenLastCalledWith(pdf, 'download');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -124,7 +124,11 @@ describe('Native sign-in hand-off e2e', () => {
|
||||
});
|
||||
|
||||
it('NATIVE-E2E-005: rate-limits the exchange per ip', async () => {
|
||||
await Promise.all(Array.from({ length: 20 }, (_, i) => exchange({ code: `nope-${i}`, verifier })));
|
||||
// One after another: twenty requests at once reset the ephemeral test server's connections.
|
||||
await Array.from({ length: 20 }).reduce<Promise<unknown>>(
|
||||
(previous, _, i) => previous.then(() => exchange({ code: `nope-${i}`, verifier })),
|
||||
Promise.resolve(),
|
||||
);
|
||||
const blocked = await exchange({ code: 'nope', verifier });
|
||||
expect(blocked.status).toBe(429);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user