mirror of
https://github.com/Memo-2023/mana-monorepo.git
synced 2026-05-18 13:29:39 +02:00
Rewrite the central authentication service from NestJS to Hono + Bun.
Uses Better Auth's native fetch-based handler — no Express conversion.
Key architecture changes:
- Better Auth handler mounted directly on Hono (app.all('/api/auth/*'))
- No NestJS DI, modules, guards, decorators — plain TypeScript
- JWT validation via jose (same as extracted services)
- Email via nodemailer (simplified, German templates)
- ~1,400 LOC vs ~11,500 LOC in NestJS (88% reduction)
Service structure:
- auth/better-auth.config.ts — copied from mana-core-auth (framework-agnostic)
- auth/stores.ts — in-memory stores for email redirect URLs
- email/send.ts — nodemailer email functions
- middleware/ — JWT auth, service auth, error handler (shared pattern)
- db/schema/ — copied from mana-core-auth (Drizzle, framework-agnostic)
Port: 3001 (same as mana-core-auth — drop-in replacement)
Database: mana_auth (same DB, same schemas)
Better Auth plugins: Organization, JWT (EdDSA), OIDC Provider,
Two-Factor (TOTP), Magic Link
Note: This is the initial version. Guilds, API keys, Me (GDPR),
security (lockout/audit), and admin endpoints will be added
incrementally. The old mana-core-auth remains until fully replaced.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
57 lines
1.4 KiB
TypeScript
57 lines
1.4 KiB
TypeScript
/**
|
|
* JWT Authentication Middleware
|
|
*
|
|
* Validates Bearer tokens via JWKS from mana-core-auth.
|
|
* Uses jose library with EdDSA algorithm.
|
|
*/
|
|
|
|
import type { MiddlewareHandler } from 'hono';
|
|
import { createRemoteJWKSet, jwtVerify } from 'jose';
|
|
import { UnauthorizedError } from '../lib/errors';
|
|
|
|
let jwks: ReturnType<typeof createRemoteJWKSet> | null = null;
|
|
|
|
function getJwks(authUrl: string) {
|
|
if (!jwks) {
|
|
jwks = createRemoteJWKSet(new URL('/api/auth/jwks', authUrl));
|
|
}
|
|
return jwks;
|
|
}
|
|
|
|
export interface AuthUser {
|
|
userId: string;
|
|
email: string;
|
|
role: string;
|
|
}
|
|
|
|
/**
|
|
* Middleware that validates JWT tokens from Authorization: Bearer header.
|
|
* Sets c.set('user', { userId, email, role }) on success.
|
|
*/
|
|
export function jwtAuth(authUrl: string): MiddlewareHandler {
|
|
return async (c, next) => {
|
|
const authHeader = c.req.header('Authorization');
|
|
if (!authHeader?.startsWith('Bearer ')) {
|
|
throw new UnauthorizedError('Missing or invalid Authorization header');
|
|
}
|
|
|
|
const token = authHeader.slice(7);
|
|
try {
|
|
const { payload } = await jwtVerify(token, getJwks(authUrl), {
|
|
issuer: authUrl,
|
|
audience: 'manacore',
|
|
});
|
|
|
|
const user: AuthUser = {
|
|
userId: payload.sub || '',
|
|
email: (payload.email as string) || '',
|
|
role: (payload.role as string) || 'user',
|
|
};
|
|
|
|
c.set('user', user);
|
|
await next();
|
|
} catch {
|
|
throw new UnauthorizedError('Invalid or expired token');
|
|
}
|
|
};
|
|
}
|