Files
archy/packages/app/server/dev-auth.ts
T

37 lines
1.4 KiB
TypeScript
Raw Normal View History

/**
* Shared dev server authentication middleware.
* Validates Bearer token on all /api/* requests.
* Token is auto-generated in scripts/dev.sh and injected via VITE_DEV_API_TOKEN.
*/
import type { IncomingMessage, ServerResponse } from 'http'
const DEV_TOKEN = process.env.VITE_DEV_API_TOKEN ?? ''
/** Validate Authorization header. Returns true if authorized, false if rejected (response already sent). */
/** Validate Authorization header. Returns true if authorized, false if rejected (response already sent). */
export function validateDevAuth(req: IncomingMessage, res: ServerResponse): boolean {
if (!DEV_TOKEN) return true // No token configured, skip auth
const auth = req.headers.authorization
if (auth === `Bearer ${DEV_TOKEN}`) return true
res.writeHead(401, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: 'Unauthorized' }))
return false
}
const ALLOWED_ORIGIN = 'http://localhost:5173'
/** Set CORS headers with explicit localhost origin instead of wildcard. */
export function setCorsHeaders(res: ServerResponse): void {
res.setHeader('Access-Control-Allow-Origin', ALLOWED_ORIGIN)
}
/** Write CORS preflight response. */
export function handleCorsOptions(res: ServerResponse): void {
res.writeHead(204, {
'Access-Control-Allow-Origin': ALLOWED_ORIGIN,
'Access-Control-Allow-Methods': 'GET, POST, PUT, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
})
res.end()
}