fix(e2e): align browser harness with local stack

This commit is contained in:
jjbrunton committed 2026-08-30 21:00:12 +01:00
1 parent db5980c9bd
commit cf19d23d8a
20 files changed
+267 -85

No files matched your search

+11
View File
@@ -1,5 +1,6 @@
import type { ApiErrorResponse, MeResponse } from '@sauci/shared';
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { z } from 'zod';
import { bearerToken, type AuthIdentity, type AuthVerifier } from './auth.js';
import type { ApiRepository } from './db/repository.js';
@@ -36,6 +37,7 @@ type Variables = { identity: AuthIdentity };
export interface AppDependencies {
auth: AuthVerifier;
repository: ApiRepository;
corsAllowedOrigins?: string[];
coupleService?: CoupleService;
packsRepository?: PacksRepository;
answersRepository?: AnswersRepository;
@@ -61,6 +63,15 @@ function error(code: string, message: string): ApiErrorResponse {
export function createApp(deps: AppDependencies): Hono<{ Variables: Variables }> {
const app = new Hono<{ Variables: Variables }>();
const corsAllowedOrigins = new Set(deps.corsAllowedOrigins ?? ['https://sauci.app']);
// The public web redemption form calls the API from a distinct browser origin.
// API authentication remains bearer-token based, so this does not grant cross-origin access to protected data.
app.use('*', cors({
origin: (origin) => corsAllowedOrigins.has(origin) ? origin : null,
allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization'],
}));
app.use('*', async (c, next) => {
const startedAt = performance.now();
try {
+22
View File
@@ -2,10 +2,30 @@ import { z } from 'zod';
const optionalString = z.preprocess((value) => value === '' ? undefined : value, z.string().min(1).optional());
const optionalUuid = z.preprocess((value) => value === '' ? undefined : value, z.string().uuid().optional());
const corsOrigins = z.string().default('https://sauci.app').transform((value, ctx) => {
const origins = value.split(',').map((origin) => origin.trim()).filter(Boolean);
if (origins.length === 0) {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'CORS_ALLOWED_ORIGINS must contain at least one origin' });
return z.NEVER;
}
for (const origin of origins) {
try {
const parsed = new URL(origin);
if (parsed.origin !== origin || parsed.username || parsed.password || parsed.pathname !== '/') {
throw new Error('not an origin');
}
} catch {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: `Invalid CORS origin: ${origin}` });
return z.NEVER;
}
}
return origins;
});
const baseSchema = z.object({
NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
PORT: z.coerce.number().int().min(1).max(65535).default(3003),
CORS_ALLOWED_ORIGINS: corsOrigins,
DATABASE_URL: z.string().url(),
DATABASE_POOL_MAX: z.coerce.number().int().min(1).max(200).default(10),
DATABASE_POOL_IDLE_TIMEOUT_MS: z.coerce.number().int().min(0).max(3_600_000).default(30_000),
@@ -30,6 +50,7 @@ const baseSchema = z.object({
export interface AppConfig {
nodeEnv: 'development' | 'test' | 'production';
port: number;
corsAllowedOrigins: string[];
databaseUrl: string;
databasePool: { max: number; idleTimeoutMillis: number; connectionTimeoutMillis: number };
authIssuer: string;
@@ -84,6 +105,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): AppConfig {
return {
nodeEnv: parsed.NODE_ENV,
port: parsed.PORT,
corsAllowedOrigins: parsed.CORS_ALLOWED_ORIGINS,
databaseUrl: parsed.DATABASE_URL,
databasePool: {
max: parsed.DATABASE_POOL_MAX,
+1
View File
@@ -65,6 +65,7 @@ const adminRepository = new PostgresAdminRepository(pool, {
const app = createApp({
auth: authVerifier,
repository,
corsAllowedOrigins: config.corsAllowedOrigins,
coupleService: new CoupleService(coupleRepository),
packsRepository,
answersRepository,
+29
View File
@@ -81,6 +81,35 @@ describe('Sauci API', () => {
expect(repository.ready).toHaveBeenCalledOnce();
});
it('allows browser preflight requests only from configured web origins', async () => {
const app = createApp({
auth: verifier(),
repository: new MemoryRepository(),
corsAllowedOrigins: ['http://127.0.0.1:3010', 'https://sauci.app'],
});
const response = await app.request('/public/v1/redemptions', {
method: 'OPTIONS',
headers: {
origin: 'http://127.0.0.1:3010',
'access-control-request-method': 'POST',
'access-control-request-headers': 'content-type',
},
});
expect(response.status).toBe(204);
expect(response.headers.get('access-control-allow-origin')).toBe('http://127.0.0.1:3010');
expect(response.headers.get('access-control-allow-methods')).toContain('POST');
const rejected = await app.request('/public/v1/redemptions', {
method: 'OPTIONS',
headers: {
origin: 'https://unapproved.example',
'access-control-request-method': 'POST',
},
});
expect(rejected.headers.get('access-control-allow-origin')).toBeNull();
});
it('fails closed when the bearer token is missing or invalid', async () => {
const app = createApp({ auth: verifier(), repository: new MemoryRepository() });
expect((await app.request('/v1/me')).status).toBe(401);