fix(backend): add CORS and disable CSRF in dev (#92)

* fix(backend): add CORS middleware and disable CSRF in dev

- Add CORS middleware for /api/auth/* and global routes
- Disable better-auth CSRF origin check when NODE_ENV != production

Co-authored-by: Ona <no-reply@ona.com>

* fix: gate permissive CORS to dev only

In production, only origins listed in CORS_ORIGINS env
var are allowed. In dev, any origin is reflected back.

Co-authored-by: Ona <no-reply@ona.com>

---------

Co-authored-by: Ona <no-reply@ona.com>
This commit is contained in:
2026-03-23 00:31:23 +00:00
committed by GitHub
parent 7909211c1b
commit 35c6371d48
2 changed files with 32 additions and 0 deletions

View File

@@ -16,6 +16,9 @@ export function createAuth(db: Database) {
provider: "pg",
schema,
}),
advanced: {
disableCSRFCheck: process.env.NODE_ENV !== "production",
},
emailAndPassword: {
enabled: true,
},

View File

@@ -1,4 +1,5 @@
import { Hono } from "hono"
import { cors } from "hono/cors"
import { registerAdminHttpHandlers } from "./admin/http.ts"
import { createRequireAdmin } from "./auth/admin-middleware.ts"
@@ -50,6 +51,34 @@ function main() {
const app = new Hono()
const isDev = process.env.NODE_ENV !== "production"
const allowedOrigins = process.env.CORS_ORIGINS?.split(",").map((o) => o.trim()) ?? []
function resolveOrigin(origin: string): string | undefined {
if (isDev) return origin
return allowedOrigins.includes(origin) ? origin : undefined
}
app.use(
"/api/auth/*",
cors({
origin: resolveOrigin,
allowHeaders: ["Content-Type", "Authorization"],
allowMethods: ["POST", "GET", "OPTIONS"],
exposeHeaders: ["Content-Length"],
maxAge: 600,
credentials: true,
}),
)
app.use(
"*",
cors({
origin: resolveOrigin,
credentials: true,
}),
)
app.get("/health", (c) => c.json({ status: "ok" }))
const authSessionMiddleware = createRequireSession(auth)