refactor to adapters

This commit is contained in:
2025-12-15 18:34:20 +01:00
parent fc671482c8
commit c817d76092
145 changed files with 906 additions and 361 deletions

View File

@@ -1,63 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
const cookieStore = {
get: vi.fn(),
set: vi.fn(),
delete: vi.fn(),
};
vi.mock('next/headers', () => ({
cookies: () => cookieStore,
}));
import { InMemoryAuthService } from '../../../../apps/website/lib/auth/InMemoryAuthService';
describe('InMemoryAuthService', () => {
beforeEach(() => {
cookieStore.get.mockReset();
cookieStore.set.mockReset();
cookieStore.delete.mockReset();
});
it('startIracingAuthRedirect returns redirectUrl with returnTo and state without touching cookies', async () => {
const service = new InMemoryAuthService();
const { redirectUrl, state } = await service.startIracingAuthRedirect('some');
expect(typeof state).toBe('string');
expect(state.length).toBeGreaterThan(0);
const url = new URL(redirectUrl, 'http://localhost');
expect(url.pathname).toBe('/auth/iracing/callback');
expect(url.searchParams.get('returnTo')).toBe('some');
expect(url.searchParams.get('state')).toBe(state);
expect(url.searchParams.get('code')).toBeTruthy();
expect(cookieStore.get).not.toHaveBeenCalled();
expect(cookieStore.set).not.toHaveBeenCalled();
expect(cookieStore.delete).not.toHaveBeenCalled();
});
it('loginWithIracingCallback returns deterministic demo session', async () => {
const service = new InMemoryAuthService();
const session = await service.loginWithIracingCallback({
code: 'dummy-code',
state: 'any-state',
});
expect(session.user.id).toBe('demo-user');
expect(session.user.primaryDriverId).toBeDefined();
expect(session.user.primaryDriverId).not.toBe('');
});
it('logout clears the demo session cookie via adapter', async () => {
const service = new InMemoryAuthService();
await service.logout();
expect(cookieStore.get).not.toHaveBeenCalled();
expect(cookieStore.set).not.toHaveBeenCalled();
expect(cookieStore.delete).toHaveBeenCalledWith('gp_demo_session');
});
});

View File

@@ -1,17 +0,0 @@
import { describe, it, expect } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';
describe('IracingAuthPage imports', () => {
it('does not import cookies or getAuthService', () => {
const filePath = path.resolve(
__dirname,
'../../../../apps/website/app/auth/iracing/page.tsx',
);
const source = fs.readFileSync(filePath, 'utf-8');
expect(source.includes("from 'next/headers'")).toBe(false);
expect(source.includes('cookies(')).toBe(false);
expect(source.includes('getAuthService')).toBe(false);
});
});

View File

@@ -1,85 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
const cookieStore = {
get: vi.fn(),
set: vi.fn(),
delete: vi.fn(),
};
vi.mock('next/headers', () => {
return {
cookies: () => cookieStore,
};
});
import { GET as startGet } from '../../../../apps/website/app/auth/iracing/start/route';
import { GET as callbackGet } from '../../../../apps/website/app/auth/iracing/callback/route';
import { POST as logoutPost } from '../../../../apps/website/app/auth/logout/route';
describe('iRacing auth route handlers', () => {
beforeEach(() => {
cookieStore.get.mockReset();
cookieStore.set.mockReset();
cookieStore.delete.mockReset();
});
it('start route redirects to auth URL and sets state cookie', async () => {
const req = new Request('http://localhost/auth/iracing/start?returnTo=/dashboard');
const res = await startGet(req);
expect(res.status).toBe(307);
const location = res.headers.get('location') ?? '';
expect(location).toContain('/auth/iracing/callback');
expect(location).toContain('returnTo=%2Fdashboard');
expect(location).toMatch(/state=/);
expect(cookieStore.set).toHaveBeenCalled();
const call = cookieStore.set.mock.calls[0];
expect(call).toBeDefined();
const [name] = call as [string, string];
expect(name).toBe('gp_demo_auth_state');
});
it('callback route creates session cookie and redirects to returnTo', async () => {
cookieStore.get.mockImplementation((name: string) => {
if (name === 'gp_demo_auth_state') {
return { value: 'valid-state' };
}
return undefined;
});
const req = new Request(
'http://localhost/auth/iracing/callback?code=demo-code&state=valid-state&returnTo=/dashboard',
);
const res = await callbackGet(req);
expect(res.status).toBe(307);
const location = res.headers.get('location');
expect(location).toBe('http://localhost/dashboard');
expect(cookieStore.set).toHaveBeenCalled();
const call = cookieStore.set.mock.calls[0];
expect(call).toBeDefined();
const [sessionName, sessionValue] = call as [string, string];
expect(sessionName).toBe('gp_demo_session');
expect(typeof sessionValue).toBe('string');
expect(cookieStore.delete).toHaveBeenCalledWith('gp_demo_auth_state');
});
it('logout route deletes session cookie and redirects home using request origin', async () => {
const req = new Request('http://example.com/auth/logout', {
method: 'POST',
});
const res = await logoutPost(req);
expect(res.status).toBe(307);
const location = res.headers.get('location');
expect(location).toBe('http://example.com/');
expect(cookieStore.delete).toHaveBeenCalledWith('gp_demo_session');
});
});

