mirror of
https://github.com/snapotter-hq/SnapOtter.git
synced 2026-08-03 07:46:42 +02:00
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:
+2200
-2
File diff suppressed because it is too large
Load Diff
@@ -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) {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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 }> = [];
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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,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;
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
|
||||
@@ -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(/\.[^.]+$/, "");
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user