feat: API sync and documentation audit - 100% endpoint coverage (#94)

Code quality:
- Add Zod validation to 14 route handlers that used raw JSON.parse
  (favicon, find-duplicates, barcode-read, upscale, blur-faces,
  erase-object, colorize, enhance-faces, red-eye-removal,
  remove-background/effects, auth, api-keys, roles, teams,
  analytics, settings, user-files)
- Standardize error responses to safeParse + formatZodErrors pattern
- Replace unsafe `as` type casts with schema validation

OpenAPI spec (89 -> 115 operations):
- Add 14 missing tool endpoints (adjust-colors, sharpening,
  optimize-for-web, image-enhancement, noise-removal, red-eye-removal,
  restore-photo, passport-photo, colorize, enhance-faces, image-to-base64)
- Add 12 missing non-tool endpoints (analytics, features, audit-log,
  roles, admin-health)
- Add typed error schemas for 401/403/409 responses
- Add descriptions to all path parameters
- Bump version from 0.9.0 to 1.15.9

Documentation:
- Fix 8 incorrect env var defaults in configuration guide
- Add 15 undocumented env vars to configuration guide
- Fix tool ID mismatch (color-adjustments -> adjust-colors)
- Add 4 new API sections (Roles, Audit Log, Analytics, Features)
- Add image-enhancement to AI engine reference
- Update AI tool count from 13 to 14 across all docs
- Add 6 missing doc links to README
This commit is contained in:
Ashim
2026-04-23 20:26:58 +08:00
committed by GitHub
parent 136a4dd641
commit 97938bdc47
28 changed files with 2814 additions and 191 deletions
+2200 -2
View File
File diff suppressed because it is too large Load Diff
+63 -32
View File
@@ -2,6 +2,7 @@ import { createHash, randomBytes, randomUUID, scrypt, timingSafeEqual } from "no
import { promisify } from "node:util";
import { eq, sql } from "drizzle-orm";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod";
import { env } from "../config.js";
import { db, schema } from "../db/index.js";
import { auditLog } from "../lib/audit.js";
@@ -69,6 +70,34 @@ function validateUsername(username: string): string | null {
return null;
}
// ── Zod schemas for auth request bodies ──────────────────────────
const loginSchema = z.object({
username: z.string().min(1, "Username is required"),
password: z.string().min(1, "Password is required"),
});
const changePasswordSchema = z.object({
currentPassword: z.string().min(1, "Current password is required"),
newPassword: z.string().min(1, "New password is required"),
});
const registerSchema = z.object({
username: z.string().min(1, "Username is required"),
password: z.string().min(1, "Password is required"),
role: z.string().optional(),
team: z.string().optional(),
});
const updateUserSchema = z.object({
role: z.string().optional(),
team: z.string().optional(),
});
const resetPasswordSchema = z.object({
newPassword: z.string().min(1, "New password is required"),
});
// ── Request helpers ───────────────────────────────────────────────
/** Extract the authenticated user attached by authMiddleware. */
@@ -164,11 +193,11 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
return reply.status(403).send({ error: "Authentication is disabled" });
}
const body = request.body as { username?: string; password?: string } | null;
if (!body?.username || !body?.password) {
const parsed = loginSchema.safeParse(request.body);
if (!parsed.success) {
return reply.status(400).send({ error: "Username and password are required" });
}
const body = parsed.data;
const user = db
.select()
@@ -290,17 +319,14 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
const authUser = requireAuth(request, reply);
if (!authUser) return;
const body = request.body as {
currentPassword?: string;
newPassword?: string;
} | null;
if (!body?.currentPassword || !body?.newPassword) {
const parsed = changePasswordSchema.safeParse(request.body);
if (!parsed.success) {
return reply.status(400).send({
error: "Current password and new password are required",
code: "VALIDATION_ERROR",
});
}
const body = parsed.data;
const pwError = validatePasswordStrength(body.newPassword);
if (pwError) {
@@ -386,18 +412,14 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
const admin = requirePermission("users:manage")(request, reply);
if (!admin) return;
const body = request.body as {
username?: string;
password?: string;
role?: string;
} | null;
if (!body?.username || !body?.password) {
const parsed = registerSchema.safeParse(request.body);
if (!parsed.success) {
return reply.status(400).send({
error: "Username and password are required",
code: "VALIDATION_ERROR",
});
}
const body = parsed.data;
const usernameError = validateUsername(body.username);
if (usernameError) {
@@ -443,8 +465,8 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
});
}
// Resolve team frontend sends team name (e.g. "Default"), not ID
const requestedTeam = (body as { team?: string }).team;
// Resolve team -- frontend sends team name (e.g. "Default"), not ID
const requestedTeam = body.team;
let teamId: string;
let teamName: string;
@@ -487,13 +509,15 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
});
}
// Check user limit
const userCount = db.select().from(schema.users).all().length;
if (userCount >= MAX_USERS) {
return reply.status(403).send({
error: `User limit reached (${MAX_USERS} max)`,
code: "USER_LIMIT_REACHED",
});
// Check user limit (0 = unlimited)
if (MAX_USERS > 0) {
const userCount = db.select().from(schema.users).all().length;
if (userCount >= MAX_USERS) {
return reply.status(403).send({
error: `User limit reached (${MAX_USERS} max)`,
code: "USER_LIMIT_REACHED",
});
}
}
const id = randomUUID();
@@ -533,7 +557,14 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
if (!admin) return;
const { id } = request.params;
const body = request.body as { role?: string; team?: string } | null;
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;
const user = db.select().from(schema.users).where(eq(schema.users.id, id)).get();
@@ -546,7 +577,7 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
};
// Escalation prevention
if (body?.role) {
if (body.role) {
const roleHierarchy: Record<string, number> = { admin: 3, editor: 2, user: 1 };
const actorLevel = roleHierarchy[admin.role] ?? 0;
const targetLevel = roleHierarchy[body.role] ?? 0;
@@ -558,7 +589,7 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
}
}
if (body?.role) {
if (body.role) {
const validBuiltinRoles = ["admin", "editor", "user"];
const isValid =
validBuiltinRoles.includes(body.role) ||
@@ -591,7 +622,7 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
}
}
if (typeof body?.team === "string" && body.team.trim()) {
if (body.team?.trim()) {
// Look up by name first, then fall back to ID
const teamByName = db
.select()
@@ -628,14 +659,14 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
if (!admin) return;
const { id } = request.params;
const body = request.body as { newPassword?: string } | null;
if (!body?.newPassword) {
const parsed = resetPasswordSchema.safeParse(request.body);
if (!parsed.success) {
return reply.status(400).send({
error: "New password is required",
code: "VALIDATION_ERROR",
});
}
const body = parsed.data;
const pwError = validatePasswordStrength(body.newPassword);
if (pwError) {
+16 -6
View File
@@ -1,9 +1,15 @@
import { eq } from "drizzle-orm";
import type { FastifyInstance } from "fastify";
import { z } from "zod";
import { env } from "../config.js";
import { db, schema } from "../db/index.js";
import { requireAuth } from "../plugins/auth.js";
const analyticsConsentSchema = z.object({
enabled: z.boolean().optional(),
remindLater: z.boolean().optional(),
});
export async function analyticsRoutes(app: FastifyInstance): Promise<void> {
app.get("/api/v1/config/analytics", async () => {
if (!env.ANALYTICS_ENABLED) {
@@ -37,14 +43,18 @@ export async function analyticsRoutes(app: FastifyInstance): Promise<void> {
const user = requireAuth(request, reply);
if (!user) return;
const body = request.body as {
enabled?: boolean;
remindLater?: boolean;
} | null;
const parsed = analyticsConsentSchema.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;
const now = new Date();
if (body?.remindLater) {
if (body.remindLater) {
const remindAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
db.update(schema.users)
.set({
@@ -58,7 +68,7 @@ export async function analyticsRoutes(app: FastifyInstance): Promise<void> {
return reply.send({ ok: true, analyticsEnabled: null });
}
const enabled = body?.enabled === true;
const enabled = body.enabled === true;
db.update(schema.users)
.set({
analyticsEnabled: enabled,
+19 -16
View File
@@ -8,36 +8,39 @@
import { randomBytes, randomUUID } from "node:crypto";
import { and, eq } from "drizzle-orm";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod";
import { db, schema } from "../db/index.js";
import { auditLog } from "../lib/audit.js";
import { getPermissions, hasEffectivePermission } from "../permissions.js";
import { computeKeyPrefix, hashPassword, requireAuth } from "../plugins/auth.js";
const createApiKeySchema = z.object({
name: z.string().max(100, "Key name must be 100 characters or fewer").optional(),
permissions: z.array(z.string()).optional(),
expiresAt: z.string().optional(),
});
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;
permissions?: string[];
expiresAt?: string;
} | null;
const name = body?.name?.trim() || "Default API Key";
if (name.length > 100) {
const parsed = createApiKeySchema.safeParse(request.body ?? {});
if (!parsed.success) {
return reply.status(400).send({
error: "Key name must be 100 characters or fewer",
error: parsed.error.issues.map((i) => i.message).join("; "),
code: "VALIDATION_ERROR",
});
}
const body = parsed.data;
const name = body.name?.trim() || "Default API Key";
let scopedPermissions: string[] | null = null;
if (Array.isArray(body?.permissions) && body.permissions.length > 0) {
if (body.permissions && body.permissions.length > 0) {
const userPerms = getPermissions(user.role);
const permSet = new Set<string>(userPerms);
const invalid = body.permissions.filter((p: string) => !permSet.has(p));
const invalid = body.permissions.filter((p) => !permSet.has(p));
if (invalid.length > 0) {
return reply.status(400).send({
error: `Cannot scope key with permissions you don't have: ${invalid.join(", ")}`,
@@ -48,19 +51,19 @@ export async function apiKeyRoutes(app: FastifyInstance): Promise<void> {
}
let expiresAt: Date | null = null;
if (body?.expiresAt) {
const parsed = new Date(body.expiresAt);
if (Number.isNaN(parsed.getTime())) {
if (body.expiresAt) {
const parsedDate = new Date(body.expiresAt);
if (Number.isNaN(parsedDate.getTime())) {
return reply
.status(400)
.send({ error: "Invalid expiresAt date", code: "VALIDATION_ERROR" });
}
if (parsed <= new Date()) {
if (parsedDate <= new Date()) {
return reply
.status(400)
.send({ error: "expiresAt must be in the future", code: "VALIDATION_ERROR" });
}
expiresAt = parsed;
expiresAt = parsedDate;
}
// Generate a raw API key: "si_" prefix + 48 random bytes as hex
+53 -41
View File
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
import type { Permission } from "@ashim/shared";
import { eq, sql } from "drizzle-orm";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod";
import { db, schema } from "../db/index.js";
import { auditLog } from "../lib/audit.js";
import { requirePermission } from "../permissions.js";
@@ -24,6 +25,32 @@ const ALL_PERMISSIONS: Permission[] = [
"audit:read",
];
const roleNameField = z
.string()
.transform((v) => v.trim().toLowerCase())
.pipe(
z
.string()
.min(2, "Role name must be 2-30 characters")
.max(30, "Role name must be 2-30 characters")
.regex(
/^[a-z0-9_-]+$/,
"Role name can only contain lowercase letters, numbers, hyphens, and underscores",
),
);
const createRoleSchema = z.object({
name: roleNameField,
description: z.string().max(500).optional(),
permissions: z.array(z.string()).min(1, "At least one permission is required"),
});
const updateRoleSchema = z.object({
name: roleNameField.optional(),
description: z.string().max(500).optional(),
permissions: z.array(z.string()).optional(),
});
export async function rolesRoutes(app: FastifyInstance): Promise<void> {
// GET /api/v1/roles — List all roles (requires audit:read to view)
app.get("/api/v1/roles", async (request: FastifyRequest, reply: FastifyReply) => {
@@ -60,31 +87,16 @@ export async function rolesRoutes(app: FastifyInstance): Promise<void> {
const user = requirePermission("users:manage")(request, reply);
if (!user) return;
const body = request.body as {
name?: string;
description?: string;
permissions?: string[];
} | null;
if (!body?.name || !Array.isArray(body?.permissions)) {
return reply
.status(400)
.send({ error: "Name and permissions are required", code: "VALIDATION_ERROR" });
}
const name = body.name.trim().toLowerCase();
if (name.length < 2 || name.length > 30) {
return reply
.status(400)
.send({ error: "Role name must be 2-30 characters", code: "VALIDATION_ERROR" });
}
if (!/^[a-z0-9_-]+$/.test(name)) {
const parsed = createRoleSchema.safeParse(request.body);
if (!parsed.success) {
return reply.status(400).send({
error: "Role name can only contain lowercase letters, numbers, hyphens, and underscores",
error: parsed.error.issues.map((i) => i.message).join("; "),
code: "VALIDATION_ERROR",
});
}
const { name, description, permissions } = parsed.data;
const invalid = body.permissions.filter((p) => !ALL_PERMISSIONS.includes(p as Permission));
const invalid = permissions.filter((p) => !ALL_PERMISSIONS.includes(p as Permission));
if (invalid.length > 0) {
return reply
.status(400)
@@ -101,8 +113,8 @@ export async function rolesRoutes(app: FastifyInstance): Promise<void> {
.values({
id,
name,
description: body.description?.trim() ?? "",
permissions: JSON.stringify(body.permissions),
description: description?.trim() ?? "",
permissions: JSON.stringify(permissions),
isBuiltin: false,
createdBy: user.id,
})
@@ -113,8 +125,8 @@ export async function rolesRoutes(app: FastifyInstance): Promise<void> {
return reply.status(201).send({
id,
name,
description: body.description?.trim() ?? "",
permissions: body.permissions,
description: description?.trim() ?? "",
permissions,
isBuiltin: false,
});
});
@@ -137,32 +149,32 @@ export async function rolesRoutes(app: FastifyInstance): Promise<void> {
.send({ error: "Cannot modify built-in roles", code: "VALIDATION_ERROR" });
}
const body = request.body as {
name?: string;
description?: string;
permissions?: string[];
} | null;
const parsed = updateRoleSchema.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;
const updates: Record<string, unknown> = { updatedAt: new Date() };
if (body?.name) {
const name = body.name.trim().toLowerCase();
if (name.length < 2 || name.length > 30) {
return reply
.status(400)
.send({ error: "Role name must be 2-30 characters", code: "VALIDATION_ERROR" });
}
const dup = db.select().from(schema.roles).where(eq(schema.roles.name, name)).get();
if (body.name) {
const dup = db.select().from(schema.roles).where(eq(schema.roles.name, body.name)).get();
if (dup && dup.id !== id) {
return reply.status(409).send({ error: "Role name already exists", code: "CONFLICT" });
}
// Update users on old role name to new name
db.update(schema.users).set({ role: name }).where(eq(schema.users.role, role.name)).run();
updates.name = name;
db.update(schema.users)
.set({ role: body.name })
.where(eq(schema.users.role, role.name))
.run();
updates.name = body.name;
}
if (body?.description !== undefined) {
if (body.description !== undefined) {
updates.description = body.description.trim();
}
if (Array.isArray(body?.permissions)) {
if (body.permissions) {
const invalid = body.permissions.filter((p) => !ALL_PERMISSIONS.includes(p as Permission));
if (invalid.length > 0) {
return reply.status(400).send({
+6 -3
View File
@@ -8,10 +8,13 @@
import { eq } from "drizzle-orm";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod";
import { db, schema } from "../db/index.js";
import { requirePermission } from "../permissions.js";
import { requireAuth } from "../plugins/auth.js";
const settingsBodySchema = z.record(z.string().min(1), z.unknown());
const HTML_TAG_PATTERN = /<[a-z/!][^>]*>/i;
export async function settingsRoutes(app: FastifyInstance): Promise<void> {
@@ -35,14 +38,14 @@ export async function settingsRoutes(app: FastifyInstance): Promise<void> {
const admin = requirePermission("settings:write")(request, reply);
if (!admin) return;
const body = request.body as Record<string, unknown> | null;
if (!body || typeof body !== "object" || Array.isArray(body)) {
const parsed = settingsBodySchema.safeParse(request.body);
if (!parsed.success) {
return reply.status(400).send({
error: "Request body must be a JSON object with key-value pairs",
code: "VALIDATION_ERROR",
});
}
const body = parsed.data;
// Pass 1: validate all entries before writing any
const entries: Array<{ key: string; strValue: string }> = [];
+26 -20
View File
@@ -10,16 +10,21 @@
import { randomUUID } from "node:crypto";
import { eq, sql } from "drizzle-orm";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod";
import { db, schema } from "../db/index.js";
import { requirePermission } from "../permissions.js";
function validateTeamName(name: unknown): string | null {
if (typeof name !== "string") return "Team name is required";
const trimmed = name.trim();
if (trimmed.length === 0) return "Team name is required";
if (trimmed.length > 50) return "Team name must be 50 characters or fewer";
return null;
}
const teamNameSchema = z.object({
name: z
.string({ required_error: "Team name is required" })
.transform((v) => v.trim())
.pipe(
z
.string()
.min(1, "Team name is required")
.max(50, "Team name must be 50 characters or fewer"),
),
});
export async function teamsRoutes(app: FastifyInstance): Promise<void> {
// GET /api/v1/teams — List all teams with member count (admin only)
@@ -50,14 +55,14 @@ export async function teamsRoutes(app: FastifyInstance): Promise<void> {
const admin = requirePermission("teams:manage")(request, reply);
if (!admin) return;
const body = request.body as { name?: string } | null;
const nameError = validateTeamName(body?.name);
if (nameError) {
return reply.status(400).send({ error: nameError, code: "VALIDATION_ERROR" });
const parsed = teamNameSchema.safeParse(request.body);
if (!parsed.success) {
return reply.status(400).send({
error: parsed.error.issues.map((i) => i.message).join("; "),
code: "VALIDATION_ERROR",
});
}
const trimmedName = (body?.name ?? "").trim();
const trimmedName = parsed.data.name;
// Check for duplicate name (case-insensitive)
const existing = db
@@ -85,19 +90,20 @@ export async function teamsRoutes(app: FastifyInstance): Promise<void> {
if (!admin) return;
const { id } = request.params;
const body = request.body as { name?: string } | null;
const team = db.select().from(schema.teams).where(eq(schema.teams.id, id)).get();
if (!team) {
return reply.status(404).send({ error: "Team not found", code: "NOT_FOUND" });
}
const nameError = validateTeamName(body?.name);
if (nameError) {
return reply.status(400).send({ error: nameError, code: "VALIDATION_ERROR" });
const parsed = teamNameSchema.safeParse(request.body);
if (!parsed.success) {
return reply.status(400).send({
error: parsed.error.issues.map((i) => i.message).join("; "),
code: "VALIDATION_ERROR",
});
}
const trimmedName = (body?.name ?? "").trim();
const trimmedName = parsed.data.name;
// Check for duplicate name (case-insensitive), excluding current team
const duplicate = db
+22 -2
View File
@@ -3,12 +3,18 @@ import { writeFile } from "node:fs/promises";
import { basename, join } from "node:path";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import sharp from "sharp";
import { z } from "zod";
import { readBarcodes } from "zxing-wasm/reader";
import { autoOrient } from "../../lib/auto-orient.js";
import { formatZodErrors } from "../../lib/errors.js";
import { validateImageBuffer } from "../../lib/file-validation.js";
import { ensureSharpCompat } from "../../lib/heic-converter.js";
import { createWorkspace } from "../../lib/workspace.js";
const settingsSchema = z.object({
tryHarder: z.boolean().default(true),
});
/**
* Color palette for bounding-box overlays.
* Semi-transparent fills paired with solid strokes.
@@ -111,9 +117,23 @@ export function registerBarcodeRead(app: FastifyInstance) {
});
}
// Parse and validate settings
let settings: z.infer<typeof settingsSchema>;
try {
const settings = settingsRaw ? JSON.parse(settingsRaw) : {};
const tryHarder = settings.tryHarder !== false; // default true
const parsed = settingsRaw ? JSON.parse(settingsRaw) : {};
const result = settingsSchema.safeParse(parsed);
if (!result.success) {
return reply
.status(400)
.send({ error: "Invalid settings", details: formatZodErrors(result.error.issues) });
}
settings = result.data;
} catch {
return reply.status(400).send({ error: "Settings must be valid JSON" });
}
try {
const tryHarder = settings.tryHarder;
// Decode HEIC/HEIF if needed, then auto-orient
fileBuffer = await ensureSharpCompat(fileBuffer);
+24 -5
View File
@@ -6,6 +6,7 @@ import { getBundleForTool, TOOL_BUNDLE_MAP } from "@ashim/shared";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod";
import { autoOrient } from "../../lib/auto-orient.js";
import { formatZodErrors } from "../../lib/errors.js";
import { isToolInstalled } from "../../lib/feature-status.js";
import { validateImageBuffer } from "../../lib/file-validation.js";
import { decodeToSharpCompat, needsCliDecode } from "../../lib/format-decoders.js";
@@ -14,6 +15,11 @@ import { createWorkspace } from "../../lib/workspace.js";
import { updateSingleFileProgress } from "../progress.js";
import { registerToolProcessFn } from "../tool-factory.js";
const settingsSchema = z.object({
blurRadius: z.number().min(1).max(100).default(30),
sensitivity: z.number().min(0).max(1).default(0.5),
});
/** Face detection and blurring route. */
export function registerBlurFaces(app: FastifyInstance) {
app.post("/api/v1/tools/blur-faces", async (request: FastifyRequest, reply: FastifyReply) => {
@@ -67,7 +73,19 @@ export function registerBlurFaces(app: FastifyInstance) {
}
try {
const settings = settingsRaw ? JSON.parse(settingsRaw) : {};
let settings: z.infer<typeof settingsSchema>;
try {
const parsed = settingsRaw ? JSON.parse(settingsRaw) : {};
const result = settingsSchema.safeParse(parsed);
if (!result.success) {
return reply
.status(400)
.send({ error: "Invalid settings", details: formatZodErrors(result.error.issues) });
}
settings = result.data;
} catch {
return reply.status(400).send({ error: "Settings must be valid JSON" });
}
if (validation.format === "heif") {
fileBuffer = await decodeHeic(fileBuffer);
@@ -78,12 +96,13 @@ export function registerBlurFaces(app: FastifyInstance) {
fileBuffer = await decodeToSharpCompat(fileBuffer, validation.format);
}
const { blurRadius, sensitivity } = settings;
request.log.info(
{
toolId: "blur-faces",
imageSize: fileBuffer.length,
blurRadius: settings.blurRadius,
sensitivity: settings.sensitivity,
blurRadius,
sensitivity,
},
"Starting face blur",
);
@@ -114,8 +133,8 @@ export function registerBlurFaces(app: FastifyInstance) {
fileBuffer,
join(workspacePath, "output"),
{
blurRadius: settings.blurRadius ?? 30,
sensitivity: settings.sensitivity ?? 0.5,
blurRadius,
sensitivity,
},
onProgress,
);
+21 -3
View File
@@ -7,6 +7,7 @@ import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import sharp from "sharp";
import { z } from "zod";
import { autoOrient } from "../../lib/auto-orient.js";
import { formatZodErrors } from "../../lib/errors.js";
import { isToolInstalled } from "../../lib/feature-status.js";
import { validateImageBuffer } from "../../lib/file-validation.js";
import { decodeToSharpCompat, needsCliDecode } from "../../lib/format-decoders.js";
@@ -16,6 +17,11 @@ import { createWorkspace } from "../../lib/workspace.js";
import { updateSingleFileProgress } from "../progress.js";
import { registerToolProcessFn } from "../tool-factory.js";
const settingsSchema = z.object({
intensity: z.number().min(0).max(1).default(1.0),
model: z.enum(["auto", "ddcolor", "opencv"]).default("auto"),
});
/**
* AI photo colorization route.
* Converts B&W / grayscale photos to full color using DDColor,
@@ -73,9 +79,21 @@ export function registerColorize(app: FastifyInstance) {
}
try {
const settings = settingsRaw ? JSON.parse(settingsRaw) : {};
const intensity = Math.min(1, Math.max(0, Number(settings.intensity) || 1.0));
const model = settings.model || "auto";
let settings: z.infer<typeof settingsSchema>;
try {
const parsed = settingsRaw ? JSON.parse(settingsRaw) : {};
const result = settingsSchema.safeParse(parsed);
if (!result.success) {
return reply
.status(400)
.send({ error: "Invalid settings", details: formatZodErrors(result.error.issues) });
}
settings = result.data;
} catch {
return reply.status(400).send({ error: "Settings must be valid JSON" });
}
const { intensity, model } = settings;
request.log.info(
{ toolId: "colorize", imageSize: fileBuffer.length, intensity, model },
+23 -5
View File
@@ -7,6 +7,7 @@ import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import sharp from "sharp";
import { z } from "zod";
import { autoOrient } from "../../lib/auto-orient.js";
import { formatZodErrors } from "../../lib/errors.js";
import { isToolInstalled } from "../../lib/feature-status.js";
import { validateImageBuffer } from "../../lib/file-validation.js";
import { decodeToSharpCompat, needsCliDecode } from "../../lib/format-decoders.js";
@@ -15,6 +16,13 @@ import { createWorkspace } from "../../lib/workspace.js";
import { updateSingleFileProgress } from "../progress.js";
import { registerToolProcessFn } from "../tool-factory.js";
const settingsSchema = z.object({
model: z.enum(["auto", "gfpgan", "codeformer"]).default("auto"),
strength: z.number().min(0).max(1).default(0.8),
onlyCenterFace: z.boolean().default(false),
sensitivity: z.number().min(0).max(1).default(0.5),
});
/** Face enhancement route using GFPGAN/CodeFormer. */
export function registerEnhanceFaces(app: FastifyInstance) {
app.post("/api/v1/tools/enhance-faces", async (request: FastifyRequest, reply: FastifyReply) => {
@@ -68,11 +76,21 @@ export function registerEnhanceFaces(app: FastifyInstance) {
}
try {
const settings = settingsRaw ? JSON.parse(settingsRaw) : {};
const model = settings.model || "auto";
const strength = Number(settings.strength) || 0.8;
const onlyCenterFace = Boolean(settings.onlyCenterFace);
const sensitivity = Number(settings.sensitivity) || 0.5;
let settings: z.infer<typeof settingsSchema>;
try {
const parsed = settingsRaw ? JSON.parse(settingsRaw) : {};
const result = settingsSchema.safeParse(parsed);
if (!result.success) {
return reply
.status(400)
.send({ error: "Invalid settings", details: formatZodErrors(result.error.issues) });
}
settings = result.data;
} catch {
return reply.status(400).send({ error: "Settings must be valid JSON" });
}
const { model, strength, onlyCenterFace, sensitivity } = settings;
request.log.info(
{ toolId: "enhance-faces", imageSize: fileBuffer.length, model, strength },
"Starting face enhancement",
+21
View File
@@ -5,6 +5,7 @@ import { inpaint } from "@ashim/ai";
import { getBundleForTool, TOOL_BUNDLE_MAP } from "@ashim/shared";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import sharp from "sharp";
import { z } from "zod";
import { autoOrient } from "../../lib/auto-orient.js";
import { isToolInstalled } from "../../lib/feature-status.js";
import { validateImageBuffer } from "../../lib/file-validation.js";
@@ -27,6 +28,13 @@ const EXT_MAP: Record<string, string> = {
const BROWSER_PREVIEWABLE = new Set(["png", "jpg", "jpeg", "webp", "gif", "avif", "bmp"]);
const settingsSchema = z.object({
format: z
.enum(["png", "jpg", "jpeg", "webp", "tiff", "gif", "avif", "heic", "heif"])
.default("png"),
quality: z.number().int().min(1).max(100).default(95),
});
/**
* Object eraser / inpainting route.
* Accepts an image and a mask image, erases masked areas using LaMa.
@@ -101,6 +109,19 @@ export function registerEraseObject(app: FastifyInstance) {
}
try {
// Validate format and quality via Zod
const settingsResult = settingsSchema.safeParse({ format, quality });
if (!settingsResult.success) {
return reply.status(400).send({
error: "Invalid settings",
details: settingsResult.error.issues
.map((i) => (i.path.length > 0 ? `${i.path.join(".")}: ${i.message}` : i.message))
.join("; "),
});
}
format = settingsResult.data.format;
quality = settingsResult.data.quality;
request.log.info(
{
toolId: "erase-object",
+32
View File
@@ -3,9 +3,14 @@ import { basename, extname } from "node:path";
import archiver from "archiver";
import type { FastifyInstance } from "fastify";
import sharp from "sharp";
import { z } from "zod";
import { autoOrient } from "../../lib/auto-orient.js";
import { formatZodErrors } from "../../lib/errors.js";
import { validateImageBuffer } from "../../lib/file-validation.js";
import { ensureSharpCompat } from "../../lib/heic-converter.js";
const settingsSchema = z.object({}).passthrough();
const FAVICON_SIZES = [
{ name: "favicon-16x16.png", size: 16, format: "png" as const },
{ name: "favicon-32x32.png", size: 32, format: "png" as const },
@@ -23,6 +28,7 @@ interface UploadedFile {
export function registerFavicon(app: FastifyInstance) {
app.post("/api/v1/tools/favicon", async (request, reply) => {
const uploadedFiles: UploadedFile[] = [];
let settingsRaw: string | null = null;
try {
const parts = request.parts();
@@ -35,6 +41,8 @@ export function registerFavicon(app: FastifyInstance) {
const buffer = Buffer.concat(chunks);
const filename = basename(part.filename ?? `image-${uploadedFiles.length + 1}`);
uploadedFiles.push({ buffer, filename });
} else if (part.fieldname === "settings") {
settingsRaw = part.value as string;
}
}
} catch (err) {
@@ -48,6 +56,30 @@ export function registerFavicon(app: FastifyInstance) {
return reply.status(400).send({ error: "No image file provided" });
}
// Validate all uploaded files
for (const file of uploadedFiles) {
const validation = await validateImageBuffer(file.buffer, file.filename);
if (!validation.valid) {
return reply
.status(400)
.send({ error: `Invalid file "${file.filename}": ${validation.reason}` });
}
}
if (settingsRaw) {
try {
const parsed = JSON.parse(settingsRaw);
const result = settingsSchema.safeParse(parsed);
if (!result.success) {
return reply
.status(400)
.send({ error: "Invalid settings", details: formatZodErrors(result.error.issues) });
}
} catch {
return reply.status(400).send({ error: "Settings must be valid JSON" });
}
}
try {
const jobId = randomUUID();
const isSingleFile = uploadedFiles.length === 1;
+28 -6
View File
@@ -1,10 +1,15 @@
import { basename } from "node:path";
import type { FastifyInstance } from "fastify";
import sharp from "sharp";
import { z } from "zod";
import { autoOrient } from "../../lib/auto-orient.js";
import { formatZodErrors } from "../../lib/errors.js";
import { ensureSharpCompat } from "../../lib/heic-converter.js";
const DEFAULT_THRESHOLD = 8;
const settingsSchema = z.object({
threshold: z.number().min(0).max(20).default(8),
});
const THUMBNAIL_WIDTH = 200;
/**
@@ -89,7 +94,7 @@ async function extractFileInfo(file: FileData): Promise<FileInfo> {
export function registerFindDuplicates(app: FastifyInstance) {
app.post("/api/v1/tools/find-duplicates", async (request, reply) => {
const files: FileData[] = [];
let threshold = DEFAULT_THRESHOLD;
let settingsRaw: string | null = null;
try {
const parts = request.parts();
@@ -107,11 +112,11 @@ export function registerFindDuplicates(app: FastifyInstance) {
originalSize: buf.length,
});
}
} else if (part.type === "field" && part.fieldname === "settings") {
settingsRaw = part.value as string;
} else if (part.type === "field" && part.fieldname === "threshold") {
const val = Number(part.value);
if (!Number.isNaN(val) && val >= 0 && val <= 20) {
threshold = val;
}
// Legacy: accept bare threshold field as settings
settingsRaw = JSON.stringify({ threshold: Number(part.value) });
}
}
} catch (err) {
@@ -121,6 +126,23 @@ export function registerFindDuplicates(app: FastifyInstance) {
});
}
// Parse and validate settings
let settings: z.infer<typeof settingsSchema>;
try {
const parsed = settingsRaw ? JSON.parse(settingsRaw) : {};
const result = settingsSchema.safeParse(parsed);
if (!result.success) {
return reply
.status(400)
.send({ error: "Invalid settings", details: formatZodErrors(result.error.issues) });
}
settings = result.data;
} catch {
return reply.status(400).send({ error: "Settings must be valid JSON" });
}
const threshold = settings.threshold;
if (files.length < 2) {
return reply
.status(400)
+2 -1
View File
@@ -2,6 +2,7 @@ import { basename } from "node:path";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import sharp from "sharp";
import { z } from "zod";
import { formatZodErrors } from "../../lib/errors.js";
import { ensureSharpCompat } from "../../lib/heic-converter.js";
const settingsSchema = z.object({
@@ -89,7 +90,7 @@ export function registerImageToBase64(app: FastifyInstance) {
if (!parsed.success) {
return reply.status(400).send({
error: "Invalid settings",
details: parsed.error.flatten().fieldErrors,
details: formatZodErrors(parsed.error.issues),
});
}
const opts = parsed.data;
+15 -1
View File
@@ -6,6 +6,7 @@ import { getBundleForTool, TOOL_BUNDLE_MAP } from "@ashim/shared";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod";
import { autoOrient } from "../../lib/auto-orient.js";
import { formatZodErrors } from "../../lib/errors.js";
import { isToolInstalled } from "../../lib/feature-status.js";
import { validateImageBuffer } from "../../lib/file-validation.js";
import { decodeToSharpCompat, needsCliDecode } from "../../lib/format-decoders.js";
@@ -79,7 +80,20 @@ export function registerNoiseRemoval(app: FastifyInstance) {
}
try {
const parsed = settingsSchema.parse(settingsRaw ? JSON.parse(settingsRaw) : {});
let parsed: z.infer<typeof settingsSchema>;
try {
const raw = settingsRaw ? JSON.parse(settingsRaw) : {};
const result = settingsSchema.safeParse(raw);
if (!result.success) {
return reply
.status(400)
.send({ error: "Invalid settings", details: formatZodErrors(result.error.issues) });
}
parsed = result.data;
} catch {
return reply.status(400).send({ error: "Settings must be valid JSON" });
}
request.log.info(
{ toolId: "noise-removal", imageSize: fileBuffer.length, tier: parsed.tier },
"Starting noise removal",
+28 -7
View File
@@ -6,6 +6,7 @@ import { getBundleForTool, TOOL_BUNDLE_MAP } from "@ashim/shared";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod";
import { autoOrient } from "../../lib/auto-orient.js";
import { formatZodErrors } from "../../lib/errors.js";
import { isToolInstalled } from "../../lib/feature-status.js";
import { validateImageBuffer } from "../../lib/file-validation.js";
import { decodeToSharpCompat, needsCliDecode } from "../../lib/format-decoders.js";
@@ -14,6 +15,13 @@ import { createWorkspace } from "../../lib/workspace.js";
import { updateSingleFileProgress } from "../progress.js";
import { registerToolProcessFn } from "../tool-factory.js";
const settingsSchema = z.object({
sensitivity: z.number().min(0).max(100).default(50),
strength: z.number().min(0).max(100).default(70),
format: z.string().optional(),
quality: z.number().min(1).max(100).default(90),
});
/** Red eye detection and removal route. */
export function registerRedEyeRemoval(app: FastifyInstance) {
app.post(
@@ -69,7 +77,19 @@ export function registerRedEyeRemoval(app: FastifyInstance) {
}
try {
const settings = settingsRaw ? JSON.parse(settingsRaw) : {};
let settings: z.infer<typeof settingsSchema>;
try {
const parsed = settingsRaw ? JSON.parse(settingsRaw) : {};
const result = settingsSchema.safeParse(parsed);
if (!result.success) {
return reply
.status(400)
.send({ error: "Invalid settings", details: formatZodErrors(result.error.issues) });
}
settings = result.data;
} catch {
return reply.status(400).send({ error: "Settings must be valid JSON" });
}
if (validation.format === "heif") {
fileBuffer = await decodeHeic(fileBuffer);
@@ -80,12 +100,13 @@ export function registerRedEyeRemoval(app: FastifyInstance) {
fileBuffer = await decodeToSharpCompat(fileBuffer, validation.format);
}
const { sensitivity, strength, format: outputFormat, quality } = settings;
request.log.info(
{
toolId: "red-eye-removal",
imageSize: fileBuffer.length,
sensitivity: settings.sensitivity,
strength: settings.strength,
sensitivity,
strength,
},
"Starting red eye removal",
);
@@ -116,10 +137,10 @@ export function registerRedEyeRemoval(app: FastifyInstance) {
fileBuffer,
join(workspacePath, "output"),
{
sensitivity: settings.sensitivity ?? 50,
strength: settings.strength ?? 70,
format: settings.format,
quality: settings.quality ?? 90,
sensitivity,
strength,
format: outputFormat,
quality,
},
onProgress,
);
+43 -6
View File
@@ -7,6 +7,7 @@ import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod";
import { autoOrient } from "../../lib/auto-orient.js";
import { applyEffects } from "../../lib/bg-effects.js";
import { formatZodErrors } from "../../lib/errors.js";
import { isToolInstalled } from "../../lib/feature-status.js";
import { validateImageBuffer } from "../../lib/file-validation.js";
import { decodeToSharpCompat, needsCliDecode } from "../../lib/format-decoders.js";
@@ -92,7 +93,19 @@ export function registerRemoveBackground(app: FastifyInstance) {
}
try {
const settings = settingsRaw ? JSON.parse(settingsRaw) : {};
let settings: z.infer<typeof settingsSchema>;
try {
const parsed = settingsRaw ? JSON.parse(settingsRaw) : {};
const result = settingsSchema.safeParse(parsed);
if (!result.success) {
return reply
.status(400)
.send({ error: "Invalid settings", details: formatZodErrors(result.error.issues) });
}
settings = result.data;
} catch {
return reply.status(400).send({ error: "Settings must be valid JSON" });
}
// Decode HEIC/HEIF before processing
if (validation.format === "heif") {
@@ -210,14 +223,38 @@ export function registerRemoveBackground(app: FastifyInstance) {
return reply.status(400).send({ error: "No settings provided" });
}
try {
const settings = JSON.parse(settingsRaw);
const { jobId, filename } = settings;
const effectsSchema = z.object({
jobId: z.string().min(1),
filename: z.string().min(1),
backgroundType: z.enum(["transparent", "color", "gradient", "blur", "image"]).optional(),
backgroundColor: z.string().optional(),
gradientColor1: z.string().optional(),
gradientColor2: z.string().optional(),
gradientAngle: z.number().optional(),
blurEnabled: z.boolean().optional(),
blurIntensity: z.number().min(0).max(100).optional(),
shadowEnabled: z.boolean().optional(),
shadowOpacity: z.number().min(0).max(100).optional(),
});
if (!jobId || !filename) {
return reply.status(400).send({ error: "jobId and filename are required" });
try {
let settings: z.infer<typeof effectsSchema>;
try {
const parsed = JSON.parse(settingsRaw);
const result = effectsSchema.safeParse(parsed);
if (!result.success) {
return reply.status(400).send({
error: "Invalid settings",
details: formatZodErrors(result.error.issues),
});
}
settings = result.data;
} catch {
return reply.status(400).send({ error: "Settings must be valid JSON" });
}
const { jobId, filename } = settings;
const workspacePath = getWorkspacePath(jobId);
const baseName = filename.replace(/\.[^.]+$/, "");
+14 -1
View File
@@ -7,6 +7,7 @@ import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import sharp from "sharp";
import { z } from "zod";
import { autoOrient } from "../../lib/auto-orient.js";
import { formatZodErrors } from "../../lib/errors.js";
import { isToolInstalled } from "../../lib/feature-status.js";
import { validateImageBuffer } from "../../lib/file-validation.js";
import { decodeToSharpCompat, needsCliDecode } from "../../lib/format-decoders.js";
@@ -82,7 +83,19 @@ export function registerRestorePhoto(app: FastifyInstance) {
}
try {
const settings = settingsSchema.parse(settingsRaw ? JSON.parse(settingsRaw) : {});
let settings: z.infer<typeof settingsSchema>;
try {
const parsed = settingsRaw ? JSON.parse(settingsRaw) : {};
const result = settingsSchema.safeParse(parsed);
if (!result.success) {
return reply
.status(400)
.send({ error: "Invalid settings", details: formatZodErrors(result.error.issues) });
}
settings = result.data;
} catch {
return reply.status(400).send({ error: "Settings must be valid JSON" });
}
request.log.info(
{ toolId: "restore-photo", imageSize: fileBuffer.length, mode: settings.mode },
+30 -7
View File
@@ -7,6 +7,7 @@ import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import sharp from "sharp";
import { z } from "zod";
import { autoOrient } from "../../lib/auto-orient.js";
import { formatZodErrors } from "../../lib/errors.js";
import { isToolInstalled } from "../../lib/feature-status.js";
import { validateImageBuffer } from "../../lib/file-validation.js";
import { decodeToSharpCompat, needsCliDecode } from "../../lib/format-decoders.js";
@@ -15,6 +16,15 @@ import { createWorkspace } from "../../lib/workspace.js";
import { updateSingleFileProgress } from "../progress.js";
import { registerToolProcessFn } from "../tool-factory.js";
const settingsSchema = z.object({
scale: z.union([z.number(), z.string()]).transform(Number).default(2),
model: z.string().default("auto"),
faceEnhance: z.boolean().default(false),
denoise: z.union([z.number(), z.string()]).transform(Number).default(0),
format: z.string().default("png"),
quality: z.union([z.number(), z.string()]).transform(Number).default(95),
});
/**
* AI image upscaling route.
* Uses Real-ESRGAN when available, falls back to Lanczos.
@@ -71,13 +81,26 @@ export function registerUpscale(app: FastifyInstance) {
}
try {
const settings = settingsRaw ? JSON.parse(settingsRaw) : {};
const scale = Number(settings.scale) || 2;
const model = settings.model || "auto";
const faceEnhance = Boolean(settings.faceEnhance);
const denoise = Number(settings.denoise) || 0;
const format = settings.format || "png";
const outputQuality = Number(settings.quality) || 95;
let settings: z.infer<typeof settingsSchema>;
try {
const parsed = settingsRaw ? JSON.parse(settingsRaw) : {};
const result = settingsSchema.safeParse(parsed);
if (!result.success) {
return reply
.status(400)
.send({ error: "Invalid settings", details: formatZodErrors(result.error.issues) });
}
settings = result.data;
} catch {
return reply.status(400).send({ error: "Settings must be valid JSON" });
}
const scale = settings.scale;
const model = settings.model;
const faceEnhance = settings.faceEnhance;
const denoise = settings.denoise;
const format = settings.format;
const outputQuality = settings.quality;
request.log.info(
{ toolId: "upscale", imageSize: fileBuffer.length, scale, model, format },
"Starting upscale",
+10 -9
View File
@@ -16,6 +16,7 @@ import { extname } from "node:path";
import { and, desc, eq, like, sql } from "drizzle-orm";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import sharp from "sharp";
import { z } from "zod";
import { db, schema, sqlite } from "../db/index.js";
import { auditLog } from "../lib/audit.js";
import {
@@ -402,16 +403,16 @@ export async function userFileRoutes(app: FastifyInstance): Promise<void> {
const user = requireAuth(request, reply);
if (!user) return;
const body = request.body as { ids?: unknown } | null;
if (!Array.isArray(body?.ids) || body.ids.length === 0) {
return reply.status(400).send({ error: "ids must be a non-empty array" });
}
const ids = body.ids.filter((id): id is string => typeof id === "string");
if (ids.length === 0) {
return reply.status(400).send({ error: "ids must contain string values" });
const deleteSchema = z.object({
ids: z.array(z.string()).min(1, "ids must be a non-empty array of strings"),
});
const parsed = deleteSchema.safeParse(request.body);
if (!parsed.success) {
return reply.status(400).send({
error: parsed.error.issues.map((i) => i.message).join("; "),
});
}
const { ids } = parsed.data;
let deletedCount = 0;
+22 -1
View File
@@ -2,7 +2,7 @@
The `@ashim/ai` package bridges Node.js to a **persistent Python sidecar** for all ML operations. The dispatcher process stays alive between requests for fast warm-start performance. GPU is auto-detected at startup and used when available.
13 AI tool routes. All models run locally - no internet required after initial model download.
14 AI tool routes. All models run locally - no internet required after initial model download.
## Architecture
@@ -216,6 +216,27 @@ GPU-accelerated when an NVIDIA GPU is available.
| `upper-body` | 4.5× face | LinkedIn / formal |
| `half-body` | 7.0× face | Full upper body |
## Image Enhancement
**Function:** `analyzeImage` + `applyCorrections`
**Tool route:** `image-enhancement`
**Engine:** Analysis-based (Sharp histogram and statistics)
Analyzes the image and applies automatic corrections for exposure, contrast, white balance, saturation, sharpness, and noise. Supports scene-specific modes.
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `mode` | `auto` \| `portrait` \| `landscape` \| `low-light` \| `food` \| `document` | `auto` | Scene mode for tuning corrections |
| `intensity` | number (0-100) | 50 | Overall correction strength |
| `corrections.exposure` | boolean | true | Apply exposure correction |
| `corrections.contrast` | boolean | true | Apply contrast correction |
| `corrections.whiteBalance` | boolean | true | Apply white balance correction |
| `corrections.saturation` | boolean | true | Apply saturation correction |
| `corrections.sharpness` | boolean | true | Apply sharpness correction |
| `corrections.denoise` | boolean | true | Apply denoising |
An additional analysis endpoint is available at `POST /api/v1/tools/image-enhancement/analyze` which returns the detected corrections without applying them.
## Content-Aware Resize (Seam Carving)
**Function:** `seamCarve`
+59 -3
View File
@@ -25,7 +25,7 @@ curl http://localhost:1349/api/v1/tools/resize \
-H "Authorization: Bearer <session-token>"
```
Sessions expire after 24 hours.
Sessions expire after 7 days (configurable via `SESSION_DURATION_HOURS`).
### API Keys
@@ -69,6 +69,13 @@ Keys are prefixed `si_` and stored as SHA-256 hashes - the raw key is shown once
| Manage users & teams | ✓ | - |
| Manage branding | ✓ | - |
## Health Check
| Method | Path | Access | Description |
|--------|------|--------|-------------|
| `GET` | `/api/v1/health` | Public | Basic health check. Returns `{"status":"healthy","version":"..."}` with 200, or `{"status":"unhealthy"}` with 503 if the database is unreachable. |
| `GET` | `/api/v1/admin/health` | Admin (`system:health`) | Detailed diagnostics including uptime, storage mode, database status, queue state, and GPU availability. |
## Using Tools
Every tool follows the same pattern:
@@ -120,7 +127,7 @@ curl -X POST http://localhost:1349/api/v1/tools/<toolId>/batch \
| Tool ID | Name | Key settings |
|---------|------|-------------|
| `color-adjustments` | Adjust Colors | `brightness`, `contrast`, `exposure`, `saturation`, `temperature`, `sharpness`, `vibrance`, effects (grayscale/sepia/invert/vignette) |
| `adjust-colors` | Adjust Colors | `brightness`, `contrast`, `exposure`, `saturation`, `temperature`, `sharpness`, `vibrance`, effects (grayscale/sepia/invert/vignette) |
| `sharpening` | Sharpening | `mode` (adaptive/unsharp/highpass), `amount`, `radius`, `threshold` |
| `replace-color` | Replace Color | `targetColor`, `replacementColor`, `tolerance`, `invert` |
@@ -197,7 +204,7 @@ curl -X POST http://localhost:1349/api/v1/tools/compress/batch \
-F 'settings={"quality":80}'
```
Limits: up to **200 files** per batch. Concurrency controlled by `CONCURRENT_JOBS` (default: 3).
Concurrency is controlled by `CONCURRENT_JOBS` (default: auto-detected from CPU cores). Set `MAX_BATCH_SIZE` to limit the number of files per batch (default: unlimited).
## Pipelines
@@ -300,6 +307,55 @@ Runtime key-value configuration (read by any authenticated user, write by admin
Known keys: `disabledTools` (JSON array of tool IDs), `enableExperimentalTools` (bool string), `loginAttemptLimit` (number), `customLogo` (managed via branding endpoint).
## Roles
Custom role management with granular permissions.
| Method | Path | Access | Description |
|--------|------|--------|-------------|
| `GET` | `/api/v1/roles` | Admin (`audit:read`) | List all roles with user counts |
| `POST` | `/api/v1/roles` | Admin (`users:manage`) | Create a custom role (`name`, `description`, `permissions`) |
| `PUT` | `/api/v1/roles/:id` | Admin (`users:manage`) | Update a custom role (cannot modify built-in roles) |
| `DELETE` | `/api/v1/roles/:id` | Admin (`users:manage`) | Delete a custom role (cannot delete built-in roles; affected users revert to `user` role) |
Available permissions: `tools:use`, `files:own`, `files:all`, `apikeys:own`, `apikeys:all`, `pipelines:own`, `pipelines:all`, `settings:read`, `settings:write`, `users:manage`, `teams:manage`, `branding:manage`, `features:manage`, `system:health`, `audit:read`.
## Audit Log
Admin-only endpoint for reviewing security-relevant actions.
| Method | Path | Access | Description |
|--------|------|--------|-------------|
| `GET` | `/api/v1/audit-log` | Admin (`audit:read`) | Paginated audit log with optional filters |
Query parameters:
| Parameter | Description |
|-----------|-------------|
| `page` | Page number (default: 1) |
| `limit` | Entries per page (default: 50, max: 100) |
| `action` | Filter by action type (e.g. `ROLE_CREATED`, `ROLE_DELETED`) |
| `from` | Filter entries after this ISO 8601 date |
| `to` | Filter entries before this ISO 8601 date |
## Analytics
| Method | Path | Access | Description |
|--------|------|--------|-------------|
| `GET` | `/api/v1/config/analytics` | Public | Get analytics configuration (PostHog key, Sentry DSN, sample rate). Returns empty values if `ANALYTICS_ENABLED=false`. |
| `PUT` | `/api/v1/user/analytics` | Auth | Set the current user's analytics consent (`enabled: true/false`) or defer with `remindLater: true`. |
## Features / AI Bundles
Manage AI feature bundles (install/uninstall AI model packages in the Docker environment).
| Method | Path | Access | Description |
|--------|------|--------|-------------|
| `GET` | `/api/v1/features` | Auth | List all feature bundles and their install status |
| `POST` | `/api/v1/admin/features/:bundleId/install` | Admin (`features:manage`) | Install a feature bundle (async, returns `jobId` for progress tracking) |
| `POST` | `/api/v1/admin/features/:bundleId/uninstall` | Admin (`features:manage`) | Uninstall a feature bundle and clean up model files |
| `GET` | `/api/v1/admin/features/disk-usage` | Admin (`features:manage`) | Get total disk usage of AI models |
## Error Responses
All errors return JSON:
+1 -1
View File
@@ -43,7 +43,7 @@ Shared TypeScript types, constants (like `APP_VERSION` and tool definitions), an
### API (`apps/api`)
A Fastify v5 server exposing 47 tool routes (34 standard image operations + 13 AI-powered) that handles:
A Fastify v5 server exposing 47 tool routes (33 standard image operations + 14 AI-powered) that handles:
- File uploads, temporary workspace management, and persistent file storage
- User file library with version chains (`user_files` table) -- each processed result links back to its source file and records which tool was applied, with auto-generated thumbnails for the Files page
- Tool execution (routes each tool request to the image engine or AI bridge)
+27 -8
View File
@@ -9,7 +9,10 @@ All configuration is done through environment variables. Every variable has a se
| Variable | Default | Description |
|---|---|---|
| `PORT` | `1349` | Port the server listens on. |
| `RATE_LIMIT_PER_MIN` | `100` | Maximum requests per minute per IP. |
| `RATE_LIMIT_PER_MIN` | `0` (disabled) | Maximum requests per minute per IP. Set to 0 to disable rate limiting. |
| `CORS_ORIGIN` | (empty) | Comma-separated allowed origins for CORS, or empty for same-origin only. |
| `LOG_LEVEL` | `info` | Log verbosity. One of: `fatal`, `error`, `warn`, `info`, `debug`, `trace`. |
| `TRUST_PROXY` | `true` | Trust `X-Forwarded-For` headers from a reverse proxy. Set to `false` if not behind a proxy. |
### Authentication
@@ -18,7 +21,8 @@ All configuration is done through environment variables. Every variable has a se
| `AUTH_ENABLED` | `false` | Set to `true` to require login. The Docker image defaults to `true`. |
| `DEFAULT_USERNAME` | `admin` | Username for the initial admin account. Only used on first run. |
| `DEFAULT_PASSWORD` | `admin` | Password for the initial admin account. Change this after first login. |
| `MAX_USERS` | `5` | Maximum number of registered user accounts |
| `MAX_USERS` | `0` (unlimited) | Maximum number of registered user accounts. Set to 0 for unlimited. |
| `SESSION_DURATION_HOURS` | `168` | Login session lifetime in hours (default is 7 days). |
| `SKIP_MUST_CHANGE_PASSWORD` | - | Set to any non-empty value to bypass the forced password-change prompt on first login |
### Storage
@@ -34,17 +38,25 @@ All configuration is done through environment variables. Every variable has a se
| Variable | Default | Description |
|---|---|---|
| `MAX_UPLOAD_SIZE_MB` | `100` | Maximum file size per upload in megabytes. |
| `MAX_BATCH_SIZE` | `200` | Maximum number of files in a single batch request. |
| `CONCURRENT_JOBS` | `3` | Number of batch jobs that run in parallel. Higher values use more memory. |
| `MAX_MEGAPIXELS` | `100` | Maximum image resolution allowed. Rejects images larger than this. |
| `MAX_UPLOAD_SIZE_MB` | `0` (unlimited) | Maximum file size per upload in megabytes. Set to 0 for unlimited. |
| `MAX_BATCH_SIZE` | `0` (unlimited) | Maximum number of files in a single batch request. Set to 0 for unlimited. |
| `CONCURRENT_JOBS` | `0` (auto) | Number of batch jobs that run in parallel. Set to 0 to auto-detect based on available CPU cores. |
| `MAX_MEGAPIXELS` | `0` (unlimited) | Maximum image resolution allowed in megapixels. Set to 0 for unlimited. |
| `MAX_WORKER_THREADS` | `0` (auto) | Maximum worker threads for image processing. Set to 0 to auto-detect based on available CPU cores. |
| `PROCESSING_TIMEOUT_S` | `0` (no limit) | Maximum processing time per request in seconds. Set to 0 for no timeout. |
| `MAX_PIPELINE_STEPS` | `0` (no limit) | Maximum number of steps in a pipeline. Set to 0 for no limit. |
| `MAX_CANVAS_PIXELS` | `0` (no limit) | Maximum canvas size in pixels for output images. Set to 0 for no limit. |
| `MAX_SVG_SIZE_MB` | `0` (unlimited) | Maximum SVG file size in megabytes. Set to 0 for unlimited. |
| `MAX_LOGO_SIZE_KB` | `500` | Maximum custom branding logo size in kilobytes. |
| `MAX_SPLIT_GRID` | `100` | Maximum grid dimension for the image split tool. |
| `MAX_PDF_PAGES` | `0` (unlimited) | Maximum number of PDF pages for PDF-to-image conversion. Set to 0 for unlimited. |
### Cleanup
| Variable | Default | Description |
|---|---|---|
| `FILE_MAX_AGE_HOURS` | `24` | How long temporary files are kept before automatic deletion. |
| `CLEANUP_INTERVAL_MINUTES` | `30` | How often the cleanup job runs. |
| `FILE_MAX_AGE_HOURS` | `72` | How long temporary files are kept before automatic deletion. |
| `CLEANUP_INTERVAL_MINUTES` | `60` | How often the cleanup job runs. |
### Appearance
@@ -54,6 +66,13 @@ All configuration is done through environment variables. Every variable has a se
| `DEFAULT_THEME` | `light` | Default theme for new sessions. `light` or `dark`. |
| `DEFAULT_LOCALE` | `en` | Default interface language. |
### Docker permissions
| Variable | Default | Description |
|---|---|---|
| `PUID` | `999` | Run the container process as this UID. Set to match your host user for bind mounts (`id -u`). |
| `PGID` | `999` | Run the container process as this GID. Set to match your host group for bind mounts (`id -g`). |
## Docker example
```yaml
+2 -2
View File
@@ -214,5 +214,5 @@ See the [Configuration guide](/guide/configuration) for the full list. Key ones
| `DEFAULT_USERNAME` | `admin` | Default admin username |
| `DEFAULT_PASSWORD` | `admin` | Default admin password |
| `SKIP_MUST_CHANGE_PASSWORD` | `false` | Skip forced password change (CI/dev only) |
| `RATE_LIMIT_PER_MIN` | `100` | API rate limit per minute |
| `MAX_UPLOAD_SIZE_MB` | `100` | Maximum upload size in MB |
| `RATE_LIMIT_PER_MIN` | `0` | API rate limit per minute (0 = disabled) |
| `MAX_UPLOAD_SIZE_MB` | `0` | Maximum upload size in MB (0 = unlimited) |
+1 -1
View File
@@ -17,7 +17,7 @@ features:
- title: 45+ Image Tools
details: Resize, crop, compress, convert, watermark, color adjust, vectorize, create GIFs, build collages, generate passport photos, find duplicates, and more.
- title: Local AI
details: 13 AI-powered tools - remove backgrounds, upscale, restore and colorize old photos, erase objects, blur faces, enhance faces, extract text (OCR). All on your hardware, no internet required.
details: 14 AI-powered tools - remove backgrounds, upscale, enhance images, restore and colorize old photos, erase objects, blur faces, enhance faces, extract text (OCR). All on your hardware, no internet required.
- title: Pipelines
details: Chain tools into reusable workflows with up to 20 steps. Batch process up to 200 images at once with a single request.
- title: REST API