View File

@@ -1,63 +0,0 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { getAppMode, AppMode } from '../../../apps/website/lib/mode';
const ORIGINAL_NODE_ENV = process.env.NODE_ENV;
describe('getAppMode', () => {
const originalEnv = process.env;
beforeEach(() => {
process.env = { ...originalEnv };
(process.env as any).NODE_ENV = 'production';
});
afterEach(() => {
process.env = originalEnv;
(process.env as any).NODE_ENV = ORIGINAL_NODE_ENV;
});
it('returns "pre-launch" when NEXT_PUBLIC_GRIDPILOT_MODE is undefined', () => {
delete process.env.NEXT_PUBLIC_GRIDPILOT_MODE;
const mode = getAppMode();
expect(mode).toBe<AppMode>('pre-launch');
});
it('returns "pre-launch" when NEXT_PUBLIC_GRIDPILOT_MODE is explicitly set to "pre-launch"', () => {
process.env.NEXT_PUBLIC_GRIDPILOT_MODE = 'pre-launch';
const mode = getAppMode();
expect(mode).toBe<AppMode>('pre-launch');
});
it('returns "alpha" when NEXT_PUBLIC_GRIDPILOT_MODE is set to "alpha"', () => {
process.env.NEXT_PUBLIC_GRIDPILOT_MODE = 'alpha';
const mode = getAppMode();
expect(mode).toBe<AppMode>('alpha');
});
it('falls back to "pre-launch" and logs when NEXT_PUBLIC_GRIDPILOT_MODE is invalid in production', () => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
process.env.NEXT_PUBLIC_GRIDPILOT_MODE = 'invalid-mode' as any;
const mode = getAppMode();
expect(mode).toBe<AppMode>('pre-launch');
expect(consoleError).toHaveBeenCalled();
consoleError.mockRestore();
});
it('throws in development when NEXT_PUBLIC_GRIDPILOT_MODE is invalid', () => {
(process.env as any).NODE_ENV = 'development';
process.env.NEXT_PUBLIC_GRIDPILOT_MODE = 'invalid-mode' as any;
expect(() => getAppMode()).toThrowError(/Invalid NEXT_PUBLIC_GRIDPILOT_MODE/);
});
});

View File

