fix: auth handler + circular imports — Phase 1 verification (P1-009) (#73)

Co-authored-by: Jason Woltje <jason@diversecanvas.com>
Co-committed-by: Jason Woltje <jason@diversecanvas.com>
This commit was merged in pull request #73.
This commit is contained in:
2026-03-13 03:02:02 +00:00
committed by jason.woltje
parent c54b69f7ce
commit aa9ee75a2a
11 changed files with 51 additions and 24 deletions

View File

@@ -1,20 +1,46 @@
import type { IncomingMessage, ServerResponse } from 'node:http';
import { All, Controller, Inject, Req, Res } from '@nestjs/common';
import type { FastifyReply, FastifyRequest } from 'fastify';
import { toNodeHandler } from 'better-auth/node';
import type { Auth } from '@mosaic/auth';
import { AUTH } from './auth.module.js';
import type { NestFastifyApplication } from '@nestjs/platform-fastify';
import { AUTH } from './auth.tokens.js';
@Controller('api/auth')
export class AuthController {
private readonly handler: (req: IncomingMessage, res: ServerResponse) => Promise<void>;
export function mountAuthHandler(app: NestFastifyApplication): void {
const auth = app.get<Auth>(AUTH);
const nodeHandler = toNodeHandler(auth);
constructor(@Inject(AUTH) auth: Auth) {
this.handler = toNodeHandler(auth);
}
const fastify = app.getHttpAdapter().getInstance();
@All('*path')
async handleAuth(@Req() req: FastifyRequest, @Res() res: FastifyReply): Promise<void> {
await this.handler(req.raw, res.raw);
}
// Use Fastify's addHook to intercept auth requests at the raw HTTP level,
// before Fastify's body parser runs. This avoids conflicts with NestJS's
// custom content-type parser.
fastify.addHook(
'onRequest',
(
req: { raw: IncomingMessage; url: string },
reply: { raw: ServerResponse; hijack: () => void },
done: () => void,
) => {
if (!req.url.startsWith('/api/auth/')) {
done();
return;
}
reply.hijack();
nodeHandler(req.raw as IncomingMessage, reply.raw as ServerResponse)
.then(() => {
if (!reply.raw.writableEnded) {
reply.raw.end();
}
})
.catch((err: unknown) => {
if (!reply.raw.headersSent) {
reply.raw.writeHead(500, { 'Content-Type': 'application/json' });
}
if (!reply.raw.writableEnded) {
reply.raw.end(JSON.stringify({ error: 'Internal auth error' }));
}
console.error('[AUTH] Handler error:', err);
});
},
);
}

View File

@@ -8,7 +8,7 @@ import {
import { fromNodeHeaders } from 'better-auth/node';
import type { Auth } from '@mosaic/auth';
import type { FastifyRequest } from 'fastify';
import { AUTH } from './auth.module.js';
import { AUTH } from './auth.tokens.js';
@Injectable()
export class AuthGuard implements CanActivate {

View File

@@ -2,9 +2,7 @@ import { Global, Module } from '@nestjs/common';
import { createAuth, type Auth } from '@mosaic/auth';
import type { Db } from '@mosaic/db';
import { DB } from '../database/database.module.js';
import { AuthController } from './auth.controller.js';
export const AUTH = 'AUTH';
import { AUTH } from './auth.tokens.js';
@Global()
@Module({
@@ -20,7 +18,6 @@ export const AUTH = 'AUTH';
inject: [DB],
},
],
controllers: [AuthController],
exports: [AUTH],
})
export class AuthModule {}

View File

@@ -0,0 +1 @@
export const AUTH = 'AUTH';

View File

@@ -2,8 +2,7 @@ import { Global, Module } from '@nestjs/common';
import { createBrain, type Brain } from '@mosaic/brain';
import type { Db } from '@mosaic/db';
import { DB } from '../database/database.module.js';
export const BRAIN = 'BRAIN';
import { BRAIN } from './brain.tokens.js';
@Global()
@Module({

View File

@@ -0,0 +1 @@
export const BRAIN = 'BRAIN';

View File

@@ -13,7 +13,7 @@ import {
UseGuards,
} from '@nestjs/common';
import type { Brain } from '@mosaic/brain';
import { BRAIN } from '../brain/brain.module.js';
import { BRAIN } from '../brain/brain.tokens.js';
import { AuthGuard } from '../auth/auth.guard.js';
import { CurrentUser } from '../auth/current-user.decorator.js';
import type {

View File

@@ -4,11 +4,14 @@ import { NestFactory } from '@nestjs/core';
import { Logger } from '@nestjs/common';
import { FastifyAdapter, type NestFastifyApplication } from '@nestjs/platform-fastify';
import { AppModule } from './app.module.js';
import { mountAuthHandler } from './auth/auth.controller.js';
async function bootstrap(): Promise<void> {
const logger = new Logger('Bootstrap');
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter());
mountAuthHandler(app);
const port = process.env['GATEWAY_PORT'] ?? 4000;
await app.listen(port as number, '0.0.0.0');
logger.log(`Gateway listening on port ${port}`);

View File

@@ -13,7 +13,7 @@ import {
UseGuards,
} from '@nestjs/common';
import type { Brain } from '@mosaic/brain';
import { BRAIN } from '../brain/brain.module.js';
import { BRAIN } from '../brain/brain.tokens.js';
import { AuthGuard } from '../auth/auth.guard.js';
import type { CreateMissionDto, UpdateMissionDto } from './missions.dto.js';

View File

@@ -13,7 +13,7 @@ import {
UseGuards,
} from '@nestjs/common';
import type { Brain } from '@mosaic/brain';
import { BRAIN } from '../brain/brain.module.js';
import { BRAIN } from '../brain/brain.tokens.js';
import { AuthGuard } from '../auth/auth.guard.js';
import { CurrentUser } from '../auth/current-user.decorator.js';
import type { CreateProjectDto, UpdateProjectDto } from './projects.dto.js';

View File

@@ -14,7 +14,7 @@ import {
UseGuards,
} from '@nestjs/common';
import type { Brain } from '@mosaic/brain';
import { BRAIN } from '../brain/brain.module.js';
import { BRAIN } from '../brain/brain.tokens.js';
import { AuthGuard } from '../auth/auth.guard.js';
import type { CreateTaskDto, UpdateTaskDto } from './tasks.dto.js';