2026-03-25 09:25:59 +08:00
|
|
|
import { createHash, randomBytes, randomUUID, scrypt, timingSafeEqual } from "node:crypto";
|
2026-03-22 02:55:10 +08:00
|
|
|
import { promisify } from "node:util";
|
2026-06-13 10:15:23 +08:00
|
|
|
import { and, eq, ne, sql } from "drizzle-orm";
|
2026-03-25 09:25:59 +08:00
|
|
|
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
2026-04-23 20:26:58 +08:00
|
|
|
import { z } from "zod";
|
2026-03-22 02:55:10 +08:00
|
|
|
import { env } from "../config.js";
|
2026-03-25 09:25:59 +08:00
|
|
|
import { db, schema } from "../db/index.js";
|
2026-06-07 21:54:27 +08:00
|
|
|
import { auditLog, sanitizeAuditInput } from "../lib/audit.js";
|
2026-04-22 18:10:04 +08:00
|
|
|
import { getPermissions, requirePermission } from "../permissions.js";
|
2026-03-22 02:55:10 +08:00
|
|
|
|
|
|
|
|
const scryptAsync = promisify(scrypt);
|
|
|
|
|
|
2026-03-22 19:28:57 +08:00
|
|
|
// ── Types ─────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
export interface AuthUser {
|
|
|
|
|
id: string;
|
|
|
|
|
username: string;
|
2026-04-22 18:10:04 +08:00
|
|
|
role: string;
|
|
|
|
|
apiKeyPermissions?: string[];
|
2026-03-22 19:28:57 +08:00
|
|
|
}
|
|
|
|
|
|
2026-04-04 17:44:51 +08:00
|
|
|
const MAX_USERS = env.MAX_USERS;
|
2026-03-25 09:25:59 +08:00
|
|
|
|
2026-03-22 02:55:10 +08:00
|
|
|
// ── Password hashing ──────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
const SALT_LENGTH = 32;
|
|
|
|
|
const KEY_LENGTH = 64;
|
|
|
|
|
|
2026-03-22 19:28:57 +08:00
|
|
|
export async function hashPassword(password: string): Promise<string> {
|
2026-03-22 02:55:10 +08:00
|
|
|
const salt = randomBytes(SALT_LENGTH).toString("hex");
|
|
|
|
|
const derived = (await scryptAsync(password, salt, KEY_LENGTH)) as Buffer;
|
|
|
|
|
return `${salt}:${derived.toString("hex")}`;
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-25 09:25:59 +08:00
|
|
|
export async function verifyPassword(password: string, stored: string): Promise<boolean> {
|
2026-03-22 02:55:10 +08:00
|
|
|
const [salt, hash] = stored.split(":");
|
|
|
|
|
if (!salt || !hash) return false;
|
|
|
|
|
const derived = (await scryptAsync(password, salt, KEY_LENGTH)) as Buffer;
|
|
|
|
|
const storedBuf = Buffer.from(hash, "hex");
|
|
|
|
|
if (derived.length !== storedBuf.length) return false;
|
|
|
|
|
return timingSafeEqual(derived, storedBuf);
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-24 21:38:06 +08:00
|
|
|
/**
|
|
|
|
|
* Compute a fast lookup prefix for an API key.
|
|
|
|
|
* Uses SHA-256 (not scrypt) so lookups are O(1) instead of O(n).
|
|
|
|
|
*/
|
|
|
|
|
export function computeKeyPrefix(rawKey: string): string {
|
|
|
|
|
return createHash("sha256").update(rawKey).digest("hex").slice(0, 16);
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-25 09:25:59 +08:00
|
|
|
const PASSWORD_RULES =
|
|
|
|
|
"Password must be at least 8 characters with uppercase, lowercase, and a number";
|
2026-03-24 21:38:06 +08:00
|
|
|
|
|
|
|
|
function validatePasswordStrength(password: string): string | null {
|
|
|
|
|
if (password.length < 8) return PASSWORD_RULES;
|
|
|
|
|
if (!/[A-Z]/.test(password)) return PASSWORD_RULES;
|
|
|
|
|
if (!/[a-z]/.test(password)) return PASSWORD_RULES;
|
|
|
|
|
if (!/[0-9]/.test(password)) return PASSWORD_RULES;
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function validateUsername(username: string): string | null {
|
|
|
|
|
if (username.length < 3 || username.length > 50) {
|
|
|
|
|
return "Username must be between 3 and 50 characters";
|
|
|
|
|
}
|
2026-03-25 09:25:59 +08:00
|
|
|
if (!/^[a-zA-Z0-9_.-]+$/.test(username)) {
|
2026-03-24 21:38:06 +08:00
|
|
|
return "Username can only contain letters, numbers, dots, hyphens, and underscores";
|
|
|
|
|
}
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-23 20:26:58 +08:00
|
|
|
// ── Zod schemas for auth request bodies ──────────────────────────
|
|
|
|
|
|
2026-05-13 21:33:50 +08:00
|
|
|
export const loginSchema = z.object({
|
|
|
|
|
username: z.string().min(1, "Username is required").max(255, "Username too long"),
|
|
|
|
|
password: z.string().min(1, "Password is required").max(1024, "Password too long"),
|
2026-04-23 20:26:58 +08:00
|
|
|
});
|
|
|
|
|
|
2026-05-13 21:33:50 +08:00
|
|
|
export const changePasswordSchema = z.object({
|
|
|
|
|
currentPassword: z.string().min(1, "Current password is required").max(1024, "Password too long"),
|
|
|
|
|
newPassword: z.string().min(1, "New password is required").max(1024, "Password too long"),
|
2026-04-23 20:26:58 +08:00
|
|
|
});
|
|
|
|
|
|
2026-05-13 21:33:50 +08:00
|
|
|
export const registerSchema = z.object({
|
|
|
|
|
username: z.string().min(1, "Username is required").max(255, "Username too long"),
|
|
|
|
|
password: z.string().min(1, "Password is required").max(1024, "Password too long"),
|
2026-04-23 20:26:58 +08:00
|
|
|
role: z.string().optional(),
|
|
|
|
|
team: z.string().optional(),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const updateUserSchema = z.object({
|
|
|
|
|
role: z.string().optional(),
|
|
|
|
|
team: z.string().optional(),
|
|
|
|
|
});
|
|
|
|
|
|
2026-05-13 21:33:50 +08:00
|
|
|
export const resetPasswordSchema = z.object({
|
|
|
|
|
newPassword: z.string().min(1, "New password is required").max(1024, "Password too long"),
|
2026-04-23 20:26:58 +08:00
|
|
|
});
|
|
|
|
|
|
2026-03-22 19:28:57 +08:00
|
|
|
// ── Request helpers ───────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
/** Extract the authenticated user attached by authMiddleware. */
|
|
|
|
|
export function getAuthUser(request: FastifyRequest): AuthUser | null {
|
|
|
|
|
return (request as FastifyRequest & { user?: AuthUser }).user ?? null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Require an authenticated user, sending 401 if missing. */
|
|
|
|
|
export function requireAuth(request: FastifyRequest, reply: FastifyReply): AuthUser | null {
|
|
|
|
|
const user = getAuthUser(request);
|
|
|
|
|
if (!user) {
|
|
|
|
|
reply.status(401).send({ error: "Authentication required", code: "AUTH_REQUIRED" });
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
return user;
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-10 21:25:03 +08:00
|
|
|
/** Require an admin user, sending 403 if not admin. */
|
|
|
|
|
export function requireAdmin(request: FastifyRequest, reply: FastifyReply): AuthUser | null {
|
|
|
|
|
const user = requireAuth(request, reply);
|
|
|
|
|
if (!user) return null;
|
|
|
|
|
if (user.role !== "admin") {
|
|
|
|
|
reply.status(403).send({ error: "Admin access required", code: "FORBIDDEN" });
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
return user;
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-22 02:55:10 +08:00
|
|
|
// ── Session helpers ────────────────────────────────────────────────
|
|
|
|
|
|
2026-04-20 21:50:17 +08:00
|
|
|
const SESSION_DURATION_MS = env.SESSION_DURATION_HOURS * 60 * 60 * 1000;
|
2026-03-22 02:55:10 +08:00
|
|
|
|
2026-05-13 18:52:39 +08:00
|
|
|
export function createSessionToken(): string {
|
2026-03-22 02:55:10 +08:00
|
|
|
return randomUUID();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ── Default admin creation ─────────────────────────────────────────
|
|
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
export async function ensureAnonymousUser(): Promise<void> {
|
|
|
|
|
const [existing] = await db.select().from(schema.users).where(eq(schema.users.id, "anonymous"));
|
2026-05-16 12:36:06 +08:00
|
|
|
if (existing) return;
|
|
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
await db
|
|
|
|
|
.insert(schema.users)
|
2026-05-16 12:36:06 +08:00
|
|
|
.values({
|
|
|
|
|
id: "anonymous",
|
|
|
|
|
username: "anonymous",
|
|
|
|
|
role: "admin",
|
|
|
|
|
mustChangePassword: false,
|
|
|
|
|
authProvider: "local",
|
|
|
|
|
})
|
2026-06-13 10:15:23 +08:00
|
|
|
.onConflictDoNothing();
|
2026-05-16 12:36:06 +08:00
|
|
|
}
|
|
|
|
|
|
2026-03-22 02:55:10 +08:00
|
|
|
export async function ensureDefaultAdmin(): Promise<void> {
|
2026-06-13 10:15:23 +08:00
|
|
|
const existingUsers = await db.select().from(schema.users);
|
2026-03-22 02:55:10 +08:00
|
|
|
if (existingUsers.length > 0) return;
|
|
|
|
|
|
|
|
|
|
const id = randomUUID();
|
|
|
|
|
const passwordHash = await hashPassword(env.DEFAULT_PASSWORD);
|
|
|
|
|
|
2026-03-28 11:19:09 +08:00
|
|
|
const mustChange = !env.SKIP_MUST_CHANGE_PASSWORD;
|
2026-06-13 10:15:23 +08:00
|
|
|
const result = await db
|
2026-03-26 01:20:09 +08:00
|
|
|
.insert(schema.users)
|
2026-03-22 02:55:10 +08:00
|
|
|
.values({
|
|
|
|
|
id,
|
|
|
|
|
username: env.DEFAULT_USERNAME,
|
|
|
|
|
passwordHash,
|
|
|
|
|
role: "admin",
|
2026-03-28 11:19:09 +08:00
|
|
|
mustChangePassword: mustChange,
|
2026-03-22 02:55:10 +08:00
|
|
|
})
|
2026-06-13 10:15:23 +08:00
|
|
|
.onConflictDoNothing();
|
2026-03-22 02:55:10 +08:00
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
if (result.rowCount && result.rowCount > 0) {
|
2026-03-26 01:20:09 +08:00
|
|
|
console.log(
|
2026-03-28 11:19:09 +08:00
|
|
|
mustChange
|
2026-06-13 10:15:23 +08:00
|
|
|
? `Default admin user '${env.DEFAULT_USERNAME}' created - password change required on first login`
|
2026-03-28 11:19:09 +08:00
|
|
|
: `Default admin user '${env.DEFAULT_USERNAME}' created (password change skipped via env)`,
|
2026-03-26 01:20:09 +08:00
|
|
|
);
|
|
|
|
|
}
|
2026-03-25 09:25:59 +08:00
|
|
|
}
|
|
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
/**
|
|
|
|
|
* Seed the three built-in roles (admin, editor, user) that the legacy SQLite
|
|
|
|
|
* migration 0007_custom_roles.sql used to insert. The Postgres baseline is
|
|
|
|
|
* DDL-only, so these must be created at boot time instead.
|
|
|
|
|
*
|
|
|
|
|
* Uses onConflictDoNothing so the function is safe to call when:
|
|
|
|
|
* - Roles already exist from a previous boot
|
|
|
|
|
* - Roles were imported by the 1.x SQLite-to-Postgres data migrator
|
|
|
|
|
*/
|
|
|
|
|
// Must match ROLE_PERMISSIONS in permissions.ts (the 1.x post-0010 state).
|
|
|
|
|
export async function ensureBuiltinRoles(): Promise<void> {
|
|
|
|
|
const builtinRoles = [
|
|
|
|
|
{
|
|
|
|
|
id: "builtin-admin",
|
|
|
|
|
name: "admin",
|
|
|
|
|
description: "Full administrative access",
|
|
|
|
|
permissions: [
|
|
|
|
|
"tools:use",
|
|
|
|
|
"files:own",
|
|
|
|
|
"files:all",
|
|
|
|
|
"apikeys:own",
|
|
|
|
|
"apikeys:all",
|
|
|
|
|
"pipelines:own",
|
|
|
|
|
"pipelines:all",
|
|
|
|
|
"settings:read",
|
|
|
|
|
"settings:write",
|
|
|
|
|
"users:manage",
|
|
|
|
|
"teams:manage",
|
|
|
|
|
"features:manage",
|
|
|
|
|
"system:health",
|
|
|
|
|
"audit:read",
|
|
|
|
|
],
|
|
|
|
|
isBuiltin: true,
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
id: "builtin-editor",
|
|
|
|
|
name: "editor",
|
|
|
|
|
description: "Can see all files and pipelines",
|
|
|
|
|
permissions: [
|
|
|
|
|
"tools:use",
|
|
|
|
|
"files:own",
|
|
|
|
|
"files:all",
|
|
|
|
|
"apikeys:own",
|
|
|
|
|
"pipelines:own",
|
|
|
|
|
"pipelines:all",
|
|
|
|
|
"settings:read",
|
|
|
|
|
],
|
|
|
|
|
isBuiltin: true,
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
id: "builtin-user",
|
|
|
|
|
name: "user",
|
|
|
|
|
description: "Basic tool access",
|
|
|
|
|
permissions: ["tools:use", "files:own", "apikeys:own", "pipelines:own", "settings:read"],
|
|
|
|
|
isBuiltin: true,
|
|
|
|
|
},
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
for (const role of builtinRoles) {
|
|
|
|
|
await db.insert(schema.roles).values(role).onConflictDoNothing();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-25 09:25:59 +08:00
|
|
|
// ── Login attempt limit ──────────────────────────────────────────
|
|
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
async function getLoginAttemptLimit(): Promise<number> {
|
|
|
|
|
const [row] = await db
|
2026-03-25 09:25:59 +08:00
|
|
|
.select()
|
|
|
|
|
.from(schema.settings)
|
2026-06-13 10:15:23 +08:00
|
|
|
.where(eq(schema.settings.key, "loginAttemptLimit"));
|
2026-03-25 09:25:59 +08:00
|
|
|
if (row) {
|
|
|
|
|
const parsed = parseInt(row.value, 10);
|
|
|
|
|
if (!Number.isNaN(parsed) && parsed > 0) return parsed;
|
|
|
|
|
}
|
2026-04-20 21:50:17 +08:00
|
|
|
return env.LOGIN_ATTEMPT_LIMIT;
|
2026-03-22 02:55:10 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ── Auth routes ────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
export async function authRoutes(app: FastifyInstance): Promise<void> {
|
|
|
|
|
// POST /api/auth/login
|
2026-03-25 09:25:59 +08:00
|
|
|
app.post(
|
|
|
|
|
"/api/auth/login",
|
|
|
|
|
{ config: { rateLimit: { max: getLoginAttemptLimit, timeWindow: "1 minute" } } },
|
|
|
|
|
async (request: FastifyRequest, reply: FastifyReply) => {
|
2026-04-23 14:45:04 +08:00
|
|
|
if (!env.AUTH_ENABLED) {
|
|
|
|
|
return reply.status(403).send({ error: "Authentication is disabled" });
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-23 20:26:58 +08:00
|
|
|
const parsed = loginSchema.safeParse(request.body);
|
|
|
|
|
if (!parsed.success) {
|
2026-03-25 09:25:59 +08:00
|
|
|
return reply.status(400).send({ error: "Username and password are required" });
|
|
|
|
|
}
|
2026-04-23 20:26:58 +08:00
|
|
|
const body = parsed.data;
|
2026-03-22 02:55:10 +08:00
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
// Postgres rejects NUL bytes (\x00) in text columns. Valid usernames
|
|
|
|
|
// never contain NUL, so such credentials can never match -- return 401
|
|
|
|
|
// immediately (same result SQLite produced by running the query).
|
|
|
|
|
if (body.username.includes("\x00") || body.password.includes("\x00")) {
|
|
|
|
|
return reply.status(401).send({ error: "Invalid credentials" });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const [user] = await db
|
2026-03-25 09:25:59 +08:00
|
|
|
.select()
|
|
|
|
|
.from(schema.users)
|
2026-06-13 10:15:23 +08:00
|
|
|
.where(eq(schema.users.username, body.username));
|
2026-03-22 02:55:10 +08:00
|
|
|
|
2026-05-13 18:52:39 +08:00
|
|
|
if (!user || !user.passwordHash) {
|
2026-06-13 10:15:23 +08:00
|
|
|
await auditLog(request.log, "LOGIN_FAILED", {
|
2026-06-07 21:54:27 +08:00
|
|
|
username: sanitizeAuditInput(body.username),
|
|
|
|
|
reason: "unknown_user",
|
|
|
|
|
});
|
2026-03-25 09:25:59 +08:00
|
|
|
return reply.status(401).send({ error: "Invalid credentials" });
|
|
|
|
|
}
|
2026-03-22 02:55:10 +08:00
|
|
|
|
2026-03-25 09:25:59 +08:00
|
|
|
const valid = await verifyPassword(body.password, user.passwordHash);
|
|
|
|
|
if (!valid) {
|
2026-06-13 10:15:23 +08:00
|
|
|
await auditLog(request.log, "LOGIN_FAILED", {
|
2026-06-07 21:54:27 +08:00
|
|
|
username: sanitizeAuditInput(body.username),
|
|
|
|
|
reason: "bad_password",
|
|
|
|
|
});
|
2026-03-25 09:25:59 +08:00
|
|
|
return reply.status(401).send({ error: "Invalid credentials" });
|
|
|
|
|
}
|
2026-03-22 02:55:10 +08:00
|
|
|
|
2026-03-25 09:25:59 +08:00
|
|
|
// Create session
|
|
|
|
|
const token = createSessionToken();
|
|
|
|
|
const expiresAt = new Date(Date.now() + SESSION_DURATION_MS);
|
2026-03-22 02:55:10 +08:00
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
await db.insert(schema.sessions).values({
|
|
|
|
|
id: token,
|
|
|
|
|
userId: user.id,
|
|
|
|
|
expiresAt,
|
|
|
|
|
});
|
2026-03-22 02:55:10 +08:00
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
await auditLog(request.log, "LOGIN_SUCCESS", { userId: user.id, username: user.username });
|
2026-03-28 11:19:09 +08:00
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
const [teamRow] = await db.select().from(schema.teams).where(eq(schema.teams.id, user.team));
|
2026-04-10 21:25:03 +08:00
|
|
|
|
2026-03-25 09:25:59 +08:00
|
|
|
return reply.send({
|
|
|
|
|
token,
|
|
|
|
|
user: {
|
|
|
|
|
id: user.id,
|
|
|
|
|
username: user.username,
|
|
|
|
|
role: user.role,
|
2026-04-20 15:03:56 +08:00
|
|
|
mustChangePassword: env.SKIP_MUST_CHANGE_PASSWORD ? false : user.mustChangePassword,
|
2026-06-13 10:15:23 +08:00
|
|
|
permissions: await getPermissions(user.role),
|
2026-04-10 21:25:03 +08:00
|
|
|
teamName: teamRow?.name ?? user.team,
|
2026-04-22 19:03:23 +08:00
|
|
|
analyticsEnabled: user.analyticsEnabled ?? null,
|
|
|
|
|
analyticsConsentShownAt: user.analyticsConsentShownAt?.getTime() ?? null,
|
|
|
|
|
analyticsConsentRemindAt: user.analyticsConsentRemindAt?.getTime() ?? null,
|
2026-03-25 09:25:59 +08:00
|
|
|
},
|
|
|
|
|
expiresAt: expiresAt.toISOString(),
|
|
|
|
|
});
|
|
|
|
|
},
|
|
|
|
|
);
|
2026-03-22 02:55:10 +08:00
|
|
|
|
|
|
|
|
// POST /api/auth/logout
|
|
|
|
|
app.post("/api/auth/logout", async (request: FastifyRequest, reply: FastifyReply) => {
|
|
|
|
|
const token = extractToken(request);
|
2026-03-28 11:19:09 +08:00
|
|
|
const user = getAuthUser(request);
|
2026-05-13 18:52:39 +08:00
|
|
|
let logoutUrl: string | undefined;
|
|
|
|
|
|
2026-03-22 02:55:10 +08:00
|
|
|
if (token) {
|
2026-06-13 10:15:23 +08:00
|
|
|
const [session] = await db
|
|
|
|
|
.select()
|
|
|
|
|
.from(schema.sessions)
|
|
|
|
|
.where(eq(schema.sessions.id, token));
|
2026-05-13 18:52:39 +08:00
|
|
|
|
|
|
|
|
if (session?.idToken && env.OIDC_ENABLED) {
|
|
|
|
|
try {
|
|
|
|
|
const { getOidcEndSessionEndpoint } = await import("./oidc.js");
|
|
|
|
|
const endSessionEndpoint = getOidcEndSessionEndpoint();
|
|
|
|
|
if (endSessionEndpoint) {
|
|
|
|
|
const params = new URLSearchParams({
|
|
|
|
|
id_token_hint: session.idToken,
|
|
|
|
|
post_logout_redirect_uri: `${env.EXTERNAL_URL}/login`,
|
|
|
|
|
});
|
|
|
|
|
logoutUrl = `${endSessionEndpoint}?${params.toString()}`;
|
|
|
|
|
}
|
|
|
|
|
} catch {
|
|
|
|
|
// OIDC plugin not loaded or discovery not cached
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
await db.delete(schema.sessions).where(eq(schema.sessions.id, token));
|
2026-03-22 02:55:10 +08:00
|
|
|
}
|
2026-05-13 18:52:39 +08:00
|
|
|
|
|
|
|
|
// Clear the session cookie
|
|
|
|
|
const cookieReply = reply as FastifyReply & {
|
|
|
|
|
clearCookie?: (name: string, opts: Record<string, unknown>) => void;
|
|
|
|
|
};
|
|
|
|
|
if (typeof cookieReply.clearCookie === "function") {
|
|
|
|
|
cookieReply.clearCookie("snapotter-session", { path: "/" });
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
await auditLog(request.log, "LOGOUT", { userId: user?.id });
|
2026-05-13 18:52:39 +08:00
|
|
|
return reply.send({ ok: true, ...(logoutUrl && { logoutUrl }) });
|
2026-03-22 02:55:10 +08:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// GET /api/auth/session
|
|
|
|
|
app.get("/api/auth/session", async (request: FastifyRequest, reply: FastifyReply) => {
|
2026-04-23 14:45:04 +08:00
|
|
|
if (!env.AUTH_ENABLED) {
|
|
|
|
|
return reply.send({
|
|
|
|
|
user: {
|
|
|
|
|
id: "anonymous",
|
|
|
|
|
username: "anonymous",
|
2026-05-16 12:25:28 +08:00
|
|
|
role: "admin",
|
2026-04-23 14:45:04 +08:00
|
|
|
mustChangePassword: false,
|
2026-06-13 10:15:23 +08:00
|
|
|
permissions: await getPermissions("admin"),
|
2026-04-23 14:45:04 +08:00
|
|
|
analyticsEnabled: null,
|
|
|
|
|
analyticsConsentShownAt: null,
|
|
|
|
|
analyticsConsentRemindAt: null,
|
|
|
|
|
},
|
|
|
|
|
expiresAt: null,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-22 02:55:10 +08:00
|
|
|
const token = extractToken(request);
|
|
|
|
|
if (!token) {
|
|
|
|
|
return reply.status(401).send({ error: "No session token provided" });
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
const [session] = await db.select().from(schema.sessions).where(eq(schema.sessions.id, token));
|
2026-03-22 02:55:10 +08:00
|
|
|
|
|
|
|
|
if (!session || session.expiresAt < new Date()) {
|
|
|
|
|
if (session) {
|
2026-06-13 10:15:23 +08:00
|
|
|
await db.delete(schema.sessions).where(eq(schema.sessions.id, token));
|
2026-03-22 02:55:10 +08:00
|
|
|
}
|
|
|
|
|
return reply.status(401).send({ error: "Session expired or invalid" });
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
const [user] = await db.select().from(schema.users).where(eq(schema.users.id, session.userId));
|
2026-03-22 02:55:10 +08:00
|
|
|
|
|
|
|
|
if (!user) {
|
|
|
|
|
return reply.status(401).send({ error: "User not found" });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return reply.send({
|
|
|
|
|
user: {
|
|
|
|
|
id: user.id,
|
|
|
|
|
username: user.username,
|
|
|
|
|
role: user.role,
|
2026-04-20 15:03:56 +08:00
|
|
|
mustChangePassword: env.SKIP_MUST_CHANGE_PASSWORD ? false : user.mustChangePassword,
|
2026-06-13 10:15:23 +08:00
|
|
|
permissions: await getPermissions(user.role),
|
2026-05-13 18:52:39 +08:00
|
|
|
authProvider: user.authProvider ?? "local",
|
|
|
|
|
loginMethod: session.idToken ? "oidc" : "local",
|
|
|
|
|
email: user.email ?? null,
|
|
|
|
|
hasLocalPassword: !!user.passwordHash,
|
|
|
|
|
hasOidcLink: !!user.externalId,
|
2026-04-22 19:03:23 +08:00
|
|
|
analyticsEnabled: user.analyticsEnabled ?? null,
|
|
|
|
|
analyticsConsentShownAt: user.analyticsConsentShownAt?.getTime() ?? null,
|
|
|
|
|
analyticsConsentRemindAt: user.analyticsConsentRemindAt?.getTime() ?? null,
|
2026-03-22 02:55:10 +08:00
|
|
|
},
|
|
|
|
|
expiresAt: session.expiresAt.toISOString(),
|
|
|
|
|
});
|
|
|
|
|
});
|
2026-03-22 19:28:57 +08:00
|
|
|
|
|
|
|
|
// POST /api/auth/change-password
|
|
|
|
|
app.post("/api/auth/change-password", async (request: FastifyRequest, reply: FastifyReply) => {
|
|
|
|
|
const authUser = requireAuth(request, reply);
|
|
|
|
|
if (!authUser) return;
|
|
|
|
|
|
2026-04-23 20:26:58 +08:00
|
|
|
const parsed = changePasswordSchema.safeParse(request.body);
|
|
|
|
|
if (!parsed.success) {
|
2026-03-22 19:28:57 +08:00
|
|
|
return reply.status(400).send({
|
|
|
|
|
error: "Current password and new password are required",
|
|
|
|
|
code: "VALIDATION_ERROR",
|
|
|
|
|
});
|
|
|
|
|
}
|
2026-04-23 20:26:58 +08:00
|
|
|
const body = parsed.data;
|
2026-03-22 19:28:57 +08:00
|
|
|
|
2026-03-24 21:38:06 +08:00
|
|
|
const pwError = validatePasswordStrength(body.newPassword);
|
|
|
|
|
if (pwError) {
|
2026-03-22 19:28:57 +08:00
|
|
|
return reply.status(400).send({
|
2026-03-24 21:38:06 +08:00
|
|
|
error: pwError,
|
2026-03-22 19:28:57 +08:00
|
|
|
code: "VALIDATION_ERROR",
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
const [user] = await db.select().from(schema.users).where(eq(schema.users.id, authUser.id));
|
2026-03-22 19:28:57 +08:00
|
|
|
|
|
|
|
|
if (!user) {
|
|
|
|
|
return reply.status(404).send({ error: "User not found", code: "NOT_FOUND" });
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-13 18:52:39 +08:00
|
|
|
if (!user.passwordHash) {
|
|
|
|
|
return reply.status(400).send({
|
|
|
|
|
error: "Password changes are managed by your identity provider.",
|
|
|
|
|
code: "OIDC_NO_PASSWORD",
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-22 19:28:57 +08:00
|
|
|
const valid = await verifyPassword(body.currentPassword, user.passwordHash);
|
|
|
|
|
if (!valid) {
|
2026-03-25 09:25:59 +08:00
|
|
|
return reply
|
|
|
|
|
.status(401)
|
|
|
|
|
.send({ error: "Current password is incorrect", code: "INVALID_PASSWORD" });
|
2026-03-22 19:28:57 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const newHash = await hashPassword(body.newPassword);
|
|
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
await db
|
|
|
|
|
.update(schema.users)
|
2026-03-22 19:28:57 +08:00
|
|
|
.set({ passwordHash: newHash, mustChangePassword: false, updatedAt: new Date() })
|
2026-06-13 10:15:23 +08:00
|
|
|
.where(eq(schema.users.id, authUser.id));
|
2026-03-22 19:28:57 +08:00
|
|
|
|
2026-03-23 11:46:45 +08:00
|
|
|
// Invalidate all other sessions for this user
|
|
|
|
|
const currentToken = extractToken(request);
|
2026-06-13 10:15:23 +08:00
|
|
|
if (currentToken) {
|
|
|
|
|
await db
|
|
|
|
|
.delete(schema.sessions)
|
|
|
|
|
.where(and(eq(schema.sessions.userId, authUser.id), ne(schema.sessions.id, currentToken)));
|
2026-03-23 11:46:45 +08:00
|
|
|
}
|
|
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
// Revoke all API keys - if credentials were compromised, keys must be rotated too
|
|
|
|
|
await db.delete(schema.apiKeys).where(eq(schema.apiKeys.userId, authUser.id));
|
2026-03-24 21:38:06 +08:00
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
await auditLog(request.log, "PASSWORD_CHANGED", {
|
|
|
|
|
userId: authUser.id,
|
|
|
|
|
username: authUser.username,
|
|
|
|
|
});
|
2026-03-28 11:19:09 +08:00
|
|
|
|
2026-03-22 19:28:57 +08:00
|
|
|
return reply.send({ ok: true });
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// GET /api/auth/users (admin only)
|
|
|
|
|
app.get("/api/auth/users", async (request: FastifyRequest, reply: FastifyReply) => {
|
2026-06-13 10:15:23 +08:00
|
|
|
const admin = await requirePermission("users:manage")(request, reply);
|
2026-03-22 19:28:57 +08:00
|
|
|
if (!admin) return;
|
|
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
const users = await db
|
2026-03-22 19:28:57 +08:00
|
|
|
.select({
|
|
|
|
|
id: schema.users.id,
|
|
|
|
|
username: schema.users.username,
|
|
|
|
|
role: schema.users.role,
|
2026-03-25 09:25:59 +08:00
|
|
|
team: schema.users.team,
|
2026-05-13 18:52:39 +08:00
|
|
|
authProvider: schema.users.authProvider,
|
|
|
|
|
email: schema.users.email,
|
|
|
|
|
externalId: schema.users.externalId,
|
|
|
|
|
passwordHash: schema.users.passwordHash,
|
2026-03-22 19:28:57 +08:00
|
|
|
createdAt: schema.users.createdAt,
|
|
|
|
|
})
|
2026-06-13 10:15:23 +08:00
|
|
|
.from(schema.users);
|
2026-03-22 19:28:57 +08:00
|
|
|
|
2026-04-04 17:44:51 +08:00
|
|
|
// Build a team ID -> name lookup
|
2026-06-13 10:15:23 +08:00
|
|
|
const allTeams = await db.select().from(schema.teams);
|
2026-04-04 17:44:51 +08:00
|
|
|
const teamNameById = new Map(allTeams.map((t) => [t.id, t.name]));
|
|
|
|
|
|
2026-03-22 19:28:57 +08:00
|
|
|
return reply.send({
|
|
|
|
|
users: users.map((u) => ({
|
2026-05-13 18:52:39 +08:00
|
|
|
id: u.id,
|
|
|
|
|
username: u.username,
|
|
|
|
|
role: u.role,
|
2026-04-04 17:44:51 +08:00
|
|
|
team: teamNameById.get(u.team) ?? u.team,
|
2026-05-13 18:52:39 +08:00
|
|
|
authProvider: u.authProvider ?? "local",
|
|
|
|
|
email: u.email ?? null,
|
|
|
|
|
hasLocalPassword: !!u.passwordHash,
|
|
|
|
|
hasOidcLink: !!u.externalId,
|
2026-03-22 19:28:57 +08:00
|
|
|
createdAt: u.createdAt.toISOString(),
|
|
|
|
|
})),
|
2026-03-25 09:25:59 +08:00
|
|
|
maxUsers: MAX_USERS,
|
2026-03-22 19:28:57 +08:00
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// POST /api/auth/register (admin only)
|
|
|
|
|
app.post("/api/auth/register", async (request: FastifyRequest, reply: FastifyReply) => {
|
2026-06-13 10:15:23 +08:00
|
|
|
const admin = await requirePermission("users:manage")(request, reply);
|
2026-03-22 19:28:57 +08:00
|
|
|
if (!admin) return;
|
|
|
|
|
|
2026-04-23 20:26:58 +08:00
|
|
|
const parsed = registerSchema.safeParse(request.body);
|
|
|
|
|
if (!parsed.success) {
|
2026-03-22 19:28:57 +08:00
|
|
|
return reply.status(400).send({
|
|
|
|
|
error: "Username and password are required",
|
|
|
|
|
code: "VALIDATION_ERROR",
|
|
|
|
|
});
|
|
|
|
|
}
|
2026-04-23 20:26:58 +08:00
|
|
|
const body = parsed.data;
|
2026-03-22 19:28:57 +08:00
|
|
|
|
2026-03-24 21:38:06 +08:00
|
|
|
const usernameError = validateUsername(body.username);
|
|
|
|
|
if (usernameError) {
|
2026-03-22 19:28:57 +08:00
|
|
|
return reply.status(400).send({
|
2026-03-24 21:38:06 +08:00
|
|
|
error: usernameError,
|
|
|
|
|
code: "VALIDATION_ERROR",
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const registerPwError = validatePasswordStrength(body.password);
|
|
|
|
|
if (registerPwError) {
|
|
|
|
|
return reply.status(400).send({
|
|
|
|
|
error: registerPwError,
|
2026-03-22 19:28:57 +08:00
|
|
|
code: "VALIDATION_ERROR",
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-22 18:10:04 +08:00
|
|
|
const validBuiltinRoles = ["admin", "editor", "user"];
|
|
|
|
|
let role: string = "user";
|
|
|
|
|
if (body.role) {
|
|
|
|
|
if (validBuiltinRoles.includes(body.role)) {
|
|
|
|
|
role = body.role;
|
|
|
|
|
} else {
|
2026-06-13 10:15:23 +08:00
|
|
|
const [customRole] = await db
|
2026-04-22 18:10:04 +08:00
|
|
|
.select()
|
|
|
|
|
.from(schema.roles)
|
2026-06-13 10:15:23 +08:00
|
|
|
.where(eq(schema.roles.name, body.role));
|
2026-04-22 18:10:04 +08:00
|
|
|
if (customRole) {
|
|
|
|
|
role = body.role;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Escalation prevention
|
|
|
|
|
const roleHierarchy: Record<string, number> = { admin: 3, editor: 2, user: 1 };
|
|
|
|
|
const actorLevel = roleHierarchy[admin.role] ?? 0;
|
|
|
|
|
const targetLevel = roleHierarchy[role] ?? 0;
|
|
|
|
|
if (targetLevel > actorLevel) {
|
|
|
|
|
return reply.status(403).send({
|
|
|
|
|
error: "Cannot create a user with a higher role than your own",
|
|
|
|
|
code: "ESCALATION_DENIED",
|
|
|
|
|
});
|
|
|
|
|
}
|
2026-03-22 19:28:57 +08:00
|
|
|
|
2026-04-23 20:26:58 +08:00
|
|
|
// Resolve team -- frontend sends team name (e.g. "Default"), not ID
|
|
|
|
|
const requestedTeam = body.team;
|
2026-04-04 17:44:51 +08:00
|
|
|
let teamId: string;
|
|
|
|
|
let teamName: string;
|
2026-03-25 09:25:59 +08:00
|
|
|
|
2026-03-27 15:31:01 +08:00
|
|
|
if (requestedTeam) {
|
|
|
|
|
// Look up by name first, then fall back to ID
|
2026-06-13 10:15:23 +08:00
|
|
|
const [teamByName] = await db
|
2026-03-25 09:25:59 +08:00
|
|
|
.select()
|
|
|
|
|
.from(schema.teams)
|
2026-06-13 10:15:23 +08:00
|
|
|
.where(eq(schema.teams.name, requestedTeam));
|
|
|
|
|
const [teamById] = teamByName
|
|
|
|
|
? [null]
|
|
|
|
|
: await db.select().from(schema.teams).where(eq(schema.teams.id, requestedTeam));
|
2026-03-27 15:31:01 +08:00
|
|
|
const found = teamByName || teamById;
|
|
|
|
|
if (!found)
|
2026-03-25 09:25:59 +08:00
|
|
|
return reply.status(400).send({ error: "Team not found", code: "VALIDATION_ERROR" });
|
2026-04-04 17:44:51 +08:00
|
|
|
teamId = found.id;
|
|
|
|
|
teamName = found.name;
|
2026-03-27 15:31:01 +08:00
|
|
|
} else {
|
2026-06-13 10:15:23 +08:00
|
|
|
const [defaultTeam] = await db
|
2026-03-27 15:31:01 +08:00
|
|
|
.select()
|
|
|
|
|
.from(schema.teams)
|
2026-06-13 10:15:23 +08:00
|
|
|
.where(eq(schema.teams.name, "Default"));
|
2026-04-04 17:44:51 +08:00
|
|
|
teamId = defaultTeam?.id || "default-team-00000000";
|
|
|
|
|
teamName = defaultTeam?.name || "Default";
|
2026-03-25 09:25:59 +08:00
|
|
|
}
|
|
|
|
|
|
2026-03-26 01:20:09 +08:00
|
|
|
// Check for duplicate username first (so 409 takes priority over limit)
|
2026-06-13 10:15:23 +08:00
|
|
|
const [existing] = await db
|
2026-03-22 19:28:57 +08:00
|
|
|
.select()
|
|
|
|
|
.from(schema.users)
|
2026-06-13 10:15:23 +08:00
|
|
|
.where(eq(schema.users.username, body.username));
|
2026-03-22 19:28:57 +08:00
|
|
|
|
|
|
|
|
if (existing) {
|
|
|
|
|
return reply.status(409).send({
|
|
|
|
|
error: "Username already exists",
|
|
|
|
|
code: "CONFLICT",
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-23 20:26:58 +08:00
|
|
|
// Check user limit (0 = unlimited)
|
|
|
|
|
if (MAX_USERS > 0) {
|
2026-06-13 10:15:23 +08:00
|
|
|
const allUsers = await db.select().from(schema.users);
|
|
|
|
|
const userCount = allUsers.length;
|
2026-04-23 20:26:58 +08:00
|
|
|
if (userCount >= MAX_USERS) {
|
|
|
|
|
return reply.status(403).send({
|
|
|
|
|
error: `User limit reached (${MAX_USERS} max)`,
|
|
|
|
|
code: "USER_LIMIT_REACHED",
|
|
|
|
|
});
|
|
|
|
|
}
|
2026-03-26 01:20:09 +08:00
|
|
|
}
|
|
|
|
|
|
2026-03-22 19:28:57 +08:00
|
|
|
const id = randomUUID();
|
|
|
|
|
const passwordHash = await hashPassword(body.password);
|
|
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
await db.insert(schema.users).values({
|
|
|
|
|
id,
|
|
|
|
|
username: body.username,
|
|
|
|
|
passwordHash,
|
|
|
|
|
role,
|
|
|
|
|
team: teamId,
|
|
|
|
|
mustChangePassword: true,
|
|
|
|
|
});
|
2026-03-22 19:28:57 +08:00
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
await auditLog(request.log, "USER_CREATED", {
|
2026-03-28 11:19:09 +08:00
|
|
|
adminId: admin.id,
|
|
|
|
|
newUserId: id,
|
|
|
|
|
newUsername: body.username,
|
|
|
|
|
role,
|
|
|
|
|
});
|
|
|
|
|
|
2026-03-22 19:28:57 +08:00
|
|
|
return reply.status(201).send({
|
|
|
|
|
id,
|
|
|
|
|
username: body.username,
|
|
|
|
|
role,
|
2026-04-04 17:44:51 +08:00
|
|
|
team: teamName,
|
2026-03-22 19:28:57 +08:00
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
2026-04-10 21:25:03 +08:00
|
|
|
// PUT /api/auth/users/:id (admin only — update role/team)
|
2026-03-25 09:25:59 +08:00
|
|
|
app.put(
|
|
|
|
|
"/api/auth/users/:id",
|
|
|
|
|
async (request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) => {
|
2026-06-13 10:15:23 +08:00
|
|
|
const admin = await requirePermission("users:manage")(request, reply);
|
2026-03-25 09:25:59 +08:00
|
|
|
if (!admin) return;
|
|
|
|
|
|
|
|
|
|
const { id } = request.params;
|
2026-04-23 20:26:58 +08:00
|
|
|
const parsed = updateUserSchema.safeParse(request.body);
|
|
|
|
|
if (!parsed.success) {
|
|
|
|
|
return reply.status(400).send({
|
|
|
|
|
error: parsed.error.issues.map((i) => i.message).join("; "),
|
|
|
|
|
code: "VALIDATION_ERROR",
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
const body = parsed.data;
|
2026-03-25 09:25:59 +08:00
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
const [user] = await db.select().from(schema.users).where(eq(schema.users.id, id));
|
2026-03-25 09:25:59 +08:00
|
|
|
|
|
|
|
|
if (!user) {
|
|
|
|
|
return reply.status(404).send({ error: "User not found", code: "NOT_FOUND" });
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-22 18:10:04 +08:00
|
|
|
const updates: { role?: string; team?: string; updatedAt: Date } = {
|
2026-03-25 09:25:59 +08:00
|
|
|
updatedAt: new Date(),
|
|
|
|
|
};
|
|
|
|
|
|
2026-04-22 18:10:04 +08:00
|
|
|
// Escalation prevention
|
2026-04-23 20:26:58 +08:00
|
|
|
if (body.role) {
|
2026-04-22 18:10:04 +08:00
|
|
|
const roleHierarchy: Record<string, number> = { admin: 3, editor: 2, user: 1 };
|
|
|
|
|
const actorLevel = roleHierarchy[admin.role] ?? 0;
|
|
|
|
|
const targetLevel = roleHierarchy[body.role] ?? 0;
|
|
|
|
|
if (targetLevel > actorLevel) {
|
|
|
|
|
return reply.status(403).send({
|
|
|
|
|
error: "Cannot assign a role higher than your own",
|
|
|
|
|
code: "ESCALATION_DENIED",
|
2026-03-25 09:25:59 +08:00
|
|
|
});
|
|
|
|
|
}
|
2026-04-22 18:10:04 +08:00
|
|
|
}
|
|
|
|
|
|
2026-04-23 20:26:58 +08:00
|
|
|
if (body.role) {
|
2026-04-22 18:10:04 +08:00
|
|
|
const validBuiltinRoles = ["admin", "editor", "user"];
|
2026-06-13 10:15:23 +08:00
|
|
|
const [customRoleRow] = validBuiltinRoles.includes(body.role)
|
|
|
|
|
? [null]
|
|
|
|
|
: await db.select().from(schema.roles).where(eq(schema.roles.name, body.role));
|
|
|
|
|
const isValid = validBuiltinRoles.includes(body.role) || customRoleRow;
|
2026-04-22 18:10:04 +08:00
|
|
|
if (isValid) {
|
|
|
|
|
// Prevent removing your own admin role
|
|
|
|
|
if (id === admin.id && body.role !== "admin") {
|
|
|
|
|
return reply.status(400).send({
|
|
|
|
|
error: "Cannot remove your own admin role",
|
|
|
|
|
code: "SELF_DEMOTE",
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Last admin protection
|
|
|
|
|
if (user.role === "admin" && body.role !== "admin") {
|
2026-06-13 10:15:23 +08:00
|
|
|
const [adminCount] = await db
|
2026-04-22 18:10:04 +08:00
|
|
|
.select({ count: sql<number>`COUNT(*)` })
|
|
|
|
|
.from(schema.users)
|
2026-06-13 10:15:23 +08:00
|
|
|
.where(eq(schema.users.role, "admin"));
|
2026-04-22 18:10:04 +08:00
|
|
|
if (adminCount && adminCount.count <= 1) {
|
|
|
|
|
return reply.status(400).send({
|
|
|
|
|
error: "Cannot demote the last admin",
|
|
|
|
|
code: "LAST_ADMIN",
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
updates.role = body.role;
|
|
|
|
|
}
|
2026-03-25 09:25:59 +08:00
|
|
|
}
|
|
|
|
|
|
2026-04-23 20:26:58 +08:00
|
|
|
if (body.team?.trim()) {
|
2026-04-04 17:44:51 +08:00
|
|
|
// Look up by name first, then fall back to ID
|
2026-06-13 10:15:23 +08:00
|
|
|
const [teamByName] = await db
|
2026-03-25 09:25:59 +08:00
|
|
|
.select()
|
|
|
|
|
.from(schema.teams)
|
2026-06-13 10:15:23 +08:00
|
|
|
.where(eq(schema.teams.name, body.team.trim()));
|
|
|
|
|
const [teamById] = teamByName
|
|
|
|
|
? [null]
|
|
|
|
|
: await db.select().from(schema.teams).where(eq(schema.teams.id, body.team.trim()));
|
2026-04-04 17:44:51 +08:00
|
|
|
const found = teamByName || teamById;
|
|
|
|
|
if (!found) {
|
2026-03-25 09:25:59 +08:00
|
|
|
return reply.status(400).send({ error: "Team not found", code: "VALIDATION_ERROR" });
|
|
|
|
|
}
|
2026-04-04 17:44:51 +08:00
|
|
|
updates.team = found.id;
|
2026-03-25 09:25:59 +08:00
|
|
|
}
|
|
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
await db.update(schema.users).set(updates).where(eq(schema.users.id, id));
|
2026-03-25 09:25:59 +08:00
|
|
|
|
2026-05-13 21:33:50 +08:00
|
|
|
// Invalidate all sessions when role changes to force re-login with new permissions
|
|
|
|
|
if (updates.role && updates.role !== user.role) {
|
2026-06-13 10:15:23 +08:00
|
|
|
await db.delete(schema.sessions).where(eq(schema.sessions.userId, id));
|
2026-05-13 21:33:50 +08:00
|
|
|
request.log.info(
|
|
|
|
|
{ targetUserId: id, oldRole: user.role, newRole: updates.role },
|
|
|
|
|
"Sessions invalidated due to role change",
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
await auditLog(request.log, "USER_UPDATED", {
|
2026-03-28 11:19:09 +08:00
|
|
|
adminId: admin.id,
|
|
|
|
|
targetUserId: id,
|
|
|
|
|
changes: { role: updates.role, team: updates.team },
|
|
|
|
|
});
|
|
|
|
|
|
2026-03-25 09:25:59 +08:00
|
|
|
return reply.send({ ok: true });
|
|
|
|
|
},
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
// POST /api/auth/users/:id/reset-password (admin only)
|
|
|
|
|
app.post(
|
|
|
|
|
"/api/auth/users/:id/reset-password",
|
|
|
|
|
async (request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) => {
|
2026-06-13 10:15:23 +08:00
|
|
|
const admin = await requirePermission("users:manage")(request, reply);
|
2026-03-25 09:25:59 +08:00
|
|
|
if (!admin) return;
|
|
|
|
|
|
|
|
|
|
const { id } = request.params;
|
2026-04-23 20:26:58 +08:00
|
|
|
const parsed = resetPasswordSchema.safeParse(request.body);
|
|
|
|
|
if (!parsed.success) {
|
2026-03-25 09:25:59 +08:00
|
|
|
return reply.status(400).send({
|
|
|
|
|
error: "New password is required",
|
|
|
|
|
code: "VALIDATION_ERROR",
|
|
|
|
|
});
|
|
|
|
|
}
|
2026-04-23 20:26:58 +08:00
|
|
|
const body = parsed.data;
|
2026-03-25 09:25:59 +08:00
|
|
|
|
|
|
|
|
const pwError = validatePasswordStrength(body.newPassword);
|
|
|
|
|
if (pwError) {
|
|
|
|
|
return reply.status(400).send({
|
|
|
|
|
error: pwError,
|
|
|
|
|
code: "VALIDATION_ERROR",
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
const [user] = await db.select().from(schema.users).where(eq(schema.users.id, id));
|
2026-03-25 09:25:59 +08:00
|
|
|
|
|
|
|
|
if (!user) {
|
|
|
|
|
return reply.status(404).send({ error: "User not found", code: "NOT_FOUND" });
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-13 18:52:39 +08:00
|
|
|
if (!user.passwordHash) {
|
|
|
|
|
return reply.status(400).send({
|
|
|
|
|
error: "Cannot reset password for OIDC user.",
|
|
|
|
|
code: "OIDC_NO_PASSWORD",
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-25 09:25:59 +08:00
|
|
|
const newHash = await hashPassword(body.newPassword);
|
|
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
await db
|
|
|
|
|
.update(schema.users)
|
2026-03-25 09:25:59 +08:00
|
|
|
.set({ passwordHash: newHash, mustChangePassword: true, updatedAt: new Date() })
|
2026-06-13 10:15:23 +08:00
|
|
|
.where(eq(schema.users.id, id));
|
2026-03-25 09:25:59 +08:00
|
|
|
|
|
|
|
|
// Invalidate all sessions for this user
|
2026-06-13 10:15:23 +08:00
|
|
|
await db.delete(schema.sessions).where(eq(schema.sessions.userId, id));
|
2026-03-25 09:25:59 +08:00
|
|
|
|
|
|
|
|
// Revoke all API keys
|
2026-06-13 10:15:23 +08:00
|
|
|
await db.delete(schema.apiKeys).where(eq(schema.apiKeys.userId, id));
|
2026-03-25 09:25:59 +08:00
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
await auditLog(request.log, "PASSWORD_RESET", {
|
2026-03-28 11:19:09 +08:00
|
|
|
adminId: admin.id,
|
|
|
|
|
targetUserId: id,
|
|
|
|
|
targetUsername: user.username,
|
|
|
|
|
});
|
|
|
|
|
|
2026-03-25 09:25:59 +08:00
|
|
|
return reply.send({ ok: true });
|
|
|
|
|
},
|
|
|
|
|
);
|
|
|
|
|
|
2026-03-22 19:28:57 +08:00
|
|
|
// DELETE /api/auth/users/:id (admin only, can't delete self)
|
|
|
|
|
app.delete(
|
|
|
|
|
"/api/auth/users/:id",
|
2026-03-25 09:25:59 +08:00
|
|
|
async (request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) => {
|
2026-06-13 10:15:23 +08:00
|
|
|
const admin = await requirePermission("users:manage")(request, reply);
|
2026-03-22 19:28:57 +08:00
|
|
|
if (!admin) return;
|
|
|
|
|
|
|
|
|
|
const { id } = request.params;
|
|
|
|
|
|
|
|
|
|
if (id === admin.id) {
|
|
|
|
|
return reply.status(400).send({
|
|
|
|
|
error: "Cannot delete your own account",
|
|
|
|
|
code: "SELF_DELETE",
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
const [user] = await db.select().from(schema.users).where(eq(schema.users.id, id));
|
2026-03-22 19:28:57 +08:00
|
|
|
|
|
|
|
|
if (!user) {
|
|
|
|
|
return reply.status(404).send({ error: "User not found", code: "NOT_FOUND" });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Delete associated sessions
|
2026-06-13 10:15:23 +08:00
|
|
|
await db.delete(schema.sessions).where(eq(schema.sessions.userId, id));
|
2026-03-22 19:28:57 +08:00
|
|
|
|
|
|
|
|
// Delete the user (cascades to api_keys via FK)
|
2026-06-13 10:15:23 +08:00
|
|
|
await db.delete(schema.users).where(eq(schema.users.id, id));
|
2026-03-22 19:28:57 +08:00
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
await auditLog(request.log, "USER_DELETED", {
|
2026-03-28 11:19:09 +08:00
|
|
|
adminId: admin.id,
|
|
|
|
|
deletedUserId: id,
|
|
|
|
|
deletedUsername: user.username,
|
|
|
|
|
});
|
|
|
|
|
|
2026-03-22 19:28:57 +08:00
|
|
|
return reply.send({ ok: true });
|
|
|
|
|
},
|
|
|
|
|
);
|
2026-03-22 02:55:10 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ── Token extraction ───────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
function extractToken(request: FastifyRequest): string | null {
|
|
|
|
|
const authHeader = request.headers.authorization;
|
|
|
|
|
if (authHeader?.startsWith("Bearer ")) {
|
|
|
|
|
return authHeader.slice(7);
|
|
|
|
|
}
|
2026-05-13 18:52:39 +08:00
|
|
|
const cookies = (request as FastifyRequest & { cookies?: Record<string, string> }).cookies;
|
|
|
|
|
if (cookies?.["snapotter-session"]) {
|
|
|
|
|
return cookies["snapotter-session"];
|
|
|
|
|
}
|
2026-03-22 02:55:10 +08:00
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ── Auth middleware ────────────────────────────────────────────────
|
|
|
|
|
|
2026-03-25 09:25:59 +08:00
|
|
|
const PUBLIC_PATHS = [
|
|
|
|
|
"/api/v1/health",
|
2026-06-13 10:17:13 +08:00
|
|
|
"/api/v1/readyz",
|
2026-03-25 09:25:59 +08:00
|
|
|
"/api/v1/config/",
|
|
|
|
|
"/api/auth/",
|
|
|
|
|
"/api/v1/download/",
|
|
|
|
|
"/api/v1/jobs/",
|
2026-03-27 12:28:11 +08:00
|
|
|
"/api/docs",
|
|
|
|
|
"/api/v1/openapi.yaml",
|
2026-05-08 23:30:27 +08:00
|
|
|
"/api/v1/meme-templates/",
|
2026-03-25 09:25:59 +08:00
|
|
|
];
|
2026-03-22 02:55:10 +08:00
|
|
|
|
|
|
|
|
function isPublicRoute(url: string): boolean {
|
2026-03-22 19:28:57 +08:00
|
|
|
// Non-API routes are public (SPA static files — auth is handled client-side)
|
|
|
|
|
if (!url.startsWith("/api/")) return true;
|
|
|
|
|
// Download URLs use unguessable UUIDs as capability tokens — no auth needed
|
2026-03-22 02:55:10 +08:00
|
|
|
return PUBLIC_PATHS.some((path) => url.startsWith(path));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function authMiddleware(app: FastifyInstance): Promise<void> {
|
2026-03-25 09:25:59 +08:00
|
|
|
app.addHook("preHandler", async (request: FastifyRequest, reply: FastifyReply) => {
|
|
|
|
|
if (!env.AUTH_ENABLED) {
|
2026-04-21 23:38:42 +08:00
|
|
|
(request as FastifyRequest & { user?: AuthUser }).user = {
|
|
|
|
|
id: "anonymous",
|
|
|
|
|
username: "anonymous",
|
2026-05-16 11:37:28 +08:00
|
|
|
role: "admin",
|
2026-04-21 23:38:42 +08:00
|
|
|
};
|
2026-03-25 09:25:59 +08:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const isPublic = isPublicRoute(request.url);
|
|
|
|
|
|
|
|
|
|
const token = extractToken(request);
|
|
|
|
|
if (!token) {
|
|
|
|
|
// Public routes don't require a token
|
|
|
|
|
if (isPublic) return;
|
|
|
|
|
return reply.status(401).send({ error: "Authentication required" });
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
const [session] = await db.select().from(schema.sessions).where(eq(schema.sessions.id, token));
|
2026-03-25 09:25:59 +08:00
|
|
|
|
|
|
|
|
if (!session || session.expiresAt < new Date()) {
|
|
|
|
|
if (session) {
|
2026-06-13 10:15:23 +08:00
|
|
|
await db.delete(schema.sessions).where(eq(schema.sessions.id, token));
|
2026-03-25 09:25:59 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Try API key authentication if token has si_ prefix
|
|
|
|
|
if (token.startsWith("si_")) {
|
|
|
|
|
const prefix = computeKeyPrefix(token);
|
|
|
|
|
// Lookup by prefix (O(1) instead of scanning all keys)
|
2026-06-13 10:15:23 +08:00
|
|
|
const candidates = await db
|
2026-03-22 21:25:14 +08:00
|
|
|
.select()
|
2026-03-25 09:25:59 +08:00
|
|
|
.from(schema.apiKeys)
|
2026-06-13 10:15:23 +08:00
|
|
|
.where(eq(schema.apiKeys.keyPrefix, prefix));
|
2026-05-13 21:33:50 +08:00
|
|
|
// Fall back to full scan for legacy keys without a prefix (bounded to 100)
|
|
|
|
|
let keysToCheck: typeof candidates;
|
|
|
|
|
if (candidates.length > 0) {
|
|
|
|
|
keysToCheck = candidates;
|
|
|
|
|
} else {
|
|
|
|
|
request.log.warn(
|
|
|
|
|
"Legacy API key lookup triggered (no keyPrefix match). Migrate keys to use prefix-based lookup.",
|
|
|
|
|
);
|
2026-06-13 10:15:23 +08:00
|
|
|
const allKeys = await db.select().from(schema.apiKeys);
|
|
|
|
|
keysToCheck = allKeys.filter((k) => !k.keyPrefix).slice(0, 100);
|
2026-05-13 21:33:50 +08:00
|
|
|
}
|
2026-03-25 09:25:59 +08:00
|
|
|
for (const key of keysToCheck) {
|
|
|
|
|
const matches = await verifyPassword(token, key.keyHash);
|
|
|
|
|
if (matches) {
|
2026-04-22 18:10:04 +08:00
|
|
|
// Check expiration
|
|
|
|
|
if (key.expiresAt && key.expiresAt < new Date()) {
|
2026-06-13 10:15:23 +08:00
|
|
|
// Key expired - skip it
|
2026-04-22 18:10:04 +08:00
|
|
|
continue;
|
|
|
|
|
}
|
2026-03-25 09:25:59 +08:00
|
|
|
// Backfill prefix for legacy keys
|
|
|
|
|
if (!key.keyPrefix) {
|
2026-06-13 10:15:23 +08:00
|
|
|
await db
|
|
|
|
|
.update(schema.apiKeys)
|
2026-03-25 09:25:59 +08:00
|
|
|
.set({ keyPrefix: prefix, lastUsedAt: new Date() })
|
2026-06-13 10:15:23 +08:00
|
|
|
.where(eq(schema.apiKeys.id, key.id));
|
2026-03-25 09:25:59 +08:00
|
|
|
} else {
|
2026-06-13 10:15:23 +08:00
|
|
|
await db
|
|
|
|
|
.update(schema.apiKeys)
|
2026-03-25 09:25:59 +08:00
|
|
|
.set({ lastUsedAt: new Date() })
|
2026-06-13 10:15:23 +08:00
|
|
|
.where(eq(schema.apiKeys.id, key.id));
|
2026-03-25 09:25:59 +08:00
|
|
|
}
|
|
|
|
|
// Load the user
|
2026-06-13 10:15:23 +08:00
|
|
|
const [apiUser] = await db
|
2026-03-25 09:25:59 +08:00
|
|
|
.select()
|
|
|
|
|
.from(schema.users)
|
2026-06-13 10:15:23 +08:00
|
|
|
.where(eq(schema.users.id, key.userId));
|
2026-03-25 09:25:59 +08:00
|
|
|
if (apiUser) {
|
2026-06-13 10:15:23 +08:00
|
|
|
const keyPermissions = key.permissions ?? undefined;
|
2026-03-25 09:25:59 +08:00
|
|
|
(request as FastifyRequest & { user?: AuthUser }).user = {
|
|
|
|
|
id: apiUser.id,
|
|
|
|
|
username: apiUser.username,
|
2026-04-22 18:10:04 +08:00
|
|
|
role: apiUser.role,
|
|
|
|
|
apiKeyPermissions: keyPermissions,
|
2026-03-25 09:25:59 +08:00
|
|
|
};
|
|
|
|
|
return;
|
2026-03-23 11:46:45 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-03-22 02:55:10 +08:00
|
|
|
}
|
|
|
|
|
|
2026-03-25 09:25:59 +08:00
|
|
|
// Public routes can proceed without a valid session
|
|
|
|
|
if (isPublic) return;
|
|
|
|
|
return reply.status(401).send({ error: "Session expired or invalid" });
|
|
|
|
|
}
|
2026-03-22 02:55:10 +08:00
|
|
|
|
2026-06-13 10:15:23 +08:00
|
|
|
const [user] = await db.select().from(schema.users).where(eq(schema.users.id, session.userId));
|
2026-03-25 09:25:59 +08:00
|
|
|
|
|
|
|
|
if (!user) {
|
|
|
|
|
if (isPublic) return;
|
|
|
|
|
return reply.status(401).send({ error: "User not found" });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Attach user info to request for downstream handlers
|
|
|
|
|
// (always populate when a valid session exists, even on public routes)
|
|
|
|
|
(request as FastifyRequest & { user?: AuthUser }).user = {
|
|
|
|
|
id: user.id,
|
|
|
|
|
username: user.username,
|
2026-04-22 18:10:04 +08:00
|
|
|
role: user.role,
|
2026-03-25 09:25:59 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Enforce mustChangePassword — block non-auth API calls
|
2026-03-28 11:19:09 +08:00
|
|
|
// (skipped when SKIP_MUST_CHANGE_PASSWORD=true for CI/dev environments)
|
|
|
|
|
if (user.mustChangePassword && !env.SKIP_MUST_CHANGE_PASSWORD) {
|
2026-03-25 09:25:59 +08:00
|
|
|
const allowed = [
|
|
|
|
|
"/api/auth/change-password",
|
|
|
|
|
"/api/auth/logout",
|
|
|
|
|
"/api/auth/session",
|
|
|
|
|
"/api/v1/config/",
|
|
|
|
|
];
|
|
|
|
|
if (!allowed.some((p) => request.url.startsWith(p)) && request.url.startsWith("/api/")) {
|
|
|
|
|
return reply.status(403).send({
|
|
|
|
|
error: "Password change required",
|
|
|
|
|
code: "MUST_CHANGE_PASSWORD",
|
|
|
|
|
});
|
2026-03-22 02:55:10 +08:00
|
|
|
}
|
2026-03-25 09:25:59 +08:00
|
|
|
}
|
|
|
|
|
});
|
2026-03-22 02:55:10 +08:00
|
|
|
}
|