mirror of
https://github.com/snapotter-hq/SnapOtter.git
synced 2026-08-03 07:46:42 +02:00
fix: first-run QA sweep of the single-container image (#413)
Fixes found by manually testing a fresh install end to end: - auth: the must-change-password gate returned 403 on public routes including /api/v1/health, so every fresh install showed a false "Reconnecting to server" banner on the forced password change screen. Public routes are now exempt (they need no session at all). Adds the gate's first direct tests. - multipart: @fastify/multipart's parts() iterator (9.4.0 and 10.0.0) ends on the request stream's "close", which on a reused keep-alive connection fires while an earlier part is still streaming to storage, silently dropping the parts behind it. The object eraser lost its mask file on every second POST per connection. Replaced with a busboy-driven iterator (lib/multipart-parts.ts) that ends on busboy's own "finish", installed for all routes via a preValidation hook; the tool-factory field-recovery workaround for the same bug is now unnecessary and removed. - eraser: the mask canvas backing store is natural resolution, but "absolute inset-0" does not stretch replaced elements, so the canvas rendered at intrinsic size and the brush ring, strokes, and exported mask were all misscaled on photos larger than the viewport. The canvas now gets an explicit CSS box at the fitted size. - compare slider: solid white divider with a dark halo so it stays visible over light images; still initialised at the painted region. - tool page: the AI bundle install prompt now centers in the content area instead of hugging the top. - api docs: disabled Scalar's cloud features (Ask AI, Generate MCP, Open API Client, dev toolbar), hid the "Powered by Scalar" footer link, and set the page title to "SnapOtter API Reference". The docs CSP blocks those cloud calls by design, so the buttons were dead UI. - docker: embedded Redis comes from packages.redis.io pinned to the 8.x major (was Debian's 7.0.15), matching the Compose stack and the documented claim. Build fails fast if the major ever drifts. - docs: DOCKERHUB.md quick start now leads with the one-command docker run (matching the README) with Compose as the production path; README says embedded Postgres 17 + Redis 8. Claude-Session: https://claude.ai/code/session_01XGB4pGvTvb7sUX4JN745U7
This commit is contained in:
+24
-12
@@ -15,13 +15,32 @@ Open-source, self-hostable file manipulation suite. 200+ tools across image, vid
|
||||
|
||||
## What is SnapOtter?
|
||||
|
||||
SnapOtter is a privacy-first alternative to cloud file-processing services. Convert, compress, edit, and transform files in your browser while the work happens on a server you control. No uploads to third parties, no per-file pricing, no SaaS lock-in. It runs as a small Docker Compose stack (the app plus PostgreSQL 17 and Redis 8) and works on AMD64 and ARM64.
|
||||
SnapOtter is a privacy-first alternative to cloud file-processing services. Convert, compress, edit, and transform files in your browser while the work happens on a server you control. No uploads to third parties, no per-file pricing, no SaaS lock-in. It runs as a single container (embedded PostgreSQL 17 and Redis 8) or as a small Docker Compose stack for production, and works on AMD64 and ARM64.
|
||||
|
||||

