49 lines
2.0 KiB
TypeScript
49 lines
2.0 KiB
TypeScript
import { addHTTPMiddleware } from "#pikku";
|
|
import { authBearer, cors } from "@pikku/core/middleware";
|
|
import { betterAuthStatelessSession } from "@pikku/better-auth";
|
|
import { sessionCookieMiddleware } from "../middleware/session-cookie.js";
|
|
|
|
// sessionCookieMiddleware runs first so that booking-form clients
|
|
// (sh_session cookie) are resolved before better-auth is checked.
|
|
addHTTPMiddleware("*", [
|
|
cors({
|
|
origin: true,
|
|
credentials: true,
|
|
headers: ["Content-Type", "Authorization", "x-api-key", "X-Auth-Return-Redirect"],
|
|
}),
|
|
sessionCookieMiddleware,
|
|
// Stateless (cookie-cache) session so the CLI detects our own registration and
|
|
// does NOT also generate a bare betterAuthStatelessSession() (no mapSession),
|
|
// which would strip the session to { userId } and 403 every admin RPC.
|
|
betterAuthStatelessSession({
|
|
mapSession: (result: any) => {
|
|
// A logged-in user must always carry a role (Better Auth defaults it to
|
|
// 'client'). A missing role means the auth wiring/schema is stale — fail
|
|
// loudly instead of silently downgrading to 'client', which would show the
|
|
// real role in the header (DB-read) while every admin RPC 403s.
|
|
const role = result.user.role;
|
|
if (!role) {
|
|
throw new Error(
|
|
`Session for user ${result.user.id} has no role — auth wiring/schema is out of date`,
|
|
);
|
|
}
|
|
return {
|
|
userId: result.user.id,
|
|
role,
|
|
locale: result.user.locale ?? "de",
|
|
};
|
|
},
|
|
}),
|
|
// External consoles (sandbox/woven-build view) can't carry the session cookie,
|
|
// so they authenticate with `Authorization: Bearer <PIKKU_CONSOLE_TOKEN>`. The
|
|
// CLI normally emits this alongside its session middleware, but because we
|
|
// register our own global session middleware above it steps aside entirely —
|
|
// so we must add the console-token bridge here or console:* RPCs 403.
|
|
authBearer({
|
|
token: {
|
|
secretId: "PIKKU_CONSOLE_TOKEN",
|
|
userSession: { userId: "pikku-console-token" },
|
|
},
|
|
}),
|
|
]);
|