@@ -1,137 +0,0 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
type RateLimitResult = {
allowed: boolean;
remaining: number;
resetAt: number;
};
const mockCheckRateLimit = vi.fn(() => Promise.resolve({ allowed: true, remaining: 4, resetAt: 0 }));
const mockGetClientIp = vi.fn(() => '127.0.0.1');
vi.mock('../../../apps/website/lib/rate-limit', () => ({
checkRateLimit: mockCheckRateLimit,
getClientIp: mockGetClientIp,
}));
async function getPostHandler() {
const routeModule = (await import(
'../../../apps/website/app/api/signup/route'
)) as { POST: (request: Request) => Promise<Response> };
return routeModule.POST;
}
function createJsonRequest(body: unknown): Request {
return new Request('http://localhost/api/signup', {
method: 'POST',
headers: {
'content-type': 'application/json',
},
body: JSON.stringify(body),
});
}
describe('/api/signup POST', () => {
beforeEach(() => {
vi.resetModules();
mockCheckRateLimit.mockReset();
mockGetClientIp.mockReset();
mockGetClientIp.mockReturnValue('127.0.0.1');
mockCheckRateLimit.mockResolvedValue({
allowed: true,
remaining: 4,
resetAt: Date.now() + 60 * 60 * 1000,
});
});
it('accepts a valid email within rate limits and returns success payload', async () => {
const POST = await getPostHandler();
const response = await POST(
createJsonRequest({
email: 'user@example.com',
}),
);
expect(response.status).toBeGreaterThanOrEqual(200);
expect(response.status).toBeLessThan(300);
const data = (await response.json()) as { message: unknown; ok: unknown };
expect(data).toHaveProperty('message');
expect(typeof data.message).toBe('string');
expect(data).toHaveProperty('ok', true);
});
it('rejects an invalid email with 400 and error message', async () => {
const POST = await getPostHandler();
const response = await POST(
createJsonRequest({
email: 'not-an-email',
}),
);
expect(response.status).toBe(400);
const data = (await response.json()) as { error: unknown };
expect(typeof data.error).toBe('string');
expect(typeof data.error === 'string' && data.error.toLowerCase()).toContain('email');
});
it('rejects disposable email domains with 400 and error message', async () => {
const POST = await getPostHandler();
const response = await POST(
createJsonRequest({
email: 'foo@mailinator.com',
}),
);
expect(response.status).toBe(400);
const data = (await response.json()) as { error: unknown };
expect(typeof data.error).toBe('string');
});
it('returns 409 and friendly message when email is already subscribed', async () => {
const POST = await getPostHandler();
const email = 'duplicate@example.com';
const first = await POST(createJsonRequest({ email }));
expect(first.status).toBeGreaterThanOrEqual(200);
expect(first.status).toBeLessThan(300);
const second = await POST(createJsonRequest({ email }));
expect(second.status).toBe(409);
const data = (await second.json()) as { error: unknown };
expect(typeof data.error).toBe('string');
expect(typeof data.error === 'string' && data.error.toLowerCase()).toContain('already');
});
it('returns 429 with retryAfter when rate limit is exceeded', async () => {
mockCheckRateLimit.mockResolvedValueOnce({
allowed: false,
remaining: 0,
resetAt: Date.now() + 30_000,
});
const POST = await getPostHandler();
const response = await POST(
createJsonRequest({
email: 'limited@example.com',
}),
);
expect(response.status).toBe(429);
const data = (await response.json()) as { error: unknown; retryAfter?: unknown };
expect(typeof data.error).toBe('string');
expect(data).toHaveProperty('retryAfter');
});
});

View File

@@ -1,32 +0,0 @@
import { describe, it, expect } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';
const alphaDir = path.resolve(__dirname, '../../../../apps/website/components/alpha');
const metaAllowlist = new Set([
'FeatureLimitationTooltip.tsx',
'CompanionInstructions.tsx',
'CompanionStatus.tsx',
'AlphaBanner.tsx',
'AlphaFooter.tsx',
'AlphaNav.tsx',
// Temporary passthrough wrapper that re-exports the real schedule form
'ScheduleRaceForm.tsx',
]);
describe('Alpha components structure', () => {
it('contains only alpha chrome and meta components', () => {
const entries = fs.readdirSync(alphaDir);
const tsxFiles = entries.filter((file) => file.endsWith('.tsx'));
const violations = tsxFiles.filter((file) => {
if (metaAllowlist.has(file)) {
return false;
}
return !file.startsWith('Alpha');
});
expect(violations).toEqual([]);
});
});

View File

@@ -1,81 +0,0 @@
import { describe, it, expect } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';
const websiteRoot = path.resolve(__dirname, '../../../../apps/website');
const forbiddenImportPrefixes = [
"@/lib/demo-data",
"@/lib/inmemory",
"@/lib/social",
"@/lib/email-validation",
"@/lib/membership-data",
"@/lib/registration-data",
"@/lib/team-data",
];
function collectTsFiles(dir: string): string[] {
const entries = fs.readdirSync(dir, { withFileTypes: true });
const files: string[] = [];
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
// Skip Next.js build output if present
if (entry.name === '.next') continue;
files.push(...collectTsFiles(fullPath));
} else if (entry.isFile()) {
if (
entry.name.endsWith('.ts') ||
entry.name.endsWith('.tsx')
) {
files.push(fullPath);
}
}
}
return files;
}
describe('Website import boundaries', () => {
it('does not import forbidden website lib modules directly', () => {
const files = collectTsFiles(websiteRoot);
const violations: { file: string; line: number; content: string }[] = [];
for (const file of files) {
const content = fs.readFileSync(file, 'utf8');
const lines = content.split(/\r?\n/);
lines.forEach((line, index) => {
const trimmed = line.trim();
if (!trimmed.startsWith('import')) return;
for (const prefix of forbiddenImportPrefixes) {
if (trimmed.includes(`"${prefix}`) || trimmed.includes(`'${prefix}`)) {
violations.push({
file,
line: index + 1,
content: line,
});
}
}
});
}
if (violations.length > 0) {
const message =
'Found forbidden imports in apps/website:\n' +
violations
.map(
(v) =>
`- ${v.file}:${v.line} :: ${v.content.trim()}`,
)
.join('\n');
// Fail with detailed message so we can iterate while RED
expect(message).toBe(''); // Intentionally impossible when violations exist
} else {
expect(violations).toEqual([]);
}
});
});