mirror of
https://github.com/snapotter-hq/SnapOtter.git
synced 2026-08-03 07:46:42 +02:00
feat: production Docker, Playwright tests, settings API, and bug fixes
- Add user management endpoints (register, list, delete, change password) - Add API key management (create, list, delete) - Add settings persistence endpoints (get, put) - Wire settings dialog to real backend (People, API Keys, System, Security) - Fix login auth flow (window.location.href for full reload) - Fix download URLs returning 401 (make public since UUIDs are unguessable) - Fix border tool shadowColor validation (accept 6-8 hex digits) - Fix remove-bg alpha matting fallback (retry without on failure) - Fix AI tool silent fallbacks (report errors instead of no-ops) - Add checkerboard background to before/after slider for transparency - Add progress bars to all AI tool components - Add Playwright E2E test suite (131 tests across 9 test files) - Rewrite Dockerfile for production (tsx runtime, pre-baked AI models) - Add .dockerignore for faster builds - Add proper accessible labels to login form
This commit is contained in:
@@ -15,6 +15,8 @@ import { registerToolRoutes } from "./routes/tools/index.js";
|
||||
import { registerBatchRoutes } from "./routes/batch.js";
|
||||
import { registerPipelineRoutes } from "./routes/pipeline.js";
|
||||
import { registerProgressRoutes } from "./routes/progress.js";
|
||||
import { apiKeyRoutes } from "./routes/api-keys.js";
|
||||
import { settingsRoutes } from "./routes/settings.js";
|
||||
|
||||
// Run before anything else
|
||||
runMigrations();
|
||||
@@ -75,6 +77,12 @@ await registerPipelineRoutes(app);
|
||||
// Progress SSE routes
|
||||
await registerProgressRoutes(app);
|
||||
|
||||
// API key management routes
|
||||
await apiKeyRoutes(app);
|
||||
|
||||
// Settings routes
|
||||
await settingsRoutes(app);
|
||||
|
||||
// Health check
|
||||
app.get("/api/v1/health", async () => ({
|
||||
status: "healthy",
|
||||
|
||||
@@ -8,18 +8,26 @@ import { env } from "../config.js";
|
||||
|
||||
const scryptAsync = promisify(scrypt);
|
||||
|
||||
// ── Types ─────────────────────────────────────────────────────────
|
||||
|
||||
export interface AuthUser {
|
||||
id: string;
|
||||
username: string;
|
||||
role: "admin" | "user";
|
||||
}
|
||||
|
||||
// ── Password hashing ──────────────────────────────────────────────
|
||||
|
||||
const SALT_LENGTH = 32;
|
||||
const KEY_LENGTH = 64;
|
||||
|
||||
async function hashPassword(password: string): Promise<string> {
|
||||
export async function hashPassword(password: string): Promise<string> {
|
||||
const salt = randomBytes(SALT_LENGTH).toString("hex");
|
||||
const derived = (await scryptAsync(password, salt, KEY_LENGTH)) as Buffer;
|
||||
return `${salt}:${derived.toString("hex")}`;
|
||||
}
|
||||
|
||||
async function verifyPassword(
|
||||
export async function verifyPassword(
|
||||
password: string,
|
||||
stored: string,
|
||||
): Promise<boolean> {
|
||||
@@ -31,6 +39,34 @@ async function verifyPassword(
|
||||
return timingSafeEqual(derived, storedBuf);
|
||||
}
|
||||
|
||||
// ── 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;
|
||||
}
|
||||
|
||||
/** 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;
|
||||
}
|
||||
|
||||
// ── Session helpers ────────────────────────────────────────────────
|
||||
|
||||
const SESSION_DURATION_MS = 24 * 60 * 60 * 1000; // 24 hours
|
||||
@@ -161,6 +197,182 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
|
||||
expiresAt: session.expiresAt.toISOString(),
|
||||
});
|
||||
});
|
||||
|
||||
// POST /api/auth/change-password
|
||||
app.post("/api/auth/change-password", async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const authUser = requireAuth(request, reply);
|
||||
if (!authUser) return;
|
||||
|
||||
const body = request.body as {
|
||||
currentPassword?: string;
|
||||
newPassword?: string;
|
||||
} | null;
|
||||
|
||||
if (!body?.currentPassword || !body?.newPassword) {
|
||||
return reply.status(400).send({
|
||||
error: "Current password and new password are required",
|
||||
code: "VALIDATION_ERROR",
|
||||
});
|
||||
}
|
||||
|
||||
if (body.newPassword.length < 8) {
|
||||
return reply.status(400).send({
|
||||
error: "New password must be at least 8 characters",
|
||||
code: "VALIDATION_ERROR",
|
||||
});
|
||||
}
|
||||
|
||||
const user = db
|
||||
.select()
|
||||
.from(schema.users)
|
||||
.where(eq(schema.users.id, authUser.id))
|
||||
.get();
|
||||
|
||||
if (!user) {
|
||||
return reply.status(404).send({ error: "User not found", code: "NOT_FOUND" });
|
||||
}
|
||||
|
||||
const valid = await verifyPassword(body.currentPassword, user.passwordHash);
|
||||
if (!valid) {
|
||||
return reply.status(401).send({ error: "Current password is incorrect", code: "INVALID_PASSWORD" });
|
||||
}
|
||||
|
||||
const newHash = await hashPassword(body.newPassword);
|
||||
|
||||
db.update(schema.users)
|
||||
.set({ passwordHash: newHash, mustChangePassword: false, updatedAt: new Date() })
|
||||
.where(eq(schema.users.id, authUser.id))
|
||||
.run();
|
||||
|
||||
return reply.send({ ok: true });
|
||||
});
|
||||
|
||||
// GET /api/auth/users (admin only)
|
||||
app.get("/api/auth/users", async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
const users = db
|
||||
.select({
|
||||
id: schema.users.id,
|
||||
username: schema.users.username,
|
||||
role: schema.users.role,
|
||||
createdAt: schema.users.createdAt,
|
||||
})
|
||||
.from(schema.users)
|
||||
.all();
|
||||
|
||||
return reply.send({
|
||||
users: users.map((u) => ({
|
||||
...u,
|
||||
createdAt: u.createdAt.toISOString(),
|
||||
})),
|
||||
});
|
||||
});
|
||||
|
||||
// POST /api/auth/register (admin only)
|
||||
app.post("/api/auth/register", async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
const body = request.body as {
|
||||
username?: string;
|
||||
password?: string;
|
||||
role?: string;
|
||||
} | null;
|
||||
|
||||
if (!body?.username || !body?.password) {
|
||||
return reply.status(400).send({
|
||||
error: "Username and password are required",
|
||||
code: "VALIDATION_ERROR",
|
||||
});
|
||||
}
|
||||
|
||||
if (body.password.length < 8) {
|
||||
return reply.status(400).send({
|
||||
error: "Password must be at least 8 characters",
|
||||
code: "VALIDATION_ERROR",
|
||||
});
|
||||
}
|
||||
|
||||
const role = body.role === "admin" ? "admin" : "user";
|
||||
|
||||
// Check for duplicate username
|
||||
const existing = db
|
||||
.select()
|
||||
.from(schema.users)
|
||||
.where(eq(schema.users.username, body.username))
|
||||
.get();
|
||||
|
||||
if (existing) {
|
||||
return reply.status(409).send({
|
||||
error: "Username already exists",
|
||||
code: "CONFLICT",
|
||||
});
|
||||
}
|
||||
|
||||
const id = randomUUID();
|
||||
const passwordHash = await hashPassword(body.password);
|
||||
|
||||
db.insert(schema.users)
|
||||
.values({
|
||||
id,
|
||||
username: body.username,
|
||||
passwordHash,
|
||||
role,
|
||||
mustChangePassword: true,
|
||||
})
|
||||
.run();
|
||||
|
||||
return reply.status(201).send({
|
||||
id,
|
||||
username: body.username,
|
||||
role,
|
||||
});
|
||||
});
|
||||
|
||||
// DELETE /api/auth/users/:id (admin only, can't delete self)
|
||||
app.delete(
|
||||
"/api/auth/users/:id",
|
||||
async (
|
||||
request: FastifyRequest<{ Params: { id: string } }>,
|
||||
reply: FastifyReply,
|
||||
) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
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",
|
||||
});
|
||||
}
|
||||
|
||||
const user = db
|
||||
.select()
|
||||
.from(schema.users)
|
||||
.where(eq(schema.users.id, id))
|
||||
.get();
|
||||
|
||||
if (!user) {
|
||||
return reply.status(404).send({ error: "User not found", code: "NOT_FOUND" });
|
||||
}
|
||||
|
||||
// Delete associated sessions
|
||||
db.delete(schema.sessions)
|
||||
.where(eq(schema.sessions.userId, id))
|
||||
.run();
|
||||
|
||||
// Delete the user (cascades to api_keys via FK)
|
||||
db.delete(schema.users)
|
||||
.where(eq(schema.users.id, id))
|
||||
.run();
|
||||
|
||||
return reply.send({ ok: true });
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// ── Token extraction ───────────────────────────────────────────────
|
||||
@@ -176,9 +388,12 @@ function extractToken(request: FastifyRequest): string | null {
|
||||
|
||||
// ── Auth middleware ────────────────────────────────────────────────
|
||||
|
||||
const PUBLIC_PATHS = ["/api/v1/health", "/api/v1/config/", "/api/auth/", "/api/docs"];
|
||||
const PUBLIC_PATHS = ["/api/v1/health", "/api/v1/config/", "/api/auth/", "/api/docs", "/api/v1/download/"];
|
||||
|
||||
function isPublicRoute(url: string): boolean {
|
||||
// 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
|
||||
return PUBLIC_PATHS.some((path) => url.startsWith(path));
|
||||
}
|
||||
|
||||
@@ -189,11 +404,12 @@ export async function authMiddleware(app: FastifyInstance): Promise<void> {
|
||||
// Skip if auth is disabled
|
||||
if (!env.AUTH_ENABLED) return;
|
||||
|
||||
// Skip public routes
|
||||
if (isPublicRoute(request.url)) 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" });
|
||||
}
|
||||
|
||||
@@ -209,6 +425,8 @@ export async function authMiddleware(app: FastifyInstance): Promise<void> {
|
||||
.where(eq(schema.sessions.id, token))
|
||||
.run();
|
||||
}
|
||||
// Public routes can proceed without a valid session
|
||||
if (isPublic) return;
|
||||
return reply.status(401).send({ error: "Session expired or invalid" });
|
||||
}
|
||||
|
||||
@@ -219,14 +437,16 @@ export async function authMiddleware(app: FastifyInstance): Promise<void> {
|
||||
.get();
|
||||
|
||||
if (!user) {
|
||||
if (isPublic) return;
|
||||
return reply.status(401).send({ error: "User not found" });
|
||||
}
|
||||
|
||||
// Attach user info to request for downstream handlers
|
||||
(request as FastifyRequest & { user?: unknown }).user = {
|
||||
// (always populate when a valid session exists, even on public routes)
|
||||
(request as FastifyRequest & { user?: AuthUser }).user = {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
role: user.role,
|
||||
role: user.role as "admin" | "user",
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* API Key management routes.
|
||||
*
|
||||
* POST /api/v1/api-keys — Generate a new API key
|
||||
* GET /api/v1/api-keys — List the current user's API keys
|
||||
* DELETE /api/v1/api-keys/:id — Delete an API key
|
||||
*/
|
||||
import { randomBytes, randomUUID } from "node:crypto";
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from "fastify";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import { db, schema } from "../db/index.js";
|
||||
import { hashPassword, requireAuth } from "../plugins/auth.js";
|
||||
|
||||
export async function apiKeyRoutes(app: FastifyInstance): Promise<void> {
|
||||
// POST /api/v1/api-keys — Generate a new API key
|
||||
app.post(
|
||||
"/api/v1/api-keys",
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const user = requireAuth(request, reply);
|
||||
if (!user) return;
|
||||
|
||||
const body = request.body as { name?: string } | null;
|
||||
const name = body?.name?.trim() || "Default API Key";
|
||||
|
||||
if (name.length > 100) {
|
||||
return reply.status(400).send({
|
||||
error: "Key name must be 100 characters or fewer",
|
||||
code: "VALIDATION_ERROR",
|
||||
});
|
||||
}
|
||||
|
||||
// Generate a raw API key: "si_" prefix + 48 random bytes as hex
|
||||
const rawKey = `si_${randomBytes(48).toString("hex")}`;
|
||||
const keyHash = await hashPassword(rawKey);
|
||||
const id = randomUUID();
|
||||
|
||||
db.insert(schema.apiKeys)
|
||||
.values({
|
||||
id,
|
||||
userId: user.id,
|
||||
keyHash,
|
||||
name,
|
||||
})
|
||||
.run();
|
||||
|
||||
// Return the raw key ONCE — it cannot be retrieved again
|
||||
return reply.status(201).send({
|
||||
id,
|
||||
key: rawKey,
|
||||
name,
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// GET /api/v1/api-keys — List user's API keys (never returns the key itself)
|
||||
app.get(
|
||||
"/api/v1/api-keys",
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const user = requireAuth(request, reply);
|
||||
if (!user) return;
|
||||
|
||||
const keys = db
|
||||
.select({
|
||||
id: schema.apiKeys.id,
|
||||
name: schema.apiKeys.name,
|
||||
createdAt: schema.apiKeys.createdAt,
|
||||
lastUsedAt: schema.apiKeys.lastUsedAt,
|
||||
})
|
||||
.from(schema.apiKeys)
|
||||
.where(eq(schema.apiKeys.userId, user.id))
|
||||
.all();
|
||||
|
||||
return reply.send({
|
||||
apiKeys: keys.map((k) => ({
|
||||
id: k.id,
|
||||
name: k.name,
|
||||
createdAt: k.createdAt.toISOString(),
|
||||
lastUsedAt: k.lastUsedAt?.toISOString() ?? null,
|
||||
})),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// DELETE /api/v1/api-keys/:id — Delete an API key
|
||||
app.delete(
|
||||
"/api/v1/api-keys/:id",
|
||||
async (
|
||||
request: FastifyRequest<{ Params: { id: string } }>,
|
||||
reply: FastifyReply,
|
||||
) => {
|
||||
const user = requireAuth(request, reply);
|
||||
if (!user) return;
|
||||
|
||||
const { id } = request.params;
|
||||
|
||||
// Ensure the key belongs to the requesting user
|
||||
const existing = db
|
||||
.select()
|
||||
.from(schema.apiKeys)
|
||||
.where(and(eq(schema.apiKeys.id, id), eq(schema.apiKeys.userId, user.id)))
|
||||
.get();
|
||||
|
||||
if (!existing) {
|
||||
return reply.status(404).send({
|
||||
error: "API key not found",
|
||||
code: "NOT_FOUND",
|
||||
});
|
||||
}
|
||||
|
||||
db.delete(schema.apiKeys)
|
||||
.where(eq(schema.apiKeys.id, id))
|
||||
.run();
|
||||
|
||||
return reply.send({ ok: true });
|
||||
},
|
||||
);
|
||||
|
||||
app.log.info("API key routes registered");
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* Application settings routes (key-value store).
|
||||
*
|
||||
* GET /api/v1/settings — Get all settings as a key-value object
|
||||
* PUT /api/v1/settings — Save settings (admin only)
|
||||
* GET /api/v1/settings/:key — Get a specific setting
|
||||
*/
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from "fastify";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { db, schema } from "../db/index.js";
|
||||
import { requireAuth, requireAdmin } from "../plugins/auth.js";
|
||||
|
||||
export async function settingsRoutes(app: FastifyInstance): Promise<void> {
|
||||
// GET /api/v1/settings — Get all settings as a key-value object
|
||||
app.get(
|
||||
"/api/v1/settings",
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const user = requireAuth(request, reply);
|
||||
if (!user) return;
|
||||
|
||||
const rows = db.select().from(schema.settings).all();
|
||||
|
||||
const settings: Record<string, string> = {};
|
||||
for (const row of rows) {
|
||||
settings[row.key] = row.value;
|
||||
}
|
||||
|
||||
return reply.send({ settings });
|
||||
},
|
||||
);
|
||||
|
||||
// PUT /api/v1/settings — Save settings (admin only)
|
||||
app.put(
|
||||
"/api/v1/settings",
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
const body = request.body as Record<string, unknown> | null;
|
||||
|
||||
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
||||
return reply.status(400).send({
|
||||
error: "Request body must be a JSON object with key-value pairs",
|
||||
code: "VALIDATION_ERROR",
|
||||
});
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
let updatedCount = 0;
|
||||
|
||||
for (const [key, value] of Object.entries(body)) {
|
||||
if (typeof key !== "string" || key.length === 0) continue;
|
||||
|
||||
const strValue = typeof value === "string" ? value : JSON.stringify(value);
|
||||
|
||||
// Upsert: insert or update on conflict
|
||||
const existing = db
|
||||
.select()
|
||||
.from(schema.settings)
|
||||
.where(eq(schema.settings.key, key))
|
||||
.get();
|
||||
|
||||
if (existing) {
|
||||
db.update(schema.settings)
|
||||
.set({ value: strValue, updatedAt: now })
|
||||
.where(eq(schema.settings.key, key))
|
||||
.run();
|
||||
} else {
|
||||
db.insert(schema.settings)
|
||||
.values({ key, value: strValue })
|
||||
.run();
|
||||
}
|
||||
|
||||
updatedCount++;
|
||||
}
|
||||
|
||||
return reply.send({ ok: true, updatedCount });
|
||||
},
|
||||
);
|
||||
|
||||
// GET /api/v1/settings/:key — Get a specific setting
|
||||
app.get(
|
||||
"/api/v1/settings/:key",
|
||||
async (
|
||||
request: FastifyRequest<{ Params: { key: string } }>,
|
||||
reply: FastifyReply,
|
||||
) => {
|
||||
const user = requireAuth(request, reply);
|
||||
if (!user) return;
|
||||
|
||||
const { key } = request.params;
|
||||
|
||||
const row = db
|
||||
.select()
|
||||
.from(schema.settings)
|
||||
.where(eq(schema.settings.key, key))
|
||||
.get();
|
||||
|
||||
if (!row) {
|
||||
return reply.status(404).send({
|
||||
error: `Setting "${key}" not found`,
|
||||
code: "NOT_FOUND",
|
||||
});
|
||||
}
|
||||
|
||||
return reply.send({
|
||||
key: row.key,
|
||||
value: row.value,
|
||||
updatedAt: row.updatedAt.toISOString(),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
app.log.info("Settings routes registered");
|
||||
}
|
||||
@@ -9,7 +9,7 @@ const settingsSchema = z.object({
|
||||
cornerRadius: z.number().min(0).max(500).default(0),
|
||||
padding: z.number().min(0).max(200).default(0),
|
||||
shadowBlur: z.number().min(0).max(50).default(0),
|
||||
shadowColor: z.string().regex(/^#[0-9a-fA-F]{6}$/).default("#00000080"),
|
||||
shadowColor: z.string().regex(/^#[0-9a-fA-F]{6,8}$/).default("#00000080"),
|
||||
});
|
||||
|
||||
export function registerBorder(app: FastifyInstance) {
|
||||
|
||||
Reference in New Issue
Block a user