Files
SnapOtter/apps/api/src/index.ts
T
SnapOtterandGitHub 1c724d5d21 feat(db)!: SnapOtter 2.0 phase 1 foundation: postgres, migrator, compose stack (#216)
* feat(infra): add dev compose stack with postgres and redis

* fix(infra): comment dev env defaults until wired; harden dev compose restart and start_period

* chore(deps): add pg driver and testcontainers for postgres migration

* feat(db): translate schema to drizzle pg-core (timestamptz, boolean, pgEnum, jsonb)

Schema translation (apps/api/src/db/schema.ts):
- sqlite-core -> pg-core, all 10 tables preserved 1:1
- integer(mode:'timestamp') -> timestamp({ withTimezone: true })
- integer(mode:'boolean') -> boolean
- jobs.status text enum -> pgEnum('job_status') with same 4 values
- 7 columns changed from text to jsonb: jobs.inputFiles, jobs.settings,
  pipelines.steps, apiKeys.permissions, roles.permissions,
  auditLog.details, userFiles.toolChain
- settings.value stays text, jobs.error stays text, jobs.progress stays real

jsonb call-site sweep (removed JSON.stringify on writes, JSON.parse on reads):
- apps/api/src/routes/roles.ts: permissions read/write (3 sites)
- apps/api/src/routes/api-keys.ts: permissions write + read (2 sites)
- apps/api/src/routes/audit-log.ts: details read (1 site)
- apps/api/src/routes/pipeline.ts: steps write + read (2 sites)
- apps/api/src/routes/progress.ts: inputFiles write (2 sites)
- apps/api/src/routes/tool-factory.ts: toolChain read + write (2 sites)
- apps/api/src/routes/user-files.ts: toolChain read + write (4 sites)
- apps/api/src/permissions.ts: roles.permissions read (1 site)
- apps/api/src/lib/audit.ts: details write (1 site)
- apps/api/src/plugins/auth.ts: apiKeys.permissions read (1 site)

* refactor(db): type jsonb columns via $type and note raw CTE conversion requirements

* feat(db): archive sqlite migrations and generate postgres baseline

* chore(db): dockerignore legacy migrations, add archive breadcrumb, fix trailing newline

* feat(db): pg pool connection, advisory-locked boot migrations, DATABASE_URL config

* fix(db): friendly fatal on unreachable postgres, idempotent closeDb, lock-key convention note

* refactor(db): async drizzle calls in plugins, lib, permissions

* fix(api): analytics never throws, typed permission guard, single-query session invalidation

* refactor(db): async drizzle calls across all routes and bootstrap

Convert every route file and index.ts from sync SQLite drizzle
patterns to async node-postgres drizzle:

- .all() removed (bare await on select)
- .get() converted to destructured [row] = await ...
- .run() removed (bare await on insert/update/delete)
- .changes replaced with .rowCount (null-guarded) in progress.ts
- sqlite import removed from user-files.ts; raw CTEs converted to
  await db.execute(sql`...`) with postgres-dialect recursive CTEs
- ChainRow types updated: tool_chain is parsed jsonb (string[] | null),
  created_at is Date (timestamptz) with no * 1000 conversion
- All requirePermission() guard calls awaited (security: unawaited
  async guard returns truthy Promise, bypassing permission check)
- All hasEffectivePermission() and getPermissions() calls awaited
- All auditLog() calls awaited (preserves write-before-response order)
- trackEvent() and captureException() left un-awaited (fire-and-forget
  by design, guaranteed never-throw)
- ensureAnonymousUser(), startCleanupCron(), recoverStaleJobs() awaited
  in bootstrap sequence
- ensureInstanceId() and ensureDefaultSettings() made async

Files converted: 14 (index.ts + 12 route files + tools/index.ts)

* fix(db): await async checkStorageQuota in user-files upload/save routes

* fix(db): await checkStorageQuota in save-result route (missed second call site)

* feat(db): sqlite-to-postgres migrator with CLI and first-boot import

* fix(db): migrator error context, honest force semantics, boot-hook fatal, null-variance tests

* test: run suite against per-file postgres databases via testcontainers

- Add tests/global-setup.ts: spins up a Postgres testcontainer,
  creates a migrated template database once per vitest run.
- Rewrite tests/setup/per-fork-env.ts: each test file (forks pool)
  clones the template into its own database via CREATE DATABASE ...
  TEMPLATE, preserving the same per-file isolation granularity.
- Update vitest.config.ts: add globalSetup, pg alias, update comment.
- Fix tests/integration/test-server.ts: remove DB_PATH mkdir, async
  runMigrations, async db operations, remove SQLite WAL checkpoint.
- Fix 21 unit test db/index mocks: add pool and closeDb exports.
- Fix 8 unit test files: add async/await for now-async permission,
  audit, and analytics functions.
- Fix 18 integration test files: convert sync .run()/.all()/.get()
  to async drizzle patterns, add async to callbacks.
- Production change: apps/api/src/routes/teams.ts: cast COUNT(*)
  to ::int so Postgres returns a number instead of bigint string.

* fix(db): seed built-in roles, reject NUL bytes, cast COUNT, serialize job persists

- Seed built-in roles (admin, editor, user) at boot via ensureBuiltinRoles()
  with onConflictDoNothing, restoring data that legacy SQLite migration 0007
  provided via INSERT statements (the pg baseline is DDL-only).
- Reject NUL bytes in login credentials with 401 (postgres rejects \x00 in
  text columns; valid usernames never contain NUL, matching 1.x behavior).
- Cast COUNT(*)::int in user-files, audit-log, and roles listing queries so
  postgres returns a JS number instead of bigint-as-string.
- Serialize fire-and-forget job progress DB writes per jobId so the final
  "completed" status is never overwritten by a late-arriving "processing"
  write (race condition exposed by async postgres round-trips).

* test: fix teams race, seed roles in test server, poll for job status

- Add missing await to resetTeams() in teams PUT beforeEach (the async
  delete raced with the subsequent insert under postgres).
- Call ensureBuiltinRoles() in test server bootstrap so integration tests
  have the same built-in roles as production.
- Replace fixed 100ms flushPersist delay with a polling helper that waits
  for terminal job status, eliminating timing-dependent failures caused by
  postgres network round-trip latency.

* test: make heic temp-file cleanup assertion resilient to concurrent workers

Use a set-based diff instead of raw file count when checking that
decodeHeic cleans up temp files. Other concurrent test workers can
create heic-in-*/heic-out-* files in the shared tmpdir, inflating the
"after" count and causing spurious failures under full-suite load.

* fix(db): align builtin-role seed to post-0010 legacy state; test polish

* feat(docker): three-container compose (app, postgres, redis) with boot wait and migrations

* fix(docker): set TEST_DATABASE_URL so containerized tests skip testcontainers

* chore(docker): test compose project name, clearer 1.x upgrade comment, unref probe timer

* feat(enterprise): enforce D15 license boundary; move s3 storage into packages/enterprise

* fix(enterprise): restore lazy aws-sdk loading; community installs load no s3 code at boot

* fix(enterprise): boundary check catches dynamic imports; document getS3 concurrency

* feat(db)!: SnapOtter 2.0 phase 1 foundation: postgres, migrator, compose stack

BREAKING CHANGE: SQLite is no longer the runtime database. Deployments now
require Postgres (and Redis, used from phase 2). Existing installs migrate
with SQLITE_MIGRATE_PATH or 'pnpm --filter @snapotter/api migrate:sqlite'.

* fix(ci): postgres service + fresh e2e database per run; ignore unfixable torch CVE-2025-3000
2026-06-13 10:15:23 +08:00

461 lines
15 KiB
TypeScript

import { randomUUID } from "node:crypto";
import cookie from "@fastify/cookie";
import cors from "@fastify/cors";
import rateLimit from "@fastify/rate-limit";
import { getDispatcherStatus, initDispatcher, isGpuAvailable } from "@snapotter/ai";
import { APP_VERSION } from "@snapotter/shared";
import { eq, sql } from "drizzle-orm";
import Fastify from "fastify";
import { env } from "./config.js";
import { closeDb, db, schema } from "./db/index.js";
import { runMigrations } from "./db/migrate.js";
import { captureException, initAnalytics, shutdownAnalytics } from "./lib/analytics.js";
import { startCleanupCron } from "./lib/cleanup.js";
import { buildCsp } from "./lib/csp.js";
import { ensureAiDirs, recoverInterruptedInstalls } from "./lib/feature-status.js";
import { shutdownWorkerPool } from "./lib/worker-pool.js";
import { requirePermission } from "./permissions.js";
import {
authMiddleware,
authRoutes,
ensureAnonymousUser,
ensureBuiltinRoles,
ensureDefaultAdmin,
} from "./plugins/auth.js";
import { oidcRoutes } from "./plugins/oidc.js";
import { registerStatic } from "./plugins/static.js";
import { registerUpload } from "./plugins/upload.js";
import { analyticsRoutes } from "./routes/analytics.js";
import { apiKeyRoutes } from "./routes/api-keys.js";
import { auditLogRoutes } from "./routes/audit-log.js";
import { registerBatchRoutes } from "./routes/batch.js";
import { configRoutes } from "./routes/config.js";
import { docsRoutes } from "./routes/docs.js";
import { registerFeatureRoutes } from "./routes/features.js";
import { registerFetchUrlsRoute } from "./routes/fetch-urls.js";
import { fileRoutes } from "./routes/files.js";
import { registerMemeTemplates } from "./routes/meme-templates.js";
import { registerPipelineRoutes } from "./routes/pipeline.js";
import { recoverStaleJobs, registerProgressRoutes } from "./routes/progress.js";
import { rolesRoutes } from "./routes/roles.js";
import { settingsRoutes } from "./routes/settings.js";
import { teamsRoutes } from "./routes/teams.js";
import { registerToolRoutes } from "./routes/tools/index.js";
import { userFileRoutes } from "./routes/user-files.js";
// Run before anything else
try {
await runMigrations();
} catch (err) {
const safeUrl = env.DATABASE_URL.replace(/:\/\/[^@]*@/, "://***@");
console.error(
`FATAL: Cannot connect to Postgres at ${safeUrl}. Is the database running? (docker compose up, or set DATABASE_URL)`,
);
console.error(err);
process.exit(1);
}
console.log("Database initialized");
// Auto-import 1.x SQLite database on first boot (before default user creation)
if (env.SQLITE_MIGRATE_PATH) {
const { rows } = await db.execute(sql`SELECT count(*)::int AS n FROM users`);
if ((rows[0].n as number) === 0) {
try {
const { migrateFromSqlite } = await import("./db/migrate-from-sqlite.js");
const result = await migrateFromSqlite(env.SQLITE_MIGRATE_PATH, { force: false });
console.log("Imported 1.x SQLite database:", JSON.stringify(result.tables));
} catch (err) {
console.error(
`FATAL: 1.x SQLite import failed from ${env.SQLITE_MIGRATE_PATH}: ${(err as Error).message}. No partial data was written.`,
);
process.exit(1);
}
} else {
console.log("SQLITE_MIGRATE_PATH set but target is not empty; skipping import");
}
}
// Seed built-in roles (admin, editor, user) that legacy SQLite migrations
// inserted via data statements. The pg baseline is DDL-only, so roles are
// seeded here at boot time. onConflictDoNothing makes this idempotent.
await ensureBuiltinRoles();
if (env.AUTH_ENABLED) {
await ensureDefaultAdmin();
} else {
await ensureAnonymousUser();
}
async function ensureInstanceId() {
const [existing] = await db
.select()
.from(schema.settings)
.where(eq(schema.settings.key, "instance_id"));
if (!existing) {
await db.insert(schema.settings).values({ key: "instance_id", value: randomUUID() });
}
}
await ensureInstanceId();
async function ensureDefaultSettings() {
const defaults: Record<string, string> = {
defaultTheme: env.DEFAULT_THEME,
defaultLocale: env.DEFAULT_LOCALE,
defaultToolView: env.DEFAULT_TOOL_VIEW,
};
for (const [key, value] of Object.entries(defaults)) {
const [existing] = await db.select().from(schema.settings).where(eq(schema.settings.key, key));
if (!existing) {
await db.insert(schema.settings).values({ key, value });
}
}
}
await ensureDefaultSettings();
if (!env.COOKIE_SECRET) {
const [existing] = await db
.select()
.from(schema.settings)
.where(eq(schema.settings.key, "cookie_secret"));
if (existing) {
(env as Record<string, unknown>).COOKIE_SECRET = existing.value;
} else {
const generated = randomUUID() + randomUUID();
await db.insert(schema.settings).values({ key: "cookie_secret", value: generated });
(env as Record<string, unknown>).COOKIE_SECRET = generated;
}
}
await initAnalytics();
// Enterprise features (license-gated)
let enterpriseLicense: { org: string; plan: string } | null = null;
try {
const { initEnterprise } = await import("@snapotter/enterprise");
const result = initEnterprise(env.SNAPOTTER_LICENSE_KEY || undefined);
if (result.valid && result.license) {
enterpriseLicense = result.license;
} else if (env.SNAPOTTER_LICENSE_KEY) {
console.warn("[WARN] Invalid or expired enterprise license key");
}
} catch {
// Enterprise package not available
}
// Mark any jobs left in processing/queued from a previous unclean shutdown
await recoverStaleJobs();
// Set up AI feature directories and recover from interrupted installs
ensureAiDirs();
recoverInterruptedInstalls();
const app = Fastify({
logger: { level: env.LOG_LEVEL },
bodyLimit: env.MAX_UPLOAD_SIZE_MB > 0 ? env.MAX_UPLOAD_SIZE_MB * 1024 * 1024 : 1073741824,
trustProxy: env.TRUST_PROXY,
routerOptions: { maxParamLength: 500 },
});
// Image processing (especially AI batch) can run for tens of minutes.
// Node.js defaults to a 5-minute requestTimeout which kills long-running
// connections. Set a generous default; per-route overrides disable it entirely.
app.server.requestTimeout = 30 * 60 * 1000;
app.server.headersTimeout = 60 * 1000;
app.removeContentTypeParser("application/json");
app.addContentTypeParser("application/json", { parseAs: "string" }, (_request, body, done) => {
try {
const str = typeof body === "string" ? body : (body as Buffer).toString();
done(null, str.length > 0 ? JSON.parse(str) : {});
} catch {
const parseErr = new Error("Malformed JSON in request body") as Error & { statusCode: number };
parseErr.statusCode = 400;
done(parseErr, undefined);
}
});
app.setErrorHandler((error: Error & { statusCode?: number }, request, reply) => {
const statusCode = error.statusCode ?? 500;
if (statusCode === 429) {
request.log.warn({ url: request.url, method: request.method }, "Rate limit exceeded");
} else if (statusCode >= 500) {
request.log.error(
{ err: error, url: request.url, method: request.method },
"Unhandled request error",
);
captureException(error, request);
} else {
request.log.warn({ err: error, url: request.url, method: request.method }, "Request error");
}
reply.status(statusCode).send({
error: statusCode >= 500 ? "Internal server error" : error.message,
...(statusCode < 500 && { details: error.message }),
});
});
// Plugins
await app.register(cors, {
origin: env.CORS_ORIGIN
? env.CORS_ORIGIN.split(",").map((s) => s.trim())
: process.env.NODE_ENV !== "production",
});
// Security headers -- applied in all environments. HSTS is ignored over plain
// HTTP so it is safe (and desirable) to send it in dev/staging too. CSP catches
// injection issues early when applied during development.
app.addHook("onSend", async (_request, reply) => {
reply.header("X-Content-Type-Options", "nosniff");
reply.header("X-Frame-Options", "DENY");
reply.header("X-XSS-Protection", "0");
reply.header("Referrer-Policy", "strict-origin-when-cross-origin");
reply.header("Permissions-Policy", "camera=(), microphone=(), geolocation=()");
reply.header("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
reply.header("Content-Security-Policy", buildCsp(_request.url.startsWith("/api/docs")));
});
// Always register rate-limit plugin so per-route limits (login brute-force protection) work.
// max=0 means "unlimited" (50k/min) -- @fastify/rate-limit treats literal 0 as "block all".
await app.register(rateLimit, {
max: env.RATE_LIMIT_PER_MIN > 0 ? env.RATE_LIMIT_PER_MIN : 50_000,
timeWindow: "1 minute",
allowList: (request) => !request.url.startsWith("/api/"),
});
// Block TRACE method (returns 401 instead of 405 without this)
app.addHook("onRequest", async (request, reply) => {
if (request.method === "TRACE") {
return reply.status(405).send({ error: "Method not allowed" });
}
});
// Multipart upload support
await registerUpload(app);
// Cookie support (required for OIDC state and session cookies)
await app.register(cookie, {
secret: env.COOKIE_SECRET,
hook: "onRequest",
});
// Public config routes (no auth required)
await configRoutes(app);
// Auth middleware (must be registered before routes it protects)
await authMiddleware(app);
// Auth routes
await authRoutes(app);
// OIDC routes
await oidcRoutes(app);
// File upload/download routes
await fileRoutes(app);
// User file library routes (persistent file management with versioning)
await userFileRoutes(app);
// Meme template listing and static serving (before tool routes which have catch-all)
await registerMemeTemplates(app);
// Tool routes (generic factory-based)
await registerToolRoutes(app);
// Batch processing routes (must be after tool routes so the registry is populated)
await registerBatchRoutes(app);
// URL fetch routes (server-side image fetching with SSRF protection)
await registerFetchUrlsRoute(app);
// Pipeline routes (must be after tool routes so the registry is populated)
await registerPipelineRoutes(app);
// Progress SSE routes
await registerProgressRoutes(app);
// API key management routes
await apiKeyRoutes(app);
// Settings routes
await settingsRoutes(app);
// Analytics config and consent routes
await analyticsRoutes(app);
// Feature management routes (AI feature bundle install/uninstall)
await registerFeatureRoutes(app);
// Teams routes
await teamsRoutes(app);
// Audit log routes
await auditLogRoutes(app);
// Roles management routes
await rolesRoutes(app);
// API docs (Scalar)
await docsRoutes(app);
// Public health check (checks core dependencies)
app.get("/api/v1/health", async (_request, reply) => {
let dbOk = false;
try {
await db.select().from(schema.settings).limit(1);
dbOk = true;
} catch {
/* db unreachable */
}
const status = dbOk ? "healthy" : "unhealthy";
const code = dbOk ? 200 : 503;
return reply.code(code).send({
status,
version: APP_VERSION,
});
});
// Admin health check (full diagnostics)
app.get("/api/v1/admin/health", async (request, reply) => {
const admin = await requirePermission("system:health")(request, reply);
if (!admin) return;
let dbOk = false;
try {
await db.select().from(schema.settings).limit(1);
dbOk = true;
} catch {
/* db unreachable */
}
return {
status: dbOk ? "healthy" : "degraded",
version: APP_VERSION,
uptime: `${process.uptime().toFixed(0)}s`,
storage: { mode: env.STORAGE_MODE, available: "N/A" },
database: dbOk ? "ok" : "error",
queue: { active: 0, pending: 0 },
ai: { gpu: isGpuAvailable(), dispatcher: getDispatcherStatus() },
enterprise: enterpriseLicense
? { active: true, org: enterpriseLicense.org, plan: enterpriseLicense.plan }
: { active: false },
};
});
// Public config endpoint (for frontend to know if auth is required)
app.get("/api/v1/config/auth", async () => {
const config: Record<string, unknown> = {
authEnabled: env.AUTH_ENABLED,
};
if (env.OIDC_ENABLED) {
config.oidcEnabled = true;
config.oidcProviderName = env.OIDC_PROVIDER_NAME || null;
config.oidcLoginUrl = "/api/auth/oidc/login";
}
return config;
});
// Serve SPA in production
if (process.env.NODE_ENV === "production") {
await registerStatic(app);
}
// Start workspace cleanup cron
const cleanupCron = await startCleanupCron();
// Start
try {
await app.listen({ port: env.PORT, host: "0.0.0.0" });
const dispatcherResult = await initDispatcher();
const gpuLine = dispatcherResult.ready
? dispatcherResult.gpu
? "[INFO] GPU detected -- AI tools will use CUDA acceleration"
: "[WARN] No GPU detected -- AI tools will use CPU (slower)"
: "[WARN] AI sidecar did not start -- AI tools will use per-request Python (slower)";
console.log(
[
`SnapOtter v${APP_VERSION} running on port ${env.PORT}`,
gpuLine,
`[INFO] Rate limit: ${env.RATE_LIMIT_PER_MIN > 0 ? `${env.RATE_LIMIT_PER_MIN}/min` : "disabled"}`,
`[INFO] Upload limit: ${env.MAX_UPLOAD_SIZE_MB > 0 ? `${env.MAX_UPLOAD_SIZE_MB} MB` : "unlimited"}`,
`[INFO] Trust proxy: ${env.TRUST_PROXY}`,
`[INFO] Storage: ${env.STORAGE_MODE}${env.STORAGE_MODE === "s3" ? ` (${env.S3_BUCKET})` : ""}`,
enterpriseLicense
? `[INFO] Enterprise license: ${enterpriseLicense.org} (${enterpriseLicense.plan})`
: "[INFO] Edition: Community",
].join("\n"),
);
} catch (err) {
app.log.error(err);
process.exit(1);
}
// Graceful shutdown
const SHUTDOWN_TIMEOUT_MS = 30000;
let shuttingDown = false;
async function shutdown(signal: string) {
if (shuttingDown) return;
shuttingDown = true;
console.log(`\n${signal} received, shutting down gracefully...`);
const forceExit = setTimeout(() => {
console.error("Shutdown timed out, forcing exit");
process.exit(1);
}, SHUTDOWN_TIMEOUT_MS);
forceExit.unref();
cleanupCron.stop();
try {
await app.close();
console.log("HTTP server closed");
} catch (err) {
console.error("Error closing HTTP server:", err);
}
try {
await shutdownWorkerPool();
console.log("Worker pool shut down");
} catch (err) {
console.error("Error shutting down worker pool:", err);
}
try {
const { shutdownDispatcher } = await import("@snapotter/ai");
shutdownDispatcher();
console.log("Python dispatcher shut down");
} catch {
// AI package may not be available
}
try {
const { shutdownBrowser } = await import("./lib/browser-service.js");
await shutdownBrowser();
console.log("Browser service shut down");
} catch {
// Browser service may not have been initialized
}
try {
await shutdownAnalytics();
console.log("Analytics flushed");
} catch {
// analytics shutdown is best-effort
}
try {
await closeDb();
console.log("Database connection closed");
} catch (err) {
console.error("Error closing database:", err);
}
clearTimeout(forceExit);
process.exit(0);
}
process.on("SIGTERM", () => shutdown("SIGTERM"));
process.on("SIGINT", () => shutdown("SIGINT"));