Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
183 changes: 93 additions & 90 deletions apps/backend/openapi.json

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion apps/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,9 @@
"^better-auth$": "<rootDir>/../test/stubs/better-auth.ts",
"^better-auth/(.*)$": "<rootDir>/../test/stubs/better-auth.ts",
"^uuid$": "<rootDir>/../test/stubs/uuid.ts"
}
},
"setupFiles": [
"<rootDir>/../test/jest.setup.ts"
]
}
}
16 changes: 11 additions & 5 deletions apps/backend/src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { Module } from '@nestjs/common';
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { validateEnv } from './common/config/env.validation';
import { FamilyVisibilityCacheMiddleware } from './common/helpers/family-visibility.middleware';
import { BullModule } from '@nestjs/bullmq';
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler';
import { APP_FILTER, APP_GUARD } from '@nestjs/core';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { DomainExceptionFilter } from './common/filters/domain-exception.filter';
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';
import { PrismaModule } from './common/prisma/prisma.module';
import { AuthCoreModule } from './feature/auth/core/auth-core.module';
import { AuthRestModule } from './feature/auth/rest/auth-rest.module';
Expand Down Expand Up @@ -35,7 +37,7 @@ import { AuthGuard } from './feature/auth/rest/guards/auth.guard';

@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
ConfigModule.forRoot({ isGlobal: true, validate: validateEnv }),
ThrottlerModule.forRoot({
throttlers: [{ name: 'default', ttl: 60_000, limit: 120 }],
}),
Expand Down Expand Up @@ -79,7 +81,7 @@ import { AuthGuard } from './feature/auth/rest/guards/auth.guard';
AppService,
{
provide: APP_FILTER,
useClass: DomainExceptionFilter,
useClass: AllExceptionsFilter,
},
{
provide: APP_GUARD,
Expand All @@ -95,4 +97,8 @@ import { AuthGuard } from './feature/auth/rest/guards/auth.guard';
},
],
})
export class AppModule {}
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer): void {
consumer.apply(FamilyVisibilityCacheMiddleware).forRoutes('*path');
}
}
85 changes: 85 additions & 0 deletions apps/backend/src/common/config/env.validation.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { readdirSync, readFileSync, statSync } from 'fs';
import { join } from 'path';
import { validateEnv } from './env.validation';

const SRC = join(__dirname, '../..');

const REQUIRED: Record<string, string> = {
CORS_ORIGIN: 'http://localhost:3000',
DATABASE_URL: 'postgresql://admin:admin@localhost:5432/db',
BETTER_AUTH_SECRET: 'a-test-secret-that-is-at-least-32-characters',
BETTER_AUTH_URL: 'http://localhost:3001',
};

function sourceFiles(dir: string): string[] {
return readdirSync(dir).flatMap((entry) => {
const full = join(dir, entry);
if (statSync(full).isDirectory()) {
return sourceFiles(full);
}
return full.endsWith('.ts') && !full.endsWith('.spec.ts') ? [full] : [];
});
}

describe('validateEnv', () => {
it('accepts a complete environment', () => {
expect(() => validateEnv(REQUIRED)).not.toThrow();
});

it('rejects a missing required variable, naming it', () => {
const { DATABASE_URL: _omitted, ...incomplete } = REQUIRED;

expect(() => validateEnv(incomplete)).toThrow(/DATABASE_URL/);
});

it('rejects a BETTER_AUTH_SECRET shorter than 32 characters', () => {
expect(() =>
validateEnv({ ...REQUIRED, BETTER_AUTH_SECRET: 'too-short' }),
).toThrow(/BETTER_AUTH_SECRET/);
});

it('transforms PORT into a number', () => {
expect(validateEnv({ ...REQUIRED, PORT: '4000' }).PORT).toBe(4000);
});

it('rejects a REPORTING_TIMEZONE that is not an IANA zone', () => {
expect(() =>
validateEnv({ ...REQUIRED, REPORTING_TIMEZONE: 'Mars/Olympus' }),
).toThrow(/REPORTING_TIMEZONE/);
});

describe('RECEIPT_NORMALIZE_NAMES', () => {
it('is part of the schema, matching .env.example', () => {
expect(readFileSync(join(SRC, '../.env.example'), 'utf8')).toContain(
'RECEIPT_NORMALIZE_NAMES',
);
expect(validateEnv(REQUIRED).RECEIPT_NORMALIZE_NAMES).toBe('false');
});

it('passes an explicit value through', () => {
expect(
validateEnv({ ...REQUIRED, RECEIPT_NORMALIZE_NAMES: 'true' })
.RECEIPT_NORMALIZE_NAMES,
).toBe('true');
});
});
});

