diff --git a/apps/app/tests/unit/vite.trialConfig.test.ts b/apps/app/tests/unit/vite.trialConfig.test.ts new file mode 100644 index 00000000..b5b0d19d --- /dev/null +++ b/apps/app/tests/unit/vite.trialConfig.test.ts @@ -0,0 +1,103 @@ +// @vitest-environment node +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { resolveConfig } from 'vite' +import { afterEach, describe, expect, it, vi } from 'vitest' + +const CONFIG = fileURLToPath( + new URL('../../vite/trial.config.ts', import.meta.url), +) +const SANDBOX_SCRIPT = fileURLToPath( + new URL('../../../../scripts/db-sandbox.sh', import.meta.url), +) +const ROUTES = ['/auth/v1', '/rest/v1', '/storage/v1'] +const HOST = '127.0.0.1' + +const b64 = (value: unknown) => + Buffer.from(JSON.stringify(value)).toString('base64url') +const key = (iss: string) => + `${b64({ alg: 'HS256', typ: 'JWT' })}.${b64({ role: 'anon', iss })}.signature` + +function stubStack(gateway: string, appPort: number, iss: string) { + vi.stubEnv('FAUNOSTEO_TRIAL_GATEWAY', gateway) + vi.stubEnv('FAUNOSTEO_TRIAL_HOST', HOST) + vi.stubEnv('VITE_SUPABASE_URL', `http://${HOST}:${appPort}`) + vi.stubEnv('VITE_SUPABASE_ANON_KEY', key(iss)) +} +const resolveOn = (port: number) => + resolveConfig( + { configFile: CONFIG, server: { host: HOST, port, strictPort: true } }, + 'serve', + ) +const proxyTargets = (config: Awaited>) => + ROUTES.map((route) => { + const entry = config.server.proxy?.[route] + return typeof entry === 'string' ? entry : entry?.target + }) + +afterEach(() => { + vi.unstubAllEnvs() + vi.unstubAllGlobals() +}) + +describe('shared trial dev server config, as Vite resolves it', () => { + it('db:sandbox trial: proxies to 57801 on 5193, never probes', async () => { + const fetch = vi.fn() + vi.stubGlobal('fetch', fetch) + stubStack('http://127.0.0.1:57801', 5193, 'db-sandbox') + const config = await resolveOn(5193) + expect(proxyTargets(config)).toEqual( + Array(3).fill('http://127.0.0.1:57801'), + ) + expect(config.server.port).toBe(5193) + expect(fetch).not.toHaveBeenCalled() + }) + + it('db:trial app: proxies to 58801 on 5194 once the gateway names itself', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('faunosteo_trial\n')), + ) + stubStack('http://127.0.0.1:58801', 5194, 'faunosteo-trial') + const config = await resolveOn(5194) + expect(proxyTargets(config)).toEqual( + Array(3).fill('http://127.0.0.1:58801'), + ) + }) + + it('refuses the trial stack on the sandbox port', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('faunosteo_trial\n')), + ) + stubStack('http://127.0.0.1:58801', 5194, 'faunosteo-trial') + await expect(resolveOn(5193)).rejects.toThrow(/Refused/) + }) + + it('refuses a trial gateway that does not name itself', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('other\n')), + ) + stubStack('http://127.0.0.1:58801', 5194, 'faunosteo-trial') + await expect(resolveOn(5194)).rejects.toThrow(/does not answer/) + }) +}) + +describe('the sandbox values above are the ones scripts/db-sandbox.sh passes', () => { + it('keeps its trial gateway, app port, key issuer and the way it passes them to Vite', () => { + // Pins what `pnpm db:sandbox trial` passes (non-regression of the shared config): a failure + // means the shared config and the script must be re-checked together. + const script = readFileSync(SANDBOX_SCRIPT, 'utf8') + expect(script).toContain('PORT_TRIAL_GATEWAY=57801') + expect(script).toContain('PORT_TRIAL_APP=5193') + expect(script).toContain('iss: "db-sandbox"') + expect(script).toContain( + 'FAUNOSTEO_TRIAL_GATEWAY="http://127.0.0.1:$PORT_TRIAL_GATEWAY"', + ) + expect(script).toContain( + 'VITE_SUPABASE_URL="http://$TRIAL_HOST:$PORT_TRIAL_APP"', + ) + expect(script).toContain('--port $PORT_TRIAL_APP --strictPort') + }) +}) diff --git a/apps/app/tests/unit/vite.trialTargets.test.ts b/apps/app/tests/unit/vite.trialTargets.test.ts new file mode 100644 index 00000000..45c473a3 --- /dev/null +++ b/apps/app/tests/unit/vite.trialTargets.test.ts @@ -0,0 +1,242 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + appPortProblem, + checkGatewayIdentity, + jwtClaims, + targetPortGuard, + TRIAL_TARGETS, + trialTarget, +} from '../../vite/trial-targets' + +const b64 = (value: unknown) => + btoa(JSON.stringify(value)) + .replace(/\+/g, '-') + .replace(/\//g, '_') + .replace(/=+$/, '') +const key = (claims: Record) => + `${b64({ alg: 'HS256', typ: 'JWT' })}.${b64(claims)}.signature` + +const HOST = '192.168.1.100' +/** Exactly what scripts/db-sandbox.sh cmd_trial passes (non-regression, A12). */ +const SANDBOX = { + FAUNOSTEO_TRIAL_GATEWAY: 'http://127.0.0.1:57801', + FAUNOSTEO_TRIAL_HOST: HOST, + VITE_SUPABASE_URL: `http://${HOST}:5193`, + VITE_SUPABASE_ANON_KEY: key({ role: 'anon', iss: 'db-sandbox' }), +} +/** What scripts/db-trial.sh cmd_app passes. */ +const TRIAL = { + FAUNOSTEO_TRIAL_GATEWAY: 'http://127.0.0.1:58801', + FAUNOSTEO_TRIAL_HOST: HOST, + VITE_SUPABASE_URL: `http://${HOST}:5194`, + VITE_SUPABASE_ANON_KEY: key({ role: 'anon', iss: 'faunosteo-trial' }), +} +const [sandbox, trial] = TRIAL_TARGETS + +describe('trial dev server target', () => { + it('holds exactly the two stacks, sandbox first', () => { + expect(TRIAL_TARGETS.map((t) => t.name)).toEqual(['sandbox', 'trial']) + }) + + it('accepts the values db:sandbox trial passes, unchanged, without a probe', () => { + expect(trialTarget(SANDBOX)).toBe(sandbox) + expect(sandbox.identity).toBeUndefined() + expect(appPortProblem(sandbox, 5193, true)).toBeNull() + }) + + it('accepts the values db:trial app passes, with the gateway identity', () => { + expect(trialTarget(TRIAL)).toBe(trial) + expect(trial.identity).toBe('faunosteo_trial\n') + expect(appPortProblem(trial, 5194, true)).toBeNull() + }) + + it.each([ + [ + 'the DEV gateway', + { ...TRIAL, FAUNOSTEO_TRIAL_GATEWAY: 'http://127.0.0.1:54321' }, + ], + [ + "the sandbox's other gateway (avatar and sheet-assets e2e)", + { ...SANDBOX, FAUNOSTEO_TRIAL_GATEWAY: 'http://127.0.0.1:57800' }, + ], + [ + 'another loopback port', + { ...TRIAL, FAUNOSTEO_TRIAL_GATEWAY: 'http://127.0.0.1:58802' }, + ], + [ + 'a trailing slash', + { ...TRIAL, FAUNOSTEO_TRIAL_GATEWAY: 'http://127.0.0.1:58801/' }, + ], + [ + 'localhost', + { ...TRIAL, FAUNOSTEO_TRIAL_GATEWAY: 'http://localhost:58801' }, + ], + ['no gateway', { ...TRIAL, FAUNOSTEO_TRIAL_GATEWAY: undefined }], + [ + 'the trial gateway with the sandbox app URL', + { ...TRIAL, VITE_SUPABASE_URL: `http://${HOST}:5193` }, + ], + [ + 'the sandbox gateway with a trial key', + { ...SANDBOX, VITE_SUPABASE_ANON_KEY: TRIAL.VITE_SUPABASE_ANON_KEY }, + ], + [ + 'the trial gateway with a sandbox key', + { ...TRIAL, VITE_SUPABASE_ANON_KEY: SANDBOX.VITE_SUPABASE_ANON_KEY }, + ], + ['a missing key', { ...TRIAL, VITE_SUPABASE_ANON_KEY: undefined }], + ['no host', { ...TRIAL, FAUNOSTEO_TRIAL_HOST: undefined }], + ['an empty host', { ...TRIAL, FAUNOSTEO_TRIAL_HOST: '' }], + [ + 'a service key', + { + ...TRIAL, + VITE_SUPABASE_ANON_KEY: key({ + role: 'service_role', + iss: 'faunosteo-trial', + }), + }, + ], + [ + 'an app URL on another host', + { ...TRIAL, VITE_SUPABASE_URL: 'http://10.0.0.9:5194' }, + ], + ])('refuses %s', (_label, env) => { + expect(() => trialTarget(env)).toThrow() + }) + + it.each([ + ['the trial gateway behind the sandbox app port', trial, 5193, true], + ['the sandbox gateway behind the trial app port', sandbox, 5194, true], + ['a port Vite may change', trial, 5194, false], + ] as const)('refuses %s', (_label, target, port, strict) => { + expect(appPortProblem(target, port, strict)).not.toBeNull() + }) + + it('reads a JWT payload only when it is one', () => { + expect(jwtClaims(TRIAL.VITE_SUPABASE_ANON_KEY)?.iss).toBe('faunosteo-trial') + expect(jwtClaims('not-a-jwt')).toBeNull() + expect(jwtClaims(`x.${b64(['iss'])}.y`)).toBeNull() + }) +}) + +/** A response of any 2xx status, even those a Response cannot carry a body with. */ +const answerWith = (status: number, body: string) => + ({ ok: true, status, text: async () => body }) as unknown as Response + +describe('trial gateway identity probe', () => { + afterEach(() => { + vi.useRealTimers() + vi.unstubAllGlobals() + }) + + it('accepts exactly faunosteo_trial and a newline, asked without redirects', async () => { + const fetch = vi.fn(async () => new Response('faunosteo_trial\n')) + vi.stubGlobal('fetch', fetch) + await expect(checkGatewayIdentity(trial)).resolves.toBeUndefined() + expect(fetch).toHaveBeenCalledWith( + 'http://127.0.0.1:58801/__faunosteo_stack', + expect.objectContaining({ redirect: 'error' }), + ) + }) + + it.each([ + ['a body without its newline', async () => new Response('faunosteo_trial')], + ['another service', async () => new Response('other\n')], + [ + 'a body with a second newline', + async () => new Response('faunosteo_trial\n\n'), + ], + [ + 'a body with a leading space', + async () => new Response(' faunosteo_trial\n'), + ], + ['a body with CRLF', async () => new Response('faunosteo_trial\r\n')], + [ + 'a 204 carrying the exact body', + async () => answerWith(204, 'faunosteo_trial\n'), + ], + [ + 'a 206 carrying the exact body', + async () => answerWith(206, 'faunosteo_trial\n'), + ], + ['a 404', async () => new Response('faunosteo_trial\n', { status: 404 })], + [ + 'a redirect', + async () => + new Response(null, { + status: 302, + headers: { location: 'http://127.0.0.1:57801/' }, + }), + ], + [ + 'a refused redirect', + async () => Promise.reject(new TypeError('unexpected redirect')), + ], + ['no answer', async () => Promise.reject(new TypeError('fetch failed'))], + ])('refuses %s', async (_label, answer) => { + vi.stubGlobal('fetch', vi.fn(answer)) + await expect(checkGatewayIdentity(trial)).rejects.toThrow(/does not answer/) + }) + + it('gives up after 3 s on a gateway that never answers', async () => { + vi.useFakeTimers() + let init: RequestInit | undefined + vi.stubGlobal( + 'fetch', + vi.fn( + (_url: string, options: RequestInit) => + new Promise((_resolve, reject) => { + init = options + options.signal?.addEventListener('abort', () => + reject(new TypeError('aborted')), + ) + }), + ), + ) + const outcome = expect(checkGatewayIdentity(trial)).rejects.toThrow( + /does not answer/, + ) + await vi.advanceTimersByTimeAsync(3001) + await outcome + expect(init?.signal).toBeDefined() + expect(init?.redirect).toBe('error') + vi.useRealTimers() + }) + + it('never probes the sandbox gateway (db-sandbox.sh unchanged, A12)', async () => { + const fetch = vi.fn() + vi.stubGlobal('fetch', fetch) + await expect(checkGatewayIdentity(sandbox)).resolves.toBeUndefined() + expect(fetch).not.toHaveBeenCalled() + }) +}) + +describe('trial dev server port guard (configResolved)', () => { + const resolved = ( + port: number | undefined, + strictPort: boolean | undefined, + ) => ({ + server: { port, strictPort }, + }) + + it('accepts each stack on its own port with strictPort', () => { + expect(() => + targetPortGuard(trial).configResolved(resolved(5194, true)), + ).not.toThrow() + expect(() => + targetPortGuard(sandbox).configResolved(resolved(5193, true)), + ).not.toThrow() + }) + + it.each([ + ['the trial stack on the sandbox port', trial, 5193, true], + ['the sandbox on the trial port', sandbox, 5194, true], + ['no strictPort', trial, 5194, false], + ['no port', trial, undefined, true], + ] as const)('refuses %s', (_label, target, port, strict) => { + expect(() => + targetPortGuard(target).configResolved(resolved(port, strict)), + ).toThrow(/Refused/) + }) +}) diff --git a/apps/app/vite/trial-targets.ts b/apps/app/vite/trial-targets.ts new file mode 100644 index 00000000..513e4ac5 --- /dev/null +++ b/apps/app/vite/trial-targets.ts @@ -0,0 +1,140 @@ +/** + * The two stacks the trial dev server (vite/trial.config.ts) may proxy to, and nothing else + * (docs/development/TRIAL_STACK.md §3.6, R13): `pnpm db:sandbox trial` (app 5193, sandbox + * gateway 57801, keys of the issuer db-sandbox) and `pnpm db:trial app` (app 5194, trial gateway + * 58801, keys of the issuer faunosteo-trial, a gateway that names itself). The exact gateway + * string picks the target; every other value it implies must match, or the server does not + * start. No default, no fallback to another stack. + */ +export interface TrialTarget { + readonly name: 'sandbox' | 'trial' + readonly appPort: number + readonly gateway: string + readonly issuer: string + /** + * The exact body of the gateway's GET /__faunosteo_stack; absent: no probe + * (the sandbox gateway, A12). + */ + readonly identity?: string +} + +export const TRIAL_TARGETS: readonly TrialTarget[] = [ + { + name: 'sandbox', + appPort: 5193, + gateway: 'http://127.0.0.1:57801', + issuer: 'db-sandbox', + }, + { + name: 'trial', + appPort: 5194, + gateway: 'http://127.0.0.1:58801', + issuer: 'faunosteo-trial', + identity: 'faunosteo_trial\n', + }, +] + +type Env = Readonly> + +/** + * The claims of a JWT payload, or null. Identity only: no secret here, so no signature check + * (scripts/db-trial.sh checks it with the stack's secret before it hands a key to Vite). + */ +export function jwtClaims( + token: string | undefined, +): Record | null { + const payload = token?.split('.')[1] + if (!payload || !/^[A-Za-z0-9_-]+$/.test(payload)) return null + try { + const base64 = payload.replace(/-/g, '+').replace(/_/g, '/') + const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, '=') + const claims: unknown = JSON.parse(atob(padded)) + return typeof claims === 'object' && + claims !== null && + !Array.isArray(claims) + ? (claims as Record) + : null + } catch { + return null + } +} + +/** The one target `env` names, every value it implies checked; throws otherwise. */ +export function trialTarget(env: Env): TrialTarget { + const target = TRIAL_TARGETS.find( + (entry) => entry.gateway === env.FAUNOSTEO_TRIAL_GATEWAY, + ) + if (!target) + throw new Error( + 'FAUNOSTEO_TRIAL_GATEWAY is neither the gateway of pnpm db:sandbox trial ' + + '(http://127.0.0.1:57801) nor that of pnpm db:trial app (http://127.0.0.1:58801)', + ) + const claims = jwtClaims(env.VITE_SUPABASE_ANON_KEY) + if (claims?.role !== 'anon' || claims.iss !== target.issuer) + throw new Error( + `VITE_SUPABASE_ANON_KEY is not an anon key of the issuer ${target.issuer} ` + + `(${target.name} stack)`, + ) + const host = env.FAUNOSTEO_TRIAL_HOST ?? '' + if (!host || env.VITE_SUPABASE_URL !== `http://${host}:${target.appPort}`) + throw new Error( + `VITE_SUPABASE_URL must be http://:${target.appPort} ` + + `(${target.name} stack)`, + ) + return target +} + +/** Why Vite's resolved port does not fit the target, or null (the CLI's --port is resolved in). */ +export function appPortProblem( + target: TrialTarget, + port: number | undefined, + strictPort: boolean | undefined, +): string | null { + if (port === target.appPort && strictPort === true) return null + return `the ${target.name} trial app runs on port ${target.appPort} with --strictPort only` +} + +/** + * The part of Vite's resolved config the guard reads (structural: no import of Vite's types + * here). + */ +export interface ResolvedServerPort { + readonly server: { readonly port?: number; readonly strictPort?: boolean } +} + +/** A Vite plugin that refuses, once the CLI is resolved in, any port but the target's. */ +export function targetPortGuard(target: TrialTarget): { + name: string + configResolved(config: ResolvedServerPort): void +} { + return { + name: 'faunosteo-trial-target-port', + configResolved(config) { + const problem = appPortProblem( + target, + config.server.port, + config.server.strictPort, + ) + if (problem) throw new Error(`Refused: ${problem}`) + }, + } +} + +/** Throws unless the target's gateway answers its identity body exactly, within 3 s. */ +export async function checkGatewayIdentity(target: TrialTarget): Promise { + if (target.identity === undefined) return + let body = '' + try { + const res = await fetch(`${target.gateway}/__faunosteo_stack`, { + signal: AbortSignal.timeout(3000), + redirect: 'error', + }) + body = res.status === 200 ? await res.text() : '' + } catch { + body = '' + } + if (body !== target.identity) + throw new Error( + `${target.gateway} does not answer as the ${target.name} stack's gateway: refused`, + ) +} diff --git a/apps/app/vite/trial.config.ts b/apps/app/vite/trial.config.ts index 21ce92b9..82b834f4 100644 --- a/apps/app/vite/trial.config.ts +++ b/apps/app/vite/trial.config.ts @@ -1,22 +1,23 @@ import { fileURLToPath } from 'node:url' import { defineConfig, mergeConfig, type Plugin } from 'vite' import base from '../vite.config' +import { + checkGatewayIdentity, + targetPortGuard, + trialTarget, +} from './trial-targets' /** - * Dev server of `pnpm db:sandbox trial` (docs/development/V1-2-6_OWNER_TRIAL.md). + * Dev server of `pnpm db:sandbox trial` (docs/development/V1-2-6_OWNER_TRIAL.md) and of + * `pnpm db:trial app` (docs/development/SUPABASE.md §5.2). * The browser talks to this origin only: the three Supabase routes are - * forwarded to the trial gateway on loopback, so the app itself needs no CORS (the proxied + * forwarded to the stack's gateway on loopback, so the app itself needs no CORS (the proxied * routes keep the stack's own CORS headers). - * The server binds the one host that scripts/db-sandbox.sh validated (loopback or a private - * address of this machine) and refuses any other Host header. + * The server binds the one host the calling script validated (loopback or a private address of + * this machine) and refuses any other Host header. It serves exactly one of the two stacks of + * ./trial-targets.ts: gateway, app port, app URL and anon key issuer must all name the same one, + * and the db:trial gateway must answer its identity; anything else stops it before it listens. */ -const target = process.env.FAUNOSTEO_TRIAL_GATEWAY -const url = target ? new URL(target) : null -if (!url || url.protocol !== 'http:' || url.hostname !== '127.0.0.1') - throw new Error( - 'FAUNOSTEO_TRIAL_GATEWAY must be an http://127.0.0.1: URL', - ) - const host = process.env.FAUNOSTEO_TRIAL_HOST ?? '' const PRIVATE_IPV4 = /^(127\.0\.0\.1|10(\.\d{1,3}){3}|172\.(1[6-9]|2\d|3[01])(\.\d{1,3}){2}|192\.168(\.\d{1,3}){2})$/ @@ -24,10 +25,14 @@ if (!PRIVATE_IPV4.test(host)) throw new Error( 'FAUNOSTEO_TRIAL_HOST must be 127.0.0.1 or a private IPv4 address', ) +const target = trialTarget(process.env) const SUPABASE_ROUTES = ['/auth/v1', '/rest/v1', '/storage/v1'] const REPO = fileURLToPath(new URL('../../../', import.meta.url)) +// The CLI's --port and --strictPort are part of the resolved config: checked there. +const targetPortOnly = targetPortGuard(target) + /** * `allowedHosts` still lets every IP literal and localhost through (Vite 7): any HTTP request whose * Host is not the trial host is refused (403); the editor-launch route is closed (404). @@ -52,9 +57,10 @@ const trialHostOnly: Plugin = { }, } -export default defineConfig((env) => - mergeConfig(base(env), { - plugins: [trialHostOnly], +export default defineConfig(async (env) => { + await checkGatewayIdentity(target) + return mergeConfig(base(env), { + plugins: [trialHostOnly, targetPortOnly], // One validated host, never 0.0.0.0: the proxy carries the trial account's session. server: { host, @@ -65,10 +71,14 @@ export default defineConfig((env) => cors: false, ws: false, // The LAN sees the app's own sources only: never the repository's notes, seed or builds. - fs: { allow: ['apps/app', 'packages', 'node_modules'].map((dir) => REPO + dir) }, + fs: { + allow: ['apps/app', 'packages', 'node_modules'].map( + (dir) => REPO + dir, + ), + }, proxy: Object.fromEntries( - SUPABASE_ROUTES.map((route) => [route, { target }]), + SUPABASE_ROUTES.map((route) => [route, { target: target.gateway }]), ), }, - }), -) + }) +})