Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: transfer uploaded author headshots to peers via the gallery (#1327)

[._.]/ Adam Eivy1c95c562f803
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 4371728db7..3d04fdaaef 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -67,6 +67,8 @@
## Fixed
+- **[issue-1327] Uploaded (non-gallery) author headshots now transfer to federated peers.** The authors federation only shipped a headshot's image bytes when its `headshotImageUrl` pointed at `/data/images/<f>` (a gallery-picked image) — `headshotImageFilename()` maps that to the `image` asset the peer-sync pull worker fetches. But the Authors page's **upload** button routed through the generic `POST /api/uploads`, storing the file in `data/uploads/` and setting `headshotImageUrl = /api/uploads/<f>`, which is **not** a pullable asset kind — so on a peer the author record synced but the headshot 404'd. Author-headshot uploads now go through the gallery instead: a new `POST /api/image-gen/upload` saves the uploaded bytes into `data/images/` (sniffing the real format from the magic bytes — PNG/JPEG/WebP/GIF — and rejecting non-image payloads) and returns a `/data/images/<f>` URL, so the headshot rides the existing `image` pull path and its bytes reach every peer. The magic-byte sniffer is consolidated into a shared `detectImageFormat()` in `fileUtils.js` (reused by `imageClean.js`). (`server/lib/fileUtils.js`, `server/lib/imageClean.js`, `server/services/imageGen/local.js`, `server/routes/imageGen.js`, `client/src/services/apiSystem.js`, `client/src/pages/Authors.jsx`, #1327)
+
- **[issue-1319] LoRA training and video renders now survive a `pm2 restart portos-server` instead of dying mid-run.** A multi-hour LoRA training run kept dying with `SIGINT`/`KeyboardInterrupt` at the exact second portos-server restarted (it restarts routinely on the memory ceiling). Root cause: pm2's `TreeKill` walks the parent→child process tree by **PPID** and signals every descendant of portos-server on restart — and the trainer/render children were descendants. `detached: true` didn't help (it only moves the child to a new process *group*; TreeKill keys on PPID, not the group), and `treekill: false` on the app broke pm2's own reap (lingering `:5555` → EADDRINUSE crash-loop). The fix is spawn-side: a new `spawnDetached` helper (`server/lib/detachedSpawn.js`) **double-forks** the job through a pure-`sh` launcher so it reparents to init (PPID=1) and leaves pm2's tree entirely, while the server keeps streaming progress by tailing on-disk log files (`stdout`/`stderr`/exit-status). Both spawn sites adopt it — `server/services/loraTraining/index.js` (was relying on the ineffective `detached: true`) and `server/services/videoGen/local.js` (which previously had *no* detach at all, so it was fully exposed). Cancel/SIGKILL escalation, the completion watchdog, and `caffeinate` keep-awake all work unchanged (they signal the job by PID, which still reaches the reparented child); video renders clean up their `data/videos/.detached/<jobId>` scratch dir on completion. Because a surviving child outlives the server, boot reconcile now **reaps** any still-running orphan (clean `SIGTERM` so the trainer checkpoints, then `SIGKILL`) before marking its run/job failed — and `resumeTrainingRun` reaps too — so a restart becomes a clean checkpointed stop instead of a mid-op `SIGINT` crash, and a resume can never spawn a second trainer into the same checkpoint dir. (Full re-attach-and-finalize across a restart is tracked in #1332.) The raised memory ceiling + checkpoint-resume remain the safety net for the rare restart that lands in the ~1ms pre-detach window. (`server/lib/detachedSpawn.js`, `server/services/loraTraining/index.js`, `server/services/videoGen/local.js`, `server/services/mediaJobQueue/index.js`, #1319)
- **Object and place LoRA datasets can now override their Lighting/Settings variation axes in the generate-batch dialog.** The object/place LoRA feature was functional server-side (`deriveVariationAxes` applies kind-appropriate lighting/setting defaults), but `LoraDatasetDetail` hard-coded `expressionOptions`/`outfitOptions` to `[]` for non-character kinds, so `GenerateBatchDialog`'s `options.length > 0` guards were always false and the relabeled "Lighting"/"Settings" chip lists never rendered — users could only ever use the server defaults, and the per-kind relabel logic was dead code. The dataset detail now exposes the server-derived axes via a new `GET /api/lora-datasets/:id/variation-axes` endpoint, and the client seeds the chips from that vocab (instead of duplicating the object/place axis constants client-side), so the overrides flow through the existing `expressions`/`outfits` generate params. (`server/services/loraDatasetGenerate.js`, `server/routes/loraDatasets.js`, `client/src/pages/LoraDatasetDetail.jsx`, #1322)
diff --git a/client/src/pages/Authors.jsx b/client/src/pages/Authors.jsx
index e1711acb77..452d00fd61 100644
--- a/client/src/pages/Authors.jsx
+++ b/client/src/pages/Authors.jsx
@@ -18,7 +18,7 @@ import useMediaJobProgress from '../hooks/useMediaJobProgress';
import { DEFAULT_NEGATIVE_PROMPT } from '../lib/imageGenDefaults';
import { readFileAsBase64 } from '../utils/fileUpload';
import {
- listAuthors, createAuthor, updateAuthor, deleteAuthor, uploadFile, generateImage,
+ listAuthors, createAuthor, updateAuthor, deleteAuthor, uploadGalleryImage, generateImage,
AUTHOR_NAME_MAX, AUTHOR_WRITING_STYLE_MAX, AUTHOR_BIO_MAX,
AUTHOR_PHYSICAL_DESCRIPTION_MAX, AUTHOR_HEADSHOT_STYLE_MAX, AUTHOR_HEADSHOT_IMAGE_URL_MAX,
} from '../services/api';
@@ -157,7 +157,10 @@ export default function Authors() {
setUploadingHeadshot(true);
const base64 = await readFileAsBase64(file).catch(() => null);
if (!base64) { setUploadingHeadshot(false); toast.error('Could not read that file'); return; }
- const uploaded = await uploadFile(base64, file.name).catch((err) => {
+ // Route through the gallery (`/data/images/`) — NOT the generic /uploads
+ // path — so the stored headshot URL rides the `image` peer-sync asset path
+ // and the bytes actually transfer to federated peers (issue #1327).
+ const uploaded = await uploadGalleryImage(base64, { silent: true }).catch((err) => {
toast.error(err.message || 'Upload failed');
return null;
});
diff --git a/client/src/pages/Authors.test.jsx b/client/src/pages/Authors.test.jsx
index 7f9d251009..836323a936 100644
--- a/client/src/pages/Authors.test.jsx
+++ b/client/src/pages/Authors.test.jsx
@@ -10,7 +10,7 @@ vi.mock('../services/api', () => ({
createAuthor: vi.fn(),
updateAuthor: vi.fn(),
deleteAuthor: vi.fn(),
- uploadFile: vi.fn(),
+ uploadGalleryImage: vi.fn(),
generateImage: (...a) => generateImage(...a),
AUTHOR_NAME_MAX: 120,
AUTHOR_WRITING_STYLE_MAX: 4000,
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index fb7193dd51..d3c64cc485 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -208,6 +208,14 @@ export const generateAvatar = (data) => request('/image-gen/avatar', {
method: 'POST',
body: JSON.stringify(data)
});
+// Save an uploaded image into the gallery (`/data/images/`) and get back its
+// `{ filename, path }`. Use this (not the generic `uploadFile`) when the stored
+// URL must sync to peers — the `image` asset path only ships `/data/images/<f>`.
+export const uploadGalleryImage = (base64Data, options = {}) => request('/image-gen/upload', {
+ method: 'POST',
+ body: JSON.stringify({ data: base64Data }),
+ ...options,
+});
// Tools Registry
export const getToolsList = () => request('/tools');
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index 6f1955c04e..4e9626ded3 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -774,6 +774,40 @@ export function getMimeType(ext) {
return EXTENSION_MIME_MAP[ext] || 'application/octet-stream';
}
+/**
+ * Magic-byte sniff of an image buffer. The client-supplied extension / MIME is
+ * not trustworthy, so when we persist uploaded image bytes (e.g. an author
+ * headshot routed into the gallery) we derive the real format from the leading
+ * bytes. Recognises PNG, JPEG, WebP, and GIF.
+ *
+ * @param {Buffer} buf - Raw decoded image bytes
+ * @returns {{ format: 'png'|'jpeg'|'webp'|'gif', ext: string, mime: string } | null}
+ * The detected format with its canonical extension + MIME, or null when the
+ * bytes don't match a known image signature.
+ */
+export function detectImageFormat(buf) {
+ if (!Buffer.isBuffer(buf)) return null;
+ if (buf.length >= 8 &&
+ buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47 &&
+ buf[4] === 0x0d && buf[5] === 0x0a && buf[6] === 0x1a && buf[7] === 0x0a) {
+ return { format: 'png', ext: '.png', mime: 'image/png' };
+ }
+ if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) {
+ return { format: 'jpeg', ext: '.jpg', mime: 'image/jpeg' };
+ }
+ if (buf.length >= 12 &&
+ buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 &&
+ buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50) {
+ return { format: 'webp', ext: '.webp', mime: 'image/webp' };
+ }
+ if (buf.length >= 6 &&
+ buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x38 &&
+ (buf[4] === 0x37 || buf[4] === 0x39) && buf[5] === 0x61) {
+ return { format: 'gif', ext: '.gif', mime: 'image/gif' };
+ }
+ return null;
+}
+
/**
* Get a file's extension, normalised to lowercase with a leading dot.
* Returns null when the filename has no extension.
diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.js
index cc74ecd384..0cac3c7058 100644
--- a/server/lib/fileUtils.test.js
+++ b/server/lib/fileUtils.test.js
@@ -33,6 +33,7 @@ import {
sanitizeFilename,
getFileExtension,
getMimeType,
+ detectImageFormat,
EXTENSION_MIME_MAP,
ATTACHMENT_ALLOWED_EXTENSIONS,
} from './fileUtils.js';
@@ -893,3 +894,47 @@ describe('ATTACHMENT_ALLOWED_EXTENSIONS', () => {
}
});
});
+
+describe('detectImageFormat', () => {
+ const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00]);
+ const JPEG = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10]);
+ const WEBP = Buffer.from([0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50]);
+ const GIF87 = Buffer.from([0x47, 0x49, 0x46, 0x38, 0x37, 0x61, 0x00]);
+ const GIF89 = Buffer.from([0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x00]);
+
+ it('detects PNG', () => {
+ expect(detectImageFormat(PNG)).toEqual({ format: 'png', ext: '.png', mime: 'image/png' });
+ });
+
+ it('detects JPEG', () => {
+ expect(detectImageFormat(JPEG)).toEqual({ format: 'jpeg', ext: '.jpg', mime: 'image/jpeg' });
+ });
+
+ it('detects WebP', () => {
+ expect(detectImageFormat(WEBP)).toEqual({ format: 'webp', ext: '.webp', mime: 'image/webp' });
+ });
+
+ it('detects both GIF variants', () => {
+ expect(detectImageFormat(GIF87)?.format).toBe('gif');
+ expect(detectImageFormat(GIF89)?.format).toBe('gif');
+ });
+
+ it('returns null for non-image bytes', () => {
+ expect(detectImageFormat(Buffer.from('not an image'))).toBeNull();
+ });
+
+ it('returns null for a RIFF container that is not WebP', () => {
+ // RIFF header but "AVI " instead of "WEBP" at offset 8.
+ const avi = Buffer.from([0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x41, 0x56, 0x49, 0x20]);
+ expect(detectImageFormat(avi)).toBeNull();
+ });
+
+ it('returns null for a truncated/too-short buffer', () => {
+ expect(detectImageFormat(Buffer.from([0x89, 0x50]))).toBeNull();
+ });
+
+ it('returns null for a non-Buffer input', () => {
+ expect(detectImageFormat('AAAA')).toBeNull();
+ expect(detectImageFormat(null)).toBeNull();
+ });
+});
diff --git a/server/lib/imageClean.js b/server/lib/imageClean.js
index 92ecc120d0..bfd17a9bd9 100644
--- a/server/lib/imageClean.js
+++ b/server/lib/imageClean.js
@@ -14,7 +14,7 @@
import sharp from 'sharp';
import { basename } from 'node:path';
import { ServerError } from './errorHandler.js';
-import { tryReadFile, safeJSONParse, atomicWrite } from './fileUtils.js';
+import { tryReadFile, safeJSONParse, atomicWrite, detectImageFormat } from './fileUtils.js';
/**
* Read cleaner flags off a per-mode settings record. Pure: no I/O, no
@@ -59,21 +59,11 @@ export const CLEAN_LEVELS = ['aggressive'];
// Magic-byte sniff so we re-encode as the source format and emit the right
// MIME type — extension/header is supplied by the client and not trustworthy.
+// Delegates to the shared sniffer in fileUtils; cleaning only handles the three
+// formats sharp re-encodes here, so a detected GIF is treated as unsupported.
function detectFormat(buf) {
- if (buf.length >= 8 &&
- buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47 &&
- buf[4] === 0x0d && buf[5] === 0x0a && buf[6] === 0x1a && buf[7] === 0x0a) {
- return 'png';
- }
- if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) {
- return 'jpeg';
- }
- if (buf.length >= 12 &&
- buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 &&
- buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50) {
- return 'webp';
- }
- return null;
+ const format = detectImageFormat(buf)?.format ?? null;
+ return format === 'gif' ? null : format;
}
// PNG chunk type bytes must be ASCII letters per the PNG spec (RFC 2083 §3.2).
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 2beda4f323..ed56037a40 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -167,6 +167,14 @@ const avatarSchema = z.object({
prompt: z.string().max(2000).optional(),
});
+// Upload a user-supplied image straight into the gallery (`data/images/`) so it
+// rides the existing `image` peer-sync asset path. `data` is base64 (no data:
+// URI prefix); the real format is sniffed server-side, so the schema only caps
+// the encoded string length (~16MB decoded ≈ 21.8M base64 chars).
+const uploadImageSchema = z.object({
+ data: z.string().min(1).max(24 * 1024 * 1024),
+});
+
// SynthID-defeat regen (issue #912). Body is optional — every field defaults
// server-side (strength → DEFAULT_REGEN_STRENGTH, steps → the model default,
// prompt → empty for minimal mutation). An empty/whitespace `prompt` is treated
@@ -334,6 +342,15 @@ router.post('/avatar', asyncHandler(async (req, res) => {
res.json(await imageGen.generateAvatar(data));
}));
+// Save an uploaded image into the gallery dir so callers (e.g. author
+// headshots) get a `/data/images/<f>` URL that the peer-sync `image` asset
+// path can transfer — unlike `/api/uploads/<f>`, which is not a pullable
+// asset kind and 404s on a peer.
+router.post('/upload', asyncHandler(async (req, res) => {
+ const { data } = validateRequest(uploadImageSchema, req.body);
+ res.json(await local.saveUploadedGalleryImage(data));
+}));
+
// Local-only: list image models and LoRAs the local backend can use.
router.get('/models', (_req, res) => {
res.json(local.listImageModels());
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index 6f592841fe..735dd6d4d0 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -35,6 +35,7 @@ vi.mock('../services/imageGen/index.js', () => ({
deleteImage: vi.fn(async () => ({ ok: true })),
assertGalleryFilename: vi.fn(),
readImageSidecar: vi.fn(async () => ({ path: '', metadata: {} })),
+ saveUploadedGalleryImage: vi.fn(async () => ({ filename: 'upload-abcd1234.png', path: '/data/images/upload-abcd1234.png' })),
},
}));
@@ -539,6 +540,35 @@ describe('Image Gen Routes', () => {
});
});
+ describe('POST /api/image-gen/upload', () => {
+ it('saves uploaded bytes into the gallery and returns a /data/images path', async () => {
+ imageGen.local.saveUploadedGalleryImage.mockResolvedValue({
+ filename: 'upload-deadbeef.png',
+ path: '/data/images/upload-deadbeef.png',
+ });
+
+ const response = await request(app)
+ .post('/api/image-gen/upload')
+ .send({ data: Buffer.from('fake-png-bytes').toString('base64') });
+
+ expect(response.status).toBe(200);
+ expect(response.body.path).toBe('/data/images/upload-deadbeef.png');
+ // The service receives the raw base64 string (route doesn't pre-decode).
+ expect(imageGen.local.saveUploadedGalleryImage).toHaveBeenCalledWith(
+ Buffer.from('fake-png-bytes').toString('base64'),
+ );
+ });
+
+ it('rejects a missing data field with 400', async () => {
+ const response = await request(app)
+ .post('/api/image-gen/upload')
+ .send({});
+
+ expect(response.status).toBe(400);
+ expect(imageGen.local.saveUploadedGalleryImage).not.toHaveBeenCalled();
+ });
+ });
+
// GET /:jobId/events and POST /cancel both go through the dispatcher's
// attachSseClient/cancel — these tests lock in that contract so a future
// refactor can't accidentally re-couple them to the local provider.
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index a7974f5636..74ad4ddb49 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -19,7 +19,7 @@ import { existsSync, watch as fsWatch } from 'fs';
import { join, dirname, resolve as resolvePath, sep as PATH_SEP, basename } from 'path';
import { tmpdir } from 'os';
import { randomUUID } from 'crypto';
-import { assertSafeFilename, ensureDir, listDirectoryByExtension, PATHS, safeJSONParse, resolveGalleryImage, resolveImageInputPath, tryReadFile } from '../../lib/fileUtils.js';
+import { assertSafeFilename, detectImageFormat, ensureDir, listDirectoryByExtension, PATHS, safeJSONParse, resolveGalleryImage, resolveImageInputPath, tryReadFile } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { autoCleanGeneratedImage } from '../../lib/imageClean.js';
import { imageGenEvents } from '../imageGenEvents.js';
@@ -831,6 +831,43 @@ export async function readImageSidecar(filename) {
return { path: portosSidecar, metadata: {} };
}
+// Cap on uploaded gallery image bytes (decoded). Headshots and similar
+// uploads never need more than a few MB; this is a defense-in-depth ceiling so
+// a hand-crafted request can't write an arbitrarily large file into the
+// gallery dir. The Authors page caps its own headshot upload well below this.
+const MAX_GALLERY_UPLOAD_BYTES = 16 * 1024 * 1024;
+
+/**
+ * Persist user-uploaded image bytes (base64) into the gallery dir under
+ * `data/images/` so the file rides the existing `image` peer-sync asset path
+ * (a record pointing at `/data/images/<f>` ships its bytes to peers; a
+ * `/api/uploads/<f>` path does not). The real format is sniffed from the
+ * leading bytes — the client-supplied name/extension is not trusted — and a
+ * non-image payload is rejected with a 400. Returns the bare gallery filename
+ * and its `/data/images/` mount path for the caller to store on the record.
+ *
+ * @param {string} base64Data - Raw base64 (no data: URI prefix) image bytes
+ * @returns {Promise<{ filename: string, path: string }>}
+ */
+export async function saveUploadedGalleryImage(base64Data) {
+ const buffer = Buffer.from(base64Data, 'base64');
+ if (buffer.length === 0) {
+ throw new ServerError('Empty image upload', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ if (buffer.length > MAX_GALLERY_UPLOAD_BYTES) {
+ throw new ServerError(`Image exceeds maximum size of ${MAX_GALLERY_UPLOAD_BYTES / 1024 / 1024}MB`, { status: 400, code: 'FILE_TOO_LARGE' });
+ }
+ const detected = detectImageFormat(buffer);
+ if (!detected) {
+ throw new ServerError('Unsupported image format (expected PNG, JPEG, WebP, or GIF)', { status: 400, code: 'UNSUPPORTED_IMAGE' });
+ }
+ const filename = `upload-${randomUUID().slice(0, 8)}${detected.ext}`;
+ await ensureDir(PATHS.images);
+ await writeFile(join(PATHS.images, filename), buffer);
+ console.log(`📥 Saved uploaded gallery image: ${filename} (${(buffer.length / 1024).toFixed(0)}KB, ${detected.mime})`);
+ return { filename, path: `/data/images/${filename}` };
+}
+
export async function listGallery() {
if (!existsSync(PATHS.images)) return [];
// requireRegularFile:false preserves the original gallery behavior — it
diff --git a/server/services/imageGen/saveUploadedGalleryImage.test.js b/server/services/imageGen/saveUploadedGalleryImage.test.js
new file mode 100644
index 0000000000..5cb10f13c5
--- /dev/null
+++ b/server/services/imageGen/saveUploadedGalleryImage.test.js
@@ -0,0 +1,76 @@
+import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest';
+import { mkdtempSync, rmSync, existsSync, readFileSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { makePathsProxy } from '../../lib/mockPathsDataRoot.js';
+
+// Redirect PATHS.images at a per-test temp dir so saving an uploaded image
+// writes into the temp gallery, not the repo's real data/images.
+let imagesDir;
+vi.mock('../../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../../lib/fileUtils.js');
+ return makePathsProxy(actual, {
+ dataRoot: () => imagesDir, // unused root; images override below is what matters
+ extraOverrides: () => ({ images: imagesDir }),
+ });
+});
+
+// local.js imports pythonSetup at load; stub it so the module loads without
+// resolving a real venv (mirrors local.test.js).
+vi.mock('../../lib/pythonSetup.js', () => ({
+ resolveFlux2Python: () => null,
+ FLUX2_VENV_DEFAULT: '/fake/home/.portos/venv-flux2/bin/python3',
+}));
+
+let tmpRoot;
+let priorRegistryEnv;
+let saveUploadedGalleryImage;
+
+const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00]);
+const GIF = Buffer.from([0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x00, 0x00]);
+
+beforeAll(async () => {
+ tmpRoot = mkdtempSync(join(tmpdir(), 'portos-gallery-upload-test-'));
+ imagesDir = join(tmpRoot, 'images');
+ priorRegistryEnv = process.env.PORTOS_MEDIA_MODELS_FILE;
+ process.env.PORTOS_MEDIA_MODELS_FILE = join(tmpRoot, 'media-models.json');
+ vi.resetModules();
+ ({ saveUploadedGalleryImage } = await import('./local.js'));
+});
+
+afterAll(() => {
+ if (priorRegistryEnv === undefined) delete process.env.PORTOS_MEDIA_MODELS_FILE;
+ else process.env.PORTOS_MEDIA_MODELS_FILE = priorRegistryEnv;
+ rmSync(tmpRoot, { recursive: true, force: true });
+});
+
+describe('saveUploadedGalleryImage', () => {
+ it('writes PNG bytes into the gallery and returns a /data/images path', async () => {
+ const { filename, path } = await saveUploadedGalleryImage(PNG.toString('base64'));
+ expect(filename).toMatch(/^upload-[0-9a-f]{8}\.png$/);
+ expect(path).toBe(`/data/images/${filename}`);
+ expect(existsSync(join(imagesDir, filename))).toBe(true);
+ expect(readFileSync(join(imagesDir, filename))).toEqual(PNG);
+ });
+
+ it('derives the extension from the real bytes, not a client filename', async () => {
+ const { filename } = await saveUploadedGalleryImage(GIF.toString('base64'));
+ expect(filename.endsWith('.gif')).toBe(true);
+ });
+
+ it('rejects an empty upload with a 400', async () => {
+ await expect(saveUploadedGalleryImage('')).rejects.toMatchObject({ status: 400 });
+ });
+
+ it('rejects non-image bytes with a 400', async () => {
+ await expect(
+ saveUploadedGalleryImage(Buffer.from('definitely not an image').toString('base64')),
+ ).rejects.toMatchObject({ status: 400, code: 'UNSUPPORTED_IMAGE' });
+ });
+
+ it('rejects an oversized upload with a 400', async () => {
+ // 17MB of zero bytes — over the 16MB ceiling, and not a valid image header.
+ const huge = Buffer.alloc(17 * 1024 * 1024).toString('base64');
+ await expect(saveUploadedGalleryImage(huge)).rejects.toMatchObject({ status: 400, code: 'FILE_TOO_LARGE' });
+ });
+});