describe('direct process.env access', () => {
it('is confined to the env validation module', () => {
const offenders = sourceFiles(SRC)
.filter((file) => readFileSync(file, 'utf8').includes('process.env'))
.map((file) => file.slice(SRC.length + 1));

expect(offenders).toEqual(['common/config/env.validation.ts']);
});
});

describe('ConfigModule wiring', () => {
it('hands the zod schema to ConfigModule.forRoot', () => {
const appModule = readFileSync(join(SRC, 'app.module.ts'), 'utf8');

expect(appModule).toContain('validate: validateEnv');
expect(appModule).toContain('isGlobal: true');
});
});
25 changes: 21 additions & 4 deletions apps/backend/src/common/config/env.validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ function isSupportedTimeZone(timeZone: string): boolean {
}
}

const envSchema = z.object({
export const envSchema = z.object({
// Server
NODE_ENV: z.string().optional().default('development'),
PORT: z
.string()
.default('3001')
Expand Down Expand Up @@ -82,12 +83,17 @@ const envSchema = z.object({
COPILOT_TIMEOUT: z.string().optional(),
COPILOT_API_ENDPOINT: z.string().optional(),
COPILOT_ENABLED: z.string().optional(),

// Receipt parsing
RECEIPT_NORMALIZE_NAMES: z.string().optional().default('false'),
});

type EnvConfig = z.infer<typeof envSchema>;
export type EnvConfig = z.infer<typeof envSchema>;

export function validateEnv(): EnvConfig {
const result = envSchema.safeParse(process.env);
export function validateEnv(
source: Record<string, unknown> = process.env,
): EnvConfig {
const result = envSchema.safeParse(source);

if (!result.success) {
const errors = result.error.issues
Expand All @@ -100,3 +106,14 @@ export function validateEnv(): EnvConfig {

return result.data;
}

let cachedEnv: EnvConfig | null = null;

export function appEnv(): EnvConfig {
cachedEnv ??= validateEnv();
return cachedEnv;
}

export function resetAppEnv(): void {
cachedEnv = null;
}
114 changes: 114 additions & 0 deletions apps/backend/src/common/config/global-prefix.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { Server } from 'http';
import { Controller, Get, INestApplication, Post } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import request from 'supertest';
import { AuthController } from '~feature/auth/rest/controllers/auth.controller';
import { applyGlobalPrefix } from './global-prefix';

@Controller('expenses')
class BusinessController {
@Get()
list() {
return { data: [] };
}
}

@Controller('auth')
class AuthShapedController {
@Post('login')
login() {
return { via: 'nest' };
}

@Post('register')
register() {
return { via: 'nest' };
}

@Post('logout')
logout() {
return { via: 'nest' };
}

@Get('me')
me() {
return { via: 'nest' };
}

@Get('get-session')
getSession() {
return { via: 'nest' };
}
}

describe('global api prefix', () => {
let app: INestApplication;
let server: Server;

beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
controllers: [BusinessController, AuthShapedController],
}).compile();

app = moduleRef.createNestApplication();
applyGlobalPrefix(app);
await app.init();
server = app.getHttpServer() as Server;
});

afterAll(async () => {
await app.close();
});

it('serves business routes under /api', async () => {
await request(server).get('/api/expenses').expect(200);
await request(server).get('/expenses').expect(404);
});

describe('better-auth path space', () => {
it('leaves /api/auth/get-session unclaimed by nest', async () => {
await request(server).get('/api/auth/get-session').expect(404);
});

it.each([
['/api/auth/login'],
['/api/auth/register'],
['/api/auth/logout'],
['/api/auth/callback/google'],
['/api/auth/sign-in/email'],
])('leaves %s unclaimed by nest', async (path) => {
const post = await request(server).post(path);
const get = await request(server).get(path);

expect(post.status).toBe(404);
expect(get.status).toBe(404);
});
});

describe('the nest auth controller', () => {
it.each([['/auth/login'], ['/auth/register'], ['/auth/logout']])(
'keeps %s unprefixed',
async (path) => {
const response = await request(server).post(path);

expect(response.status).toBe(201);
expect(response.body).toEqual({ via: 'nest' });
},
);

it('keeps GET /auth/me unprefixed', async () => {
await request(server).get('/auth/me').expect(200, { via: 'nest' });
});
});

it('excludes every route the real AuthController declares', () => {
const declared = Object.getOwnPropertyNames(
AuthController.prototype,
).filter((name) => name !== 'constructor');
const covered = Object.getOwnPropertyNames(
AuthShapedController.prototype,
).filter((name) => name !== 'constructor');

expect(covered).toEqual(expect.arrayContaining(declared));
});
});
15 changes: 15 additions & 0 deletions apps/backend/src/common/config/global-prefix.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { INestApplication, RequestMethod } from '@nestjs/common';
import { RouteInfo } from '@nestjs/common/interfaces';

export const API_GLOBAL_PREFIX = 'api';

export const GLOBAL_PREFIX_EXCLUDED_ROUTES: RouteInfo[] = [
{ path: 'auth', method: RequestMethod.ALL },
{ path: 'auth/{*path}', method: RequestMethod.ALL },
];

export function applyGlobalPrefix(app: INestApplication): void {
app.setGlobalPrefix(API_GLOBAL_PREFIX, {
exclude: GLOBAL_PREFIX_EXCLUDED_ROUTES,
});
}
4 changes: 2 additions & 2 deletions apps/backend/src/common/config/reporting-timezone.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const DEFAULT_REPORTING_TIMEZONE = 'Europe/Belgrade';
import { appEnv } from './env.validation';

export function reportingTimeZone(): string {
return process.env.REPORTING_TIMEZONE || DEFAULT_REPORTING_TIMEZONE;
return appEnv().REPORTING_TIMEZONE;
}
43 changes: 43 additions & 0 deletions apps/backend/src/common/dto/to-boolean.transform.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { plainToInstance } from 'class-transformer';
import { ToBoolean } from './to-boolean.transform';

class QueryWithPending {
@ToBoolean()
pending?: boolean;
}

const parse = (pending: unknown) =>
plainToInstance(QueryWithPending, { pending }).pending;

describe('ToBoolean', () => {
it('reads the query string "false" as false, not true', () => {
expect(parse('false')).toBe(false);
});

it.each(['true', '1', 'yes', 'on', 'TRUE', ' True '])(
'reads %p as true',
(value) => {
expect(parse(value)).toBe(true);
},
);

it.each(['false', '0', 'no', 'off', 'FALSE', ' False '])(
'reads %p as false',
(value) => {
expect(parse(value)).toBe(false);
},
);

it('leaves real booleans alone', () => {
expect(parse(true)).toBe(true);
expect(parse(false)).toBe(false);
});

it('leaves an absent value absent', () => {
expect(parse(undefined)).toBeUndefined();
});

it('passes an unrecognised value through so IsBoolean can reject it', () => {
expect(parse('maybe')).toBe('maybe');
});
});
27 changes: 27 additions & 0 deletions apps/backend/src/common/dto/to-boolean.transform.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Transform } from 'class-transformer';

const TRUE_VALUES = new Set(['true', '1', 'yes', 'on']);
const FALSE_VALUES = new Set(['false', '0', 'no', 'off', '']);

export function toBooleanValue(value: unknown): unknown {
if (typeof value === 'boolean') {
return value;
}
if (typeof value === 'number') {
return value !== 0;
}
if (typeof value === 'string') {
const normalized = value.trim().toLowerCase();
if (TRUE_VALUES.has(normalized)) {
return true;
}
if (FALSE_VALUES.has(normalized)) {
return false;
}
}
return value;
}

export function ToBoolean(): PropertyDecorator {
return Transform(({ value }) => toBooleanValue(value), { toClassOnly: true });
}
Loading