|
||||
|
||||
## Quick start
|
||||
|
||||
SnapOtter runs alongside PostgreSQL 17 and Redis 8. Save this as `compose.yaml`:
|
||||
One command, no setup. The container starts an embedded PostgreSQL 17 and Redis 8 on the loopback interface and keeps all data in the `SnapOtter-data` volume:
|
||||
|
||||
```bash
|
||||
docker run -d --name SnapOtter -p 1349:1349 -v SnapOtter-data:/data snapotter/snapotter:latest
|
||||
```
|
||||
|
||||
The same image is also published to GHCR as `ghcr.io/snapotter-hq/snapotter:latest`. Embedded mode turns off automatically as soon as you set `DATABASE_URL`, so moving to the Compose stack later is just a config change.
|
||||
|
||||
Open `http://localhost:1349` and log in.
|
||||
|
||||
| Field | Value |
|
||||
|----------|---------|
|
||||
| Username | `admin` |
|
||||
| Password | `admin` |
|
||||
|
||||
You will be asked to change your password on first login.
|
||||
|
||||
### Production: Docker Compose
|
||||
|
||||
For production, run PostgreSQL and Redis in their own containers. Save this as `compose.yaml`:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
@@ -59,14 +78,7 @@ Then start the stack:
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Open `http://localhost:1349` and log in.
|
||||
|
||||
| Field | Value |
|
||||
|----------|---------|
|
||||
| Username | `admin` |
|
||||
| Password | `admin` |
|
||||
|
||||
You will be asked to change your password on first login. Change `DEFAULT_PASSWORD` for any non-local deployment.
|
||||
Change `DEFAULT_PASSWORD` for any non-local deployment.
|
||||
|
||||
## Supported tags and platforms
|
||||
|
||||
@@ -128,10 +140,10 @@ OIDC, SSO, S3 storage, and the full variable reference are documented in [Config
|
||||
|
||||
| Path | Purpose |
|
||||
|------|---------|
|
||||
| `/data` | AI models and persistent user files. Back this up. |
|
||||
| `/data` | AI models and persistent user files; in single-container mode also the embedded PostgreSQL and Redis data. Back this up. |
|
||||
| `/tmp/workspace` | Temporary processing files (auto-cleaned). |
|
||||
|
||||
PostgreSQL and Redis keep their own volumes (`snapotter-pgdata`, `snapotter-redisdata`) in the Compose stack above.
|
||||
In the Compose stack, PostgreSQL and Redis keep their own volumes (`snapotter-pgdata`, `snapotter-redisdata`).
|
||||
|
||||
## Ports
|
||||
|
||||
|
||||
@@ -41,13 +41,13 @@ Stirling-PDF stops at PDFs. ConvertX stops at conversions. SnapOtter runs all fi
|
||||
- **21 languages:** English, Arabic, Chinese (Simplified & Traditional), Dutch, French, German, Hindi, Indonesian, Italian, Japanese, Korean, Polish, Portuguese, Russian, Spanish, Swedish, Thai, Turkish, Ukrainian, Vietnamese. RTL support for Arabic
|
||||
- **Pipelines:** Chain tools into reusable workflows with unlimited steps. Import/export as JSON. Batch process unlimited files at once
|
||||
- **REST API:** Every tool available via API with API key auth. Interactive docs at `/api/docs`
|
||||
- **Self-hosted:** one `docker run` for a single-container quick start (embedded Postgres + Redis), or a Postgres 17 + Redis 8 Compose stack for production. No external SaaS dependencies
|
||||
- **Self-hosted:** one `docker run` for a single-container quick start (embedded Postgres 17 + Redis 8), or the same Postgres 17 + Redis 8 as a Compose stack for production. No external SaaS dependencies
|
||||
- **Multi-arch:** Runs on AMD64 and ARM64 (Intel, Apple Silicon, Raspberry Pi)
|
||||
- **Privacy first:** Your files never leave your network. Basic analytics help us catch bugs and improve tools -- disable anytime by rebuilding with `SNAPOTTER_ANALYTICS=off` ([Here's how to do it](https://docs.snapotter.com/guide/deployment.html#analytics))
|
||||
|
||||
## Quick Start
|
||||
|
||||
One container, no setup. It starts an embedded Postgres + Redis on loopback and stores data in the `SnapOtter-data` volume:
|
||||
One container, no setup. It starts an embedded Postgres 17 + Redis 8 on loopback and stores data in the `SnapOtter-data` volume:
|
||||
|
||||
```bash
|
||||
docker run -d --name SnapOtter -p 1349:1349 -v SnapOtter-data:/data snapotter/snapotter:latest
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
"migrate:sqlite": "tsx src/db/migrate-from-sqlite.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/busboy": "^3.2.0",
|
||||
"@fastify/cookie": "^11.0.2",
|
||||
"@fastify/cors": "^11.0.0",
|
||||
"@fastify/multipart": "^9.0.0",
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import type { Readable } from "node:stream";
|
||||
import { Busboy, type BusboyHeaders } from "@fastify/busboy";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { env } from "../config.js";
|
||||
|
||||
export interface MultipartFilePart {
|
||||
type: "file";
|
||||
fieldname: string;
|
||||
filename: string;
|
||||
encoding: string;
|
||||
mimetype: string;
|
||||
file: Readable;
|
||||
}
|
||||
|
||||
export interface MultipartFieldPart {
|
||||
type: "field";
|
||||
fieldname: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
export type MultipartPart = MultipartFilePart | MultipartFieldPart;
|
||||
|
||||
const DONE = Symbol("multipart-done");
|
||||
|
||||
/**
|
||||
* Iterate multipart parts by driving busboy directly.
|
||||
*
|
||||
* Replaces @fastify/multipart's request.parts(): that iterator treats the
|
||||
* REQUEST stream's "close" event as end-of-parts, and on a reused keep-alive
|
||||
* connection the whole body can be read (firing "close") while the consumer
|
||||
* is still streaming an earlier part to storage. Every part busboy emits
|
||||
* after that moment lands behind the end marker and is silently dropped; in
|
||||
* practice the second multipart POST on a warm connection lost its trailing
|
||||
* parts (the object eraser's mask file, then the settings fields). Verified
|
||||
* against @fastify/multipart 9.4.0 and 10.0.0. Busboy's own "finish" fires
|
||||
* only after every part has been emitted, so iteration ends there instead,
|
||||
* and the request stream's "close" is deliberately not treated as an end
|
||||
* signal (a client abort surfaces as an "error" on the stream and as a
|
||||
* truncated-part error from busboy).
|
||||
*/
|
||||
export async function* multipartParts(request: FastifyRequest): AsyncGenerator<MultipartPart> {
|
||||
const raw = request.raw;
|
||||
const bb = new Busboy({
|
||||
headers: raw.headers as BusboyHeaders,
|
||||
limits: {
|
||||
fileSize: env.MAX_UPLOAD_SIZE_MB > 0 ? env.MAX_UPLOAD_SIZE_MB * 1024 * 1024 : undefined,
|
||||
files: env.MAX_BATCH_SIZE > 0 ? env.MAX_BATCH_SIZE : undefined,
|
||||
},
|
||||
});
|
||||
|
||||
const queue: Array<MultipartPart | Error | typeof DONE> = [];
|
||||
let wake: (() => void) | null = null;
|
||||
const push = (value: MultipartPart | Error | typeof DONE) => {
|
||||
queue.push(value);
|
||||
wake?.();
|
||||
wake = null;
|
||||
};
|
||||
|
||||
bb.on("file", (fieldname, stream, filename, encoding, mimetype) => {
|
||||
// Parity with @fastify/multipart's throwFileSizeLimit default: a stream
|
||||
// that hit the fileSize limit fails its consumer instead of silently
|
||||
// truncating the stored object.
|
||||
stream.on("limit", () => stream.destroy(new Error("request file too large")));
|
||||
push({
|
||||
type: "file",
|
||||
fieldname,
|
||||
filename: filename || "upload",
|
||||
encoding,
|
||||
mimetype,
|
||||
file: stream,
|
||||
});
|
||||
});
|
||||
bb.on("field", (fieldname, value) => push({ type: "field", fieldname, value }));
|
||||
bb.on("filesLimit", () => push(new Error("reached files limit")));
|
||||
bb.on("partsLimit", () => push(new Error("reached parts limit")));
|
||||
bb.on("error", (err: unknown) => push(err instanceof Error ? err : new Error(String(err))));
|
||||
bb.on("finish", () => push(DONE));
|
||||
raw.on("error", (err: Error) => push(err));
|
||||
|
||||
raw.pipe(bb);
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
if (queue.length === 0) {
|
||||
await new Promise<void>((resolve) => {
|
||||
wake = resolve;
|
||||
});
|
||||
}
|
||||
const value = queue.shift();
|
||||
if (value === undefined) continue;
|
||||
if (value === DONE) return;
|
||||
if (value instanceof Error) throw value;
|
||||
yield value;
|
||||
}
|
||||
} finally {
|
||||
raw.unpipe(bb);
|
||||
bb.removeAllListeners();
|
||||
}
|
||||
}
|
||||
@@ -1243,21 +1243,17 @@ export async function authMiddleware(app: FastifyInstance): Promise<void> {
|
||||
role: user.role,
|
||||
};
|
||||
|
||||
// Enforce mustChangePassword — block non-auth API calls
|
||||
// (skipped when SKIP_MUST_CHANGE_PASSWORD=true for CI/dev environments)
|
||||
if (user.mustChangePassword && !env.SKIP_MUST_CHANGE_PASSWORD) {
|
||||
const allowed = [
|
||||
"/api/auth/change-password",
|
||||
"/api/auth/logout",
|
||||
"/api/auth/session",
|
||||
"/api/v1/config/",
|
||||
];
|
||||
if (!allowed.some((p) => request.url.startsWith(p)) && request.url.startsWith("/api/")) {
|
||||
return reply.status(403).send({
|
||||
error: "Password change required",
|
||||
code: "MUST_CHANGE_PASSWORD",
|
||||
});
|
||||
}
|
||||
// Enforce mustChangePassword by blocking the authenticated API surface
|
||||
// until the password is rotated. Public routes stay reachable: they need
|
||||
// no session at all, so a 403 on the cookied variant adds no security and
|
||||
// breaks the SPA (the /api/v1/health poll used to trip a false
|
||||
// "Reconnecting to server" banner on the forced change-password screen).
|
||||
// Skipped when SKIP_MUST_CHANGE_PASSWORD=true for CI/dev environments.
|
||||
if (user.mustChangePassword && !env.SKIP_MUST_CHANGE_PASSWORD && !isPublic) {
|
||||
return reply.status(403).send({
|
||||
error: "Password change required",
|
||||
code: "MUST_CHANGE_PASSWORD",
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import multipart from "@fastify/multipart";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { env } from "../config.js";
|
||||
import { multipartParts } from "../lib/multipart-parts.js";
|
||||
|
||||
export async function registerUpload(app: FastifyInstance): Promise<void> {
|
||||
await app.register(multipart, {
|
||||
@@ -9,4 +10,21 @@ export async function registerUpload(app: FastifyInstance): Promise<void> {
|
||||
files: env.MAX_BATCH_SIZE > 0 ? env.MAX_BATCH_SIZE : undefined,
|
||||
},
|
||||
});
|
||||
|
||||
// Swap the plugin's request.parts() for a busboy-driven iterator
|
||||
// (lib/multipart-parts.ts). The plugin's iterator ends when the REQUEST
|
||||
// stream closes, which on a reused keep-alive connection fires while an
|
||||
// earlier part is still streaming to storage, silently dropping every part
|
||||
// behind it (the object eraser lost its mask file on the second POST per
|
||||
// connection; dropped trailing settings fields were papered over by a
|
||||
// recovery workaround in tool-factory). request.file() callers
|
||||
// (features.ts, files.ts) stay on the plugin: the first part is always
|
||||
// emitted before the premature end marker can be queued, and field values
|
||||
// are recovered from busboy's side map.
|
||||
app.addHook("preValidation", async (request) => {
|
||||
if (request.isMultipart()) {
|
||||
const fixedParts = (() => multipartParts(request)) as unknown as typeof request.parts;
|
||||
(request as { parts: typeof request.parts }).parts = fixedParts;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+32
-11
@@ -1,7 +1,7 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import scalarPlugin from "@scalar/fastify-api-reference";
|
||||
import scalarPlugin, { type FastifyApiReferenceOptions } from "@scalar/fastify-api-reference";
|
||||
import { SECTIONS, TOOLS, toolSection } from "@snapotter/shared";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import yaml from "js-yaml";
|
||||
@@ -173,12 +173,23 @@ export async function docsRoutes(app: FastifyInstance): Promise<void> {
|
||||
reply.type("text/yaml").send(specContent);
|
||||
});
|
||||
|
||||
await app.register(scalarPlugin, {
|
||||
routePrefix: "/api/docs",
|
||||
configuration: {
|
||||
content: specContent,
|
||||
theme: "default",
|
||||
customCss: `
|
||||
// Scalar's "Ask AI" (Agent Scalar), "Generate MCP", "Open API Client", and
|
||||
// the Configure/Share/Deploy toolbar are all Scalar cloud features: they
|
||||
// upload or link the OpenAPI document to scalar.com, which the docs CSP
|
||||
// blocks by design (self-hosted docs make no external calls). Hide them
|
||||
// instead of shipping dead UI. `agent` is a source-level key the plugin's
|
||||
// configuration type doesn't list yet, hence the widened type.
|
||||
const configuration: NonNullable<FastifyApiReferenceOptions["configuration"]> & {
|
||||
agent?: { disabled?: boolean };
|
||||
} = {
|
||||
content: specContent,
|
||||
pageTitle: "SnapOtter API Reference",
|
||||
agent: { disabled: true },
|
||||
mcp: { disabled: true },
|
||||
hideClientButton: true,
|
||||
showDeveloperTools: "never",
|
||||
theme: "default",
|
||||
customCss: `
|
||||
:root {
|
||||
--scalar-color-1: #09090b;
|
||||
--scalar-color-2: #3f3f46;
|
||||
@@ -190,10 +201,20 @@ export async function docsRoutes(app: FastifyInstance): Promise<void> {
|
||||
--scalar-border-color: #e4e4e7;
|
||||
--scalar-font: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
}
|
||||
/* Hide the "Powered by Scalar" sidebar footer link. Scalar exposes no
|
||||
config flag for it (unlike the cloud buttons disabled above). */
|
||||
a[href^="https://www.scalar.com"],
|
||||
a[href^="https://scalar.com"] {
|
||||
display: none !important;
|
||||
}
|
||||
`,
|
||||
hideDownloadButton: false,
|
||||
hideTestRequestButton: true,
|
||||
hiddenClients: true,
|
||||
},
|
||||
hideDownloadButton: false,
|
||||
hideTestRequestButton: true,
|
||||
hiddenClients: true,
|
||||
};
|
||||
|
||||
await app.register(scalarPlugin, {
|
||||
routePrefix: "/api/docs",
|
||||
configuration,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -249,15 +249,15 @@ export function createToolRoute<T>(app: FastifyInstance, config: ToolRouteConfig
|
||||
let clientJobId: string | null = null;
|
||||
let fileCount = 0;
|
||||
const received: ReceivedUpload[] = [];
|
||||
// Track last part for post-loop field recovery
|
||||
let lastPart: { fields?: Record<string, unknown> } | undefined;
|
||||
|
||||
// Parse multipart parts (file parts stream to object storage)
|
||||
// Parse multipart parts (file parts stream to object storage).
|
||||
// request.parts() is the keep-alive-safe iterator from
|
||||
// lib/multipart-parts.ts (installed in plugins/upload.ts), which never
|
||||
// drops trailing parts, so no post-loop field recovery is needed.
|
||||
try {
|
||||
const parts = request.parts();
|
||||
|
||||
for await (const part of parts) {
|
||||
lastPart = part as { fields?: Record<string, unknown> };
|
||||
if (part.type === "file") {
|
||||
fileCount++;
|
||||
if (fileCount > maxInputs) {
|
||||
@@ -291,31 +291,6 @@ export function createToolRoute<T>(app: FastifyInstance, config: ToolRouteConfig
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The upstream parts iterator can terminate before yielding trailing
|
||||
// fields, but busboy has already populated part.fields on every part.
|
||||
if (lastPart?.fields) {
|
||||
const recover = (name: string): string | null => {
|
||||
const f = lastPart?.fields?.[name];
|
||||
const entry = Array.isArray(f) ? f[0] : f;
|
||||
if (entry != null && typeof (entry as { value?: unknown }).value === "string") {
|
||||
return (entry as { value: string }).value;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
if (settingsRaw === null) {
|
||||
settingsRaw = recover("settings");
|
||||
}
|
||||
if (fileId === null) {
|
||||
fileId = recover("fileId");
|
||||
}
|
||||
if (clientJobId === null) {
|
||||
const raw = recover("clientJobId");
|
||||
if (raw !== null && raw.length > 0 && raw.length <= 128) {
|
||||
clientJobId = raw;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
return reply.status(400).send({
|
||||
error: "Failed to parse multipart request",
|
||||
|
||||
@@ -13,7 +13,7 @@ interface BeforeAfterSliderProps {
|
||||
beforeSize?: number;
|
||||
/** Processed file size in bytes. */
|
||||
afterSize?: number;
|
||||
/** Initial divider position as a percentage (0–100). Defaults to 50. */
|
||||
/** Initial divider position as a percentage (0-100). Defaults to 50. */
|
||||
initialPosition?: number;
|
||||
/** Optional CSS preview layers for the "after" panel (remove-bg effects). */
|
||||
bgPreview?: BgPreviewState | null;
|
||||
@@ -213,11 +213,11 @@ export function BeforeAfterSlider({
|
||||
{/* Divider line */}
|
||||
{isMobile ? (
|
||||
<div
|
||||
className="absolute inset-x-0 h-0.5 bg-white/80 pointer-events-none"
|
||||
className="absolute inset-x-0 h-0.5 bg-white pointer-events-none shadow-[0_0_0_1px_rgba(0,0,0,0.4),0_0_6px_rgba(0,0,0,0.35)]"
|
||||
style={{ top: `${position}%`, transform: "translateY(-50%)" }}
|
||||
>
|
||||
{/* Handle grip */}
|
||||
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-8 rounded-full bg-white border-2 border-primary shadow-lg flex items-center justify-center pointer-events-none">
|
||||
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-8 rounded-full bg-white border-2 border-primary shadow-[0_0_0_1px_rgba(0,0,0,0.25),0_4px_12px_rgba(0,0,0,0.35)] flex items-center justify-center pointer-events-none">
|
||||
<svg
|
||||
width="14"
|
||||
height="14"
|
||||
@@ -245,11 +245,11 @@ export function BeforeAfterSlider({
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className="absolute top-0 bottom-0 w-0.5 bg-white/80 pointer-events-none"
|
||||
className="absolute top-0 bottom-0 w-0.5 bg-white pointer-events-none shadow-[0_0_0_1px_rgba(0,0,0,0.4),0_0_6px_rgba(0,0,0,0.35)]"
|
||||
style={{ left: `${position}%`, transform: "translateX(-50%)" }}
|
||||
>
|
||||
{/* Handle grip */}
|
||||
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-8 rounded-full bg-white border-2 border-primary shadow-lg flex items-center justify-center pointer-events-none">
|
||||
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-8 rounded-full bg-white border-2 border-primary shadow-[0_0_0_1px_rgba(0,0,0,0.25),0_4px_12px_rgba(0,0,0,0.35)] flex items-center justify-center pointer-events-none">
|
||||
<svg
|
||||
width="14"
|
||||
height="14"
|
||||
|
||||
@@ -451,12 +451,20 @@ export const EraserCanvas = forwardRef<EraserCanvasRef, EraserCanvasProps>(funct
|
||||
style={{ width: canvasSize.w, height: canvasSize.h }}
|
||||
draggable={false}
|
||||
/>
|
||||
{/* Explicit CSS size is load-bearing: the backing store (width/height
|
||||
attributes) is natural resolution, and `inset-0` alone does not
|
||||
stretch a replaced element, so without it the canvas renders at
|
||||
intrinsic size and every rect-based coordinate is misscaled. */}
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
width={renderDims.w}
|
||||
height={renderDims.h}
|
||||
className="absolute inset-0 touch-none"
|
||||
style={{ cursor: isPanMode ? "grab" : "none" }}
|
||||
style={{
|
||||
width: canvasSize.w,
|
||||
height: canvasSize.h,
|
||||
cursor: isPanMode ? "grab" : "none",
|
||||
}}
|
||||
onMouseDown={handleDown}
|
||||
onMouseMove={handleMove}
|
||||
onMouseUp={handleUp}
|
||||
|
||||
@@ -365,7 +365,7 @@ export function ToolPage() {
|
||||
const [eraserHasStrokes, setEraserHasStrokes] = useState(false);
|
||||
const [eraserBrushSize, setEraserBrushSize] = useState(30);
|
||||
const [eraserMaskedCount, setEraserMaskedCount] = useState(0);
|
||||
// Center of the painted mask as a 0-100 percentage — used to init the slider at the right spot
|
||||
// Center of the painted mask as a 0-100 percentage, used to init the slider at the erased spot
|
||||
const [eraserSliderInitPos, setEraserSliderInitPos] = useState<number | null>(null);
|
||||
|
||||
// Sign state
|
||||
@@ -596,15 +596,16 @@ export function ToolPage() {
|
||||
if (isAiTool && !toolInstalled && featureBundle) {
|
||||
return (
|
||||
<AppLayout breadcrumb={breadcrumb}>
|
||||
<div className="flex-1 overflow-y-auto bg-muted/20">
|
||||
<div className="flex items-center justify-center min-h-full">
|
||||
<FeatureInstallPrompt
|
||||
bundle={featureBundle}
|
||||
isAdmin={isAdmin}
|
||||
toolName={tool?.name}
|
||||
toolDescription={tool?.description}
|
||||
/>
|
||||
</div>
|
||||
{/* min-h-full (not flex-1): AppLayout's <main> is a block scroll
|
||||
container, so flex-1 collapses to content height and the prompt
|
||||
hugs the top instead of centering. */}
|
||||
<div className="min-h-full bg-muted/20 flex items-center justify-center py-8">
|
||||
<FeatureInstallPrompt
|
||||
bundle={featureBundle}
|
||||
isAdmin={isAdmin}
|
||||
toolName={tool?.name}
|
||||
toolDescription={tool?.description}
|
||||
/>
|
||||
</div>
|
||||
</AppLayout>
|
||||
);
|
||||
|
||||
+12
-4
@@ -283,18 +283,26 @@ RUN for i in 1 2 3; do apt-get -o Acquire::Retries=3 update && break || sleep $(
|
||||
&& pandoc --version \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Embedded-mode databases: PostgreSQL 17 (PGDG, to match the Compose postgres:17
|
||||
# major for a clean data handoff) + Redis. Shipped in every image (single tag);
|
||||
# unused in external/Compose mode, ~tens of MB against the multi-GB base. They
|
||||
# enter the Trivy CVE surface and ride the existing apt-get upgrade patching.
|
||||
# Embedded-mode databases: PostgreSQL 17 (PGDG) + Redis 8 (packages.redis.io),
|
||||
# each pinned to the same major the Compose stack runs (postgres:17 / redis:8)
|
||||
# so embedded and external deployments behave identically and data hands off
|
||||
# cleanly. Distro repos would silently downgrade Redis to 7.x. Shipped in every
|
||||
# image (single tag); unused in external/Compose mode, ~tens of MB against the
|
||||
# multi-GB base. They enter the Trivy CVE surface and ride the existing
|
||||
# apt-get upgrade patching.
|
||||
RUN install -d /usr/share/postgresql-common/pgdg \
|
||||
&& curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc \
|
||||
-o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc \
|
||||
&& curl -fsSL https://packages.redis.io/gpg \
|
||||
-o /usr/share/keyrings/redis-archive-keyring.asc \
|
||||
&& . /etc/os-release \
|
||||
&& echo "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt ${VERSION_CODENAME}-pgdg main" \
|
||||
> /etc/apt/sources.list.d/pgdg.list \
|
||||
&& echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.asc] https://packages.redis.io/deb ${VERSION_CODENAME} main" \
|
||||
> /etc/apt/sources.list.d/redis.list \
|
||||
&& for i in 1 2 3; do apt-get -o Acquire::Retries=3 update && break || sleep $((i * 15)); done \
|
||||
&& apt-get install -y --no-install-recommends postgresql-17 postgresql-client-17 redis-server \
|
||||
&& redis-server --version | grep -q 'v=8\.' \
|
||||
&& rm -f /etc/ssl/private/ssl-cert-snakeoil.key /etc/ssl/certs/ssl-cert-snakeoil.pem \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
|
||||
Generated
+3
@@ -136,6 +136,9 @@ importers:
|
||||
|
||||
apps/api:
|
||||
dependencies:
|
||||
'@fastify/busboy':
|
||||
specifier: ^3.2.0
|
||||
version: 3.2.0
|
||||
'@fastify/cookie':
|
||||
specifier: ^11.0.2
|
||||
version: 11.0.2
|
||||
|
||||
@@ -450,3 +450,64 @@ describe("Register validation", () => {
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// FORCED PASSWORD CHANGE GATE
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
describe("Forced password change gate", () => {
|
||||
// The register route leaves mustChangePassword=true; log straight in
|
||||
// without clearing it so the gate is active for the session.
|
||||
async function loginWithMustChange(): Promise<{ password: string; token: string }> {
|
||||
const username = uid();
|
||||
const password = "ValidPass1";
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/register",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { username, password, role: "admin" },
|
||||
});
|
||||
if (res.statusCode !== 201) {
|
||||
throw new Error(`register failed: ${res.statusCode} ${res.body}`);
|
||||
}
|
||||
return { password, token: await loginAs(username, password) };
|
||||
}
|
||||
|
||||
it("keeps public endpoints reachable while the flag is set", async () => {
|
||||
const { token } = await loginWithMustChange();
|
||||
// Regression: /api/v1/health returned 403 here, tripping the SPA's
|
||||
// "Reconnecting to server" banner on the forced change-password screen.
|
||||
const health = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/health",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
expect(health.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it("blocks protected endpoints until the password is changed", async () => {
|
||||
const { password, token } = await loginWithMustChange();
|
||||
|
||||
const blocked = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
expect(blocked.statusCode).toBe(403);
|
||||
expect(JSON.parse(blocked.body).code).toBe("MUST_CHANGE_PASSWORD");
|
||||
|
||||
const change = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/change-password",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { currentPassword: password, newPassword: "RotatedPass1" },
|
||||
});
|
||||
expect(change.statusCode).toBe(200);
|
||||
|
||||
const after = await testApp.app.inject({
|
||||
method: "GET",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
expect(after.statusCode).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* Integration tests for the erase-object multipart contract
|
||||
* (/api/v1/tools/image/erase-object).
|
||||
*
|
||||
* Every AI-matrix test stops at the 501 FEATURE_NOT_INSTALLED guard, so the
|
||||
* file+mask parse path behind it had no coverage. These tests mock the
|
||||
* install gate open and replay the exact multipart shape the web client
|
||||
* sends. The AI sidecar is not running in tests, so a successful parse
|
||||
* yields 202 (job enqueued); any 4xx means the request was misparsed.
|
||||
*/
|
||||
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { Agent as HttpAgent, request as httpRequest } from "node:http";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { fixtures, readFixture } from "../../../fixtures/index.js";
|
||||
import {
|
||||
buildTestApp,
|
||||
createMultipartPayload,
|
||||
loginAsAdmin,
|
||||
type TestApp,
|
||||
} from "../../test-server.js";
|
||||
|
||||
vi.mock("../../../../apps/api/src/lib/feature-status.js", async (importOriginal) => {
|
||||
const mod =
|
||||
await importOriginal<typeof import("../../../../apps/api/src/lib/feature-status.js")>();
|
||||
return { ...mod, isToolInstalled: () => true };
|
||||
});
|
||||
|
||||
const JPG = readFixture(fixtures.image.base.jpg100);
|
||||
const PNG = readFixture(fixtures.image.base.png200);
|
||||
// Large first file: widens the window in which the request stream fully
|
||||
// buffers (firing "close") while the first part is still streaming to
|
||||
// storage, which is what dropped the trailing mask part.
|
||||
const LARGE_JPG = readFixture(fixtures.image.stressLarge);
|
||||
|
||||
let testApp: TestApp;
|
||||
let app: TestApp["app"];
|
||||
let adminToken: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
testApp = await buildTestApp();
|
||||
app = testApp.app;
|
||||
adminToken = await loginAsAdmin(app);
|
||||
}, 30_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await testApp.cleanup();
|
||||
}, 10_000);
|
||||
|
||||
describe("erase-object multipart contract", () => {
|
||||
it("accepts the web client's file + mask + fields shape", async () => {
|
||||
const { body, contentType } = createMultipartPayload([
|
||||
{ name: "file", filename: "photo.jpg", contentType: "image/jpeg", content: JPG },
|
||||
{ name: "mask", filename: "mask.png", contentType: "image/png", content: PNG },
|
||||
{ name: "clientJobId", content: randomUUID() },
|
||||
{ name: "format", content: "png" },
|
||||
{ name: "quality", content: "95" },
|
||||
]);
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/tools/image/erase-object",
|
||||
headers: { authorization: `Bearer ${adminToken}`, "content-type": contentType },
|
||||
payload: body,
|
||||
});
|
||||
expect(res.statusCode, res.body).toBeLessThan(400);
|
||||
});
|
||||
|
||||
it("keeps trailing parts across reused keep-alive connections", async () => {
|
||||
// Regression for the @fastify/multipart parts() race: its iterator ends
|
||||
// on the REQUEST stream's "close", which on a warm keep-alive connection
|
||||
// fires while the first file is still streaming to storage, dropping the
|
||||
// trailing mask part. inject() cannot reproduce it (no real socket), so
|
||||
// this test runs real sequential HTTP posts over one connection. Before
|
||||
// the busboy-driven iterator fix, the second post reliably 400'd with
|
||||
// "No mask image provided".
|
||||
await app.listen({ port: 0, host: "127.0.0.1" });
|
||||
const address = app.server.address();
|
||||
const port = typeof address === "object" && address !== null ? address.port : 0;
|
||||
const agent = new HttpAgent({ keepAlive: true, maxSockets: 1 });
|
||||
|
||||
const post = (): Promise<{ status: number; body: string }> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const { body, contentType } = createMultipartPayload([
|
||||
{ name: "file", filename: "photo.jpg", contentType: "image/jpeg", content: LARGE_JPG },
|
||||
{ name: "mask", filename: "mask.png", contentType: "image/png", content: PNG },
|
||||
{ name: "clientJobId", content: randomUUID() },
|
||||
{ name: "format", content: "png" },
|
||||
{ name: "quality", content: "95" },
|
||||
]);
|
||||
const req = httpRequest(
|
||||
{
|
||||
host: "127.0.0.1",
|
||||
port,
|
||||
path: "/api/v1/tools/image/erase-object",
|
||||
method: "POST",
|
||||
agent,
|
||||
headers: {
|
||||
authorization: `Bearer ${adminToken}`,
|
||||
"content-type": contentType,
|
||||
"content-length": body.length,
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
let text = "";
|
||||
res.on("data", (chunk) => {
|
||||
text += chunk;
|
||||
});
|
||||
res.on("end", () => resolve({ status: res.statusCode ?? 0, body: text }));
|
||||
},
|
||||
);
|
||||
req.on("error", reject);
|
||||
req.end(body);
|
||||
});
|
||||
|
||||
try {
|
||||
const results = [await post(), await post(), await post()];
|
||||
for (const [i, r] of results.entries()) {
|
||||
expect(r.status, `request ${i + 1} of 3: ${r.body}`).toBeLessThan(400);
|
||||
}
|
||||
} finally {
|
||||
agent.destroy();
|
||||
}
|
||||
}, 30_000);
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* Unit tests for lib/multipart-parts.ts, the keep-alive-safe replacement for
|
||||
* @fastify/multipart's request.parts().
|
||||
*
|
||||
* The scenario that broke the plugin: the whole request body is already
|
||||
* buffered (request "end"/"close" fire immediately once piped) while the
|
||||
* consumer awaits slow storage writes between parts. The plugin's iterator
|
||||
* queued its end marker on request "close" and dropped every part emitted
|
||||
* after it; the busboy-driven iterator must deliver all parts regardless of
|
||||
* consumer pacing.
|
||||
*/
|
||||
|
||||
import { PassThrough } from "node:stream";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { multipartParts } from "../../../apps/api/src/lib/multipart-parts.js";
|
||||
|
||||
const BOUNDARY = "----UnitBoundary1234";
|
||||
|
||||
function multipartBody(
|
||||
parts: Array<{ name: string; filename?: string; content: string | Buffer }>,
|
||||
): Buffer {
|
||||
const chunks: Buffer[] = [];
|
||||
for (const part of parts) {
|
||||
let header = `--${BOUNDARY}\r\n`;
|
||||
if (part.filename) {
|
||||
header += `Content-Disposition: form-data; name="${part.name}"; filename="${part.filename}"\r\n`;
|
||||
header += "Content-Type: application/octet-stream\r\n\r\n";
|
||||
} else {
|
||||
header += `Content-Disposition: form-data; name="${part.name}"\r\n\r\n`;
|
||||
}
|
||||
chunks.push(Buffer.from(header), Buffer.from(part.content), Buffer.from("\r\n"));
|
||||
}
|
||||
chunks.push(Buffer.from(`--${BOUNDARY}--\r\n`));
|
||||
return Buffer.concat(chunks);
|
||||
}
|
||||
|
||||
/** Fake request whose raw stream has the whole body buffered up front. */
|
||||
function fakeRequest(body: Buffer): FastifyRequest {
|
||||
const raw = new PassThrough();
|
||||
Object.assign(raw, {
|
||||
headers: { "content-type": `multipart/form-data; boundary=${BOUNDARY}` },
|
||||
});
|
||||
// Whole body available immediately: "end"/"close" fire as soon as the
|
||||
// pipe drains the stream, exactly like a warm keep-alive socket.
|
||||
raw.end(body);
|
||||
return { raw } as unknown as FastifyRequest;
|
||||
}
|
||||
|
||||
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
async function drain(stream: NodeJS.ReadableStream): Promise<Buffer> {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of stream) chunks.push(chunk as Buffer);
|
||||
return Buffer.concat(chunks);
|
||||
}
|
||||
|
||||
describe("multipartParts", () => {
|
||||
it("yields every part when the consumer is slower than the body arrival", async () => {
|
||||
const body = multipartBody([
|
||||
{ name: "file", filename: "photo.jpg", content: Buffer.alloc(256 * 1024, 7) },
|
||||
{ name: "mask", filename: "mask.png", content: Buffer.alloc(8 * 1024, 9) },
|
||||
{ name: "clientJobId", content: "abc-123" },
|
||||
{ name: "format", content: "png" },
|
||||
{ name: "quality", content: "95" },
|
||||
]);
|
||||
|
||||
const seen: string[] = [];
|
||||
const sizes: Record<string, number> = {};
|
||||
for await (const part of multipartParts(fakeRequest(body))) {
|
||||
if (part.type === "file") {
|
||||
const buf = await drain(part.file);
|
||||
sizes[part.fieldname] = buf.length;
|
||||
seen.push(`file:${part.fieldname}`);
|
||||
// Slow consumer: the raw stream has long since closed by now.
|
||||
await sleep(25);
|
||||
} else {
|
||||
seen.push(`field:${part.fieldname}=${part.value}`);
|
||||
}
|
||||
}
|
||||
|
||||
expect(seen).toEqual([
|
||||
"file:file",
|
||||
"file:mask",
|
||||
"field:clientJobId=abc-123",
|
||||
"field:format=png",
|
||||
"field:quality=95",
|
||||
]);
|
||||
expect(sizes.file).toBe(256 * 1024);
|
||||
expect(sizes.mask).toBe(8 * 1024);
|
||||
});
|
||||
|
||||
it("propagates malformed multipart as an error", async () => {
|
||||
const raw = new PassThrough();
|
||||
Object.assign(raw, {
|
||||
headers: { "content-type": `multipart/form-data; boundary=${BOUNDARY}` },
|
||||
});
|
||||
raw.end(Buffer.from("this is not multipart at all"));
|
||||
const request = { raw } as unknown as FastifyRequest;
|
||||
|
||||
await expect(async () => {
|
||||
for await (const part of multipartParts(request)) {
|
||||
if (part.type === "file") await drain(part.file);
|
||||
}
|
||||
}).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -118,7 +118,7 @@ describe("registerUpload", () => {
|
||||
it("registers multipart with correct file size limit", async () => {
|
||||
uploadConfig.MAX_UPLOAD_SIZE_MB = 10;
|
||||
uploadConfig.MAX_BATCH_SIZE = 5;
|
||||
const app = { register: vi.fn().mockResolvedValue(undefined) };
|
||||
const app = { register: vi.fn().mockResolvedValue(undefined), addHook: vi.fn() };
|
||||
|
||||
await registerUpload(app as never);
|
||||
expect(app.register).toHaveBeenCalledWith(mockMultipartPlugin, {
|
||||
@@ -132,7 +132,7 @@ describe("registerUpload", () => {
|
||||
it("passes undefined for fileSize when MAX_UPLOAD_SIZE_MB is 0", async () => {
|
||||
uploadConfig.MAX_UPLOAD_SIZE_MB = 0;
|
||||
uploadConfig.MAX_BATCH_SIZE = 5;
|
||||
const app = { register: vi.fn().mockResolvedValue(undefined) };
|
||||
const app = { register: vi.fn().mockResolvedValue(undefined), addHook: vi.fn() };
|
||||
|
||||
await registerUpload(app as never);
|
||||
expect(app.register).toHaveBeenCalledWith(mockMultipartPlugin, {
|
||||
@@ -146,7 +146,7 @@ describe("registerUpload", () => {
|
||||
it("passes undefined for files when MAX_BATCH_SIZE is 0", async () => {
|
||||
uploadConfig.MAX_UPLOAD_SIZE_MB = 10;
|
||||
uploadConfig.MAX_BATCH_SIZE = 0;
|
||||
const app = { register: vi.fn().mockResolvedValue(undefined) };
|
||||
const app = { register: vi.fn().mockResolvedValue(undefined), addHook: vi.fn() };
|
||||
|
||||
await registerUpload(app as never);
|
||||
expect(app.register).toHaveBeenCalledWith(mockMultipartPlugin, {
|
||||
@@ -160,7 +160,7 @@ describe("registerUpload", () => {
|
||||
it("passes undefined for both limits when both are 0", async () => {
|
||||
uploadConfig.MAX_UPLOAD_SIZE_MB = 0;
|
||||
uploadConfig.MAX_BATCH_SIZE = 0;
|
||||
const app = { register: vi.fn().mockResolvedValue(undefined) };
|
||||
const app = { register: vi.fn().mockResolvedValue(undefined), addHook: vi.fn() };
|
||||
|
||||
await registerUpload(app as never);
|
||||
expect(app.register).toHaveBeenCalledWith(mockMultipartPlugin, {
|
||||
|
||||
@@ -641,153 +641,4 @@ describe("createToolRoute", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("multipart field recovery", () => {
|
||||
it("recovers settings from part.fields when the iterator drops trailing fields", async () => {
|
||||
const app = createMockApp();
|
||||
const id = "resize";
|
||||
createToolRoute(app as never, makeMockConfig(id));
|
||||
const handler = app.routes[apiToolPath(id)];
|
||||
const reply = createMockReply();
|
||||
|
||||
// Simulate the @fastify/multipart race: the iterator yields only the
|
||||
// file part; the settings field is present only on part.fields.
|
||||
const req = {
|
||||
parts: () => ({
|
||||
[Symbol.asyncIterator]: async function* () {
|
||||
yield {
|
||||
type: "file",
|
||||
filename: "test.png",
|
||||
file: (async function* () {
|
||||
yield Buffer.from("png-data");
|
||||
})(),
|
||||
fields: {
|
||||
settings: { value: '{"x":1}' },
|
||||
},
|
||||
};
|
||||
},
|
||||
}),
|
||||
headers: {},
|
||||
log: { warn: vi.fn(), error: vi.fn(), info: vi.fn() },
|
||||
};
|
||||
|
||||
await handler(req, reply);
|
||||
|
||||
// Settings must be recovered as {x:1}, not fall through to defaults ({})
|
||||
const enqueueCall = vi.mocked(enqueueToolJob).mock.calls[0][0];
|
||||
expect(enqueueCall.settings).toEqual({ x: 1 });
|
||||
expect(reply.send).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ jobId: expect.any(String) }),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not overwrite settings already collected from the iterator", async () => {
|
||||
const app = createMockApp();
|
||||
const id = "resize";
|
||||
createToolRoute(app as never, makeMockConfig(id));
|
||||
const handler = app.routes[apiToolPath(id)];
|
||||
const reply = createMockReply();
|
||||
|
||||
// Both the iterator and part.fields carry settings; the iterator value wins
|
||||
const req = {
|
||||
parts: () => ({
|
||||
[Symbol.asyncIterator]: async function* () {
|
||||
yield {
|
||||
type: "file",
|
||||
filename: "test.png",
|
||||
file: (async function* () {
|
||||
yield Buffer.from("png-data");
|
||||
})(),
|
||||
fields: {
|
||||
settings: { value: '{"from":"fields"}' },
|
||||
},
|
||||
};
|
||||
yield {
|
||||
type: "field",
|
||||
fieldname: "settings",
|
||||
value: '{"from":"iterator"}',
|
||||
file: (async function* () {})(),
|
||||
fields: {
|
||||
settings: { value: '{"from":"fields"}' },
|
||||
},
|
||||
};
|
||||
},
|
||||
}),
|
||||
headers: {},
|
||||
log: { warn: vi.fn(), error: vi.fn(), info: vi.fn() },
|
||||
};
|
||||
|
||||
await handler(req, reply);
|
||||
|
||||
const enqueueCall = vi.mocked(enqueueToolJob).mock.calls[0][0];
|
||||
expect(enqueueCall.settings).toEqual({ from: "iterator" });
|
||||
});
|
||||
|
||||
it("recovers fileId and clientJobId from part.fields", async () => {
|
||||
const app = createMockApp();
|
||||
const id = "resize";
|
||||
createToolRoute(app as never, makeMockConfig(id));
|
||||
const handler = app.routes[apiToolPath(id)];
|
||||
const reply = createMockReply();
|
||||
|
||||
const req = {
|
||||
parts: () => ({
|
||||
[Symbol.asyncIterator]: async function* () {
|
||||
yield {
|
||||
type: "file",
|
||||
filename: "test.png",
|
||||
file: (async function* () {
|
||||
yield Buffer.from("png-data");
|
||||
})(),
|
||||
fields: {
|
||||
settings: { value: "{}" },
|
||||
fileId: { value: "f-123" },
|
||||
clientJobId: { value: "cj-456" },
|
||||
},
|
||||
};
|
||||
},
|
||||
}),
|
||||
headers: {},
|
||||
log: { warn: vi.fn(), error: vi.fn(), info: vi.fn() },
|
||||
};
|
||||
|
||||
await handler(req, reply);
|
||||
|
||||
const enqueueCall = vi.mocked(enqueueToolJob).mock.calls[0][0];
|
||||
expect(enqueueCall.fileId).toBe("f-123");
|
||||
expect(enqueueCall.clientJobId).toBe("cj-456");
|
||||
});
|
||||
|
||||
it("handles array-form fields from part.fields", async () => {
|
||||
const app = createMockApp();
|
||||
const id = "resize";
|
||||
createToolRoute(app as never, makeMockConfig(id));
|
||||
const handler = app.routes[apiToolPath(id)];
|
||||
const reply = createMockReply();
|
||||
|
||||
const req = {
|
||||
parts: () => ({
|
||||
[Symbol.asyncIterator]: async function* () {
|
||||
yield {
|
||||
type: "file",
|
||||
filename: "test.png",
|
||||
file: (async function* () {
|
||||
yield Buffer.from("png-data");
|
||||
})(),
|
||||
fields: {
|
||||
settings: [{ value: '{"arr":true}' }],
|
||||
},
|
||||
};
|
||||
},
|
||||
}),
|
||||
headers: {},
|
||||
log: { warn: vi.fn(), error: vi.fn(), info: vi.fn() },
|
||||
};
|
||||
|
||||
await handler(req, reply);
|
||||
|
||||
const enqueueCall = vi.mocked(enqueueToolJob).mock.calls[0][0];
|
||||
expect(enqueueCall.settings).toEqual({ arr: true });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user