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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: extract shared localImageFilename helper across persona/project resolvers (#1640)
[._.]/ Adam Eivy893fed5d846e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d60fb1bb74..e6ed45eb0b 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -145,4 +145,5 @@## Internal+- **[issue-1640] Extracted the duplicated gallery-image filename resolver into one shared `server/lib/localImageFilename.js` helper.** Four federated-record domains each carried a byte-identical copy of the "resolve a stored image reference to its bare `data/images/` filename (or null for empty/external-URL/non-image-path)" logic that the peer-sync asset pipeline relies on — `headshotImageFilename` (authors), `portraitImageFilename` (artists), `coverImageFilename` (albums), and `startingImageFilename` (Creative Director projects). They now all delegate to a single `localImageFilename(urlOrPath)` (barrelled + cataloged per the module-organization rule); each domain keeps its named export as a thin wrapper so the imports `peerSync.js` relies on are unchanged. Pure-function refactor, no behavior change; the new helper is unit-tested and each domain's existing `logic.test.js` still pins the wrapper behavior. (`server/lib/localImageFilename.js`, `server/services/{authors,artists,albums,creativeDirector}/`)- **[issue-1524] Renumbered the duplicate `121-comic-script-visible-text-prompt` migration to `126`.** A rebase had landed two migration files numbered 121 (`121-codex-tui-bypass-sandbox` and `121-comic-script-visible-text-prompt`) on main. Both still applied exactly once (migrations are keyed by full filename, not number), so this was cosmetic — but the duplicate number muddied log/sort order. Renamed the comic-script one to the next free number; it's an idempotent hash-driven prompt-replace, so installs that already applied it re-run it harmlessly as a no-op. (`scripts/migrations/126-comic-script-visible-text-prompt.js`)diff --git a/server/lib/README.md b/server/lib/README.mdindex 9077d1d2a1..dd631e1a3c 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -111,6 +111,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `fileWriteQueue.js` | Single-tail promise chain for serializing writes to a file. || `imageClean.js` | `cleanImageBuffer` (sharp-based denoise + C2PA strip) + `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer`. || `imageWatermark.js` | `removeCornerWatermark` (erases the visible Gemini/Nano-Banana bottom-right ✦ via dependency-free harmonic/Laplace inpaint) + pure helpers `resolveWatermarkRegion` / `inpaintRegion`. Distinct from SynthID regen — this targets the *visible* corner logo. |+| `localImageFilename.js` | `localImageFilename(urlOrPath)` resolves a stored image reference to the bare gallery-image filename under `data/images/` (or null for empty/external-URL/non-image-path) — the unit the peer-sync asset pipeline hashes + transfers. Single source of truth for the authors/artists/albums/Creative-Director filename resolvers (`headshotImageFilename`/`portraitImageFilename`/`coverImageFilename`/`startingImageFilename` are thin wrappers). || `multipart.js` | Streaming multipart/form-data parser. || `safetensors.js` | `readSafetensorsHeader(path)` reads only the JSON header of a `.safetensors` file (never the tensor payload). `detectFlux2VariantFromHeader(header)` / `detectFlux2Variant(path)` classify a LoRA as FLUX.2 Klein `'4b'` (hidden dim 3072) vs `'9b'` (4096) by transformer-block tensor shapes, so the LoRA picker can hide off-variant weights that would silently fail to load. || `pdfImageEmbed.js` | PDF image embed helpers for comic / volume PDFs. |diff --git a/server/lib/index.js b/server/lib/index.jsindex d18f69c061..a574c660f0 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -105,6 +105,7 @@ export * from './fileWriteQueue.js';export * from './schemaVersions.js';export * from './imageClean.js';export * from './imageWatermark.js';+export * from './localImageFilename.js';export * from './multipart.js';export * from './safetensors.js';export * from './assetHash.js';diff --git a/server/lib/localImageFilename.js b/server/lib/localImageFilename.jsnew file mode 100644index 0000000000..9cb02baaf6--- /dev/null+++ b/server/lib/localImageFilename.js@@ -0,0 +1,45 @@+// Shared resolver for "is this a local gallery image, and what's its filename?"+//+// Several federated-record domains (authors `headshotImageUrl`, artists+// `portraitImageUrl`, albums `coverImageUrl`, Creative Director projects+// `startingImageFile`) need to reduce a stored image reference to the bare+// filename under `data/images/` that the peer-sync asset pipeline hashes ++// transfers. They all carried a byte-identical copy of this logic; this is the+// single source of truth they re-export thin wrappers around.+//+// Contract: return the basename of a local gallery image, or `null` when there+// is nothing local to ship —+// - empty / non-string input,+// - an external URL (`http(s)://…`, `data:`, `blob:`) the receiver fetches+// itself (we don't proxy third-party bytes),+// - any non-`/data/images/` absolute path (videos, `image-refs`, etc. — those+// federate through their own manifests).+// A leading `/data/images/` mount prefix or a bare filename both reduce to the+// basename. Path-traversal scrubbing happens downstream in+// `sanitizeAssetFilename`; here we only decide IS-this-a-local-image + basename.++const isStr = (v) => typeof v === 'string';++/**+ * Resolve a stored image URL/path to the bare gallery-image filename under+ * `data/images/`, or null when there's nothing local to ship.+ *+ * @param {unknown} urlOrPath - a stored image reference (URL, mount path, or bare filename)+ * @returns {string|null}+ */+export function localImageFilename(urlOrPath) {+ if (!isStr(urlOrPath)) return null;+ const url = urlOrPath.trim();+ if (!url) return null;+ if (/^(https?:|data:|blob:)/i.test(url)) return null;+ // Only gallery images sync as assets. Accept the canonical mount path or a+ // bare filename; reject any other absolute path (videos, image-refs, etc.).+ let name = url;+ const imagesPrefix = '/data/images/';+ if (url.startsWith(imagesPrefix)) name = url.slice(imagesPrefix.length);+ else if (url.startsWith('/')) return null; // some other absolute path → not a gallery image+ // Strip any querystring/hash a stored URL might carry, then take the basename.+ name = name.split(/[?#]/)[0];+ const base = name.split('/').pop();+ return base || null;+}diff --git a/server/lib/localImageFilename.test.js b/server/lib/localImageFilename.test.jsnew file mode 100644index 0000000000..30ee8330a3--- /dev/null+++ b/server/lib/localImageFilename.test.js@@ -0,0 +1,49 @@+import { describe, it, expect } from 'vitest';+import { localImageFilename } from './localImageFilename.js';++describe('localImageFilename', () => {+ it('returns null for non-string / empty input', () => {+ expect(localImageFilename(undefined)).toBe(null);+ expect(localImageFilename(null)).toBe(null);+ expect(localImageFilename(42)).toBe(null);+ expect(localImageFilename('')).toBe(null);+ expect(localImageFilename(' ')).toBe(null);+ });++ it('rejects external URLs (the receiver fetches those itself)', () => {+ expect(localImageFilename('https://example.com/a.png')).toBe(null);+ expect(localImageFilename('http://example.com/a.png')).toBe(null);+ expect(localImageFilename('HTTPS://EXAMPLE.com/a.png')).toBe(null);+ expect(localImageFilename('data:image/png;base64,AAAA')).toBe(null);+ expect(localImageFilename('blob:http://x/abc')).toBe(null);+ });++ it('strips the /data/images/ mount prefix to the basename', () => {+ expect(localImageFilename('/data/images/photo.png')).toBe('photo.png');+ expect(localImageFilename('/data/images/nested/photo.png')).toBe('photo.png');+ });++ it('accepts a bare filename', () => {+ expect(localImageFilename('photo.png')).toBe('photo.png');+ });++ it('rejects any other absolute path (videos, image-refs, etc.)', () => {+ expect(localImageFilename('/data/videos/clip.mp4')).toBe(null);+ expect(localImageFilename('/data/image-refs/ref.png')).toBe(null);+ expect(localImageFilename('/etc/passwd')).toBe(null);+ });++ it('strips querystring / hash before taking the basename', () => {+ expect(localImageFilename('/data/images/photo.png?v=2')).toBe('photo.png');+ expect(localImageFilename('photo.png#frag')).toBe('photo.png');+ expect(localImageFilename('/data/images/photo.png?a=1#b')).toBe('photo.png');+ });++ it('trims surrounding whitespace', () => {+ expect(localImageFilename(' /data/images/photo.png ')).toBe('photo.png');+ });++ it('returns null when the basename collapses to empty', () => {+ expect(localImageFilename('/data/images/')).toBe(null);+ });+});diff --git a/server/services/albums/logic.js b/server/services/albums/logic.jsindex aef82d5fa1..f1a1bbcbf4 100644--- a/server/services/albums/logic.js+++ b/server/services/albums/logic.js@@ -24,6 +24,7 @@*/import { compareNewerWins } from '../../lib/lwwTimestamp.js';+import { localImageFilename } from '../../lib/localImageFilename.js';export const ALBUM_ID_RE = /^album-[A-Za-z0-9-]{1,64}$/;@@ -94,21 +95,11 @@ export function sanitizeAlbum(raw) {/*** Resolve an album's `coverImageUrl` to the bare gallery-image filename under- * `data/images/` for peer-sync asset transfer. Returns null when- * there's nothing local to ship. Mirrors artists' portraitImageFilename.+ * `data/images/` for peer-sync asset transfer. Thin wrapper over the shared+ * `localImageFilename` helper (the named export is what `peerSync.js` imports).*/export function coverImageFilename(coverImageUrl) {- if (!isStr(coverImageUrl)) return null;- const url = coverImageUrl.trim();- if (!url) return null;- if (/^(https?:|data:|blob:)/i.test(url)) return null;- let name = url;- const imagesPrefix = '/data/images/';- if (url.startsWith(imagesPrefix)) name = url.slice(imagesPrefix.length);- else if (url.startsWith('/')) return null;- name = name.split(/[?#]/)[0];- const base = name.split('/').pop();- return base || null;+ return localImageFilename(coverImageUrl);}/** Build a fresh album record from create input. */diff --git a/server/services/artists/logic.js b/server/services/artists/logic.jsindex 77d74df850..d7ee3b1082 100644--- a/server/services/artists/logic.js+++ b/server/services/artists/logic.js@@ -25,6 +25,7 @@*/import { compareNewerWins } from '../../lib/lwwTimestamp.js';+import { localImageFilename } from '../../lib/localImageFilename.js';export const ARTIST_ID_RE = /^artist-[A-Za-z0-9-]{1,64}$/;@@ -72,21 +73,11 @@ export function sanitizeArtist(raw) {/*** Resolve an artist's `portraitImageUrl` to the bare gallery-image filename that* lives under `data/images/` — the unit the peer-sync asset pipeline hashes +- * transfers. Returns null when there's nothing local to ship (empty,- * external URL, or a non-image path). Mirrors authors' headshotImageFilename.+ * transfers. Thin wrapper over the shared `localImageFilename` helper (the named+ * export is what `peerSync.js` imports).*/export function portraitImageFilename(portraitImageUrl) {- if (!isStr(portraitImageUrl)) return null;- const url = portraitImageUrl.trim();- if (!url) return null;- if (/^(https?:|data:|blob:)/i.test(url)) return null;- let name = url;- const imagesPrefix = '/data/images/';- if (url.startsWith(imagesPrefix)) name = url.slice(imagesPrefix.length);- else if (url.startsWith('/')) return null; // some other absolute path → not a gallery image- name = name.split(/[?#]/)[0];- const base = name.split('/').pop();- return base || null;+ return localImageFilename(portraitImageUrl);}/** Build a fresh artist record from create input. */diff --git a/server/services/authors/logic.js b/server/services/authors/logic.jsindex ff458cdcca..af1dd07f69 100644--- a/server/services/authors/logic.js+++ b/server/services/authors/logic.js@@ -25,6 +25,7 @@*/import { compareNewerWins } from '../../lib/lwwTimestamp.js';+import { localImageFilename } from '../../lib/localImageFilename.js';export const AUTHOR_ID_RE = /^auth-[A-Za-z0-9-]{1,64}$/;@@ -70,30 +71,11 @@ export function sanitizeAuthor(raw) {/*** Resolve an author's `headshotImageUrl` to the bare gallery-image filename* that lives under `data/images/` — the unit the peer-sync asset pipeline can- * hash + transfer. Returns null when there's nothing local to ship:- * - empty / non-string,- * - an external URL (`http(s)://…`, `data:…`) — the receiver fetches that- * itself; we don't proxy third-party bytes,- * - a non-image path (e.g. `/data/videos/…`) — headshots are always images.- * A leading `/data/images/` mount prefix or a bare filename both reduce to the- * basename. Path-traversal scrubbing happens downstream in- * `sanitizeAssetFilename`; here we only decide IS-this-a-local-image + basename.+ * hash + transfer. Thin wrapper over the shared `localImageFilename` helper+ * (the named export is what `peerSync.js` imports).*/export function headshotImageFilename(headshotImageUrl) {- if (!isStr(headshotImageUrl)) return null;- const url = headshotImageUrl.trim();- if (!url) return null;- if (/^(https?:|data:|blob:)/i.test(url)) return null;- // Only gallery images sync as assets. Accept the canonical mount path or a- // bare filename; reject any other absolute path (videos, image-refs, etc.).- let name = url;- const imagesPrefix = '/data/images/';- if (url.startsWith(imagesPrefix)) name = url.slice(imagesPrefix.length);- else if (url.startsWith('/')) return null; // some other absolute path → not a gallery image- // Strip any querystring/hash a stored URL might carry, then take the basename.- name = name.split(/[?#]/)[0];- const base = name.split('/').pop();- return base || null;+ return localImageFilename(headshotImageUrl);}/** Build a fresh author record from create input. */diff --git a/server/services/creativeDirector/projectsLogic.js b/server/services/creativeDirector/projectsLogic.jsindex eb5730471b..944e5e0b64 100644--- a/server/services/creativeDirector/projectsLogic.js+++ b/server/services/creativeDirector/projectsLogic.js@@ -16,6 +16,7 @@ import { creativeDirectorTreatmentSchema } from '../../lib/validation.js';import { PROJECT_STATUSES } from '../../lib/creativeDirectorPresets.js';import { compareNewerWins } from '../../lib/lwwTimestamp.js';import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';+import { localImageFilename } from '../../lib/localImageFilename.js';const isStr = (v) => typeof v === 'string';@@ -122,25 +123,13 @@ export function buildProjectRecord(input, { id, now, collectionId }) {/*** Resolve a project's `startingImageFile` to the bare gallery-image filename* under `data/images/` so the peer-sync asset pipeline can hash + transfer it.- * Mirrors `headshotImageFilename` in services/authors/logic.js: returns null for- * an empty/non-string value, an external URL (`http(s)://…`, `data:`, `blob:`),- * or any non-images absolute path — the receiver resolves those itself. Scene- * video renders are NOT covered here: they live in the project's linked media- * collection, which federates as its own record (so its bytes ride that- * collection's manifest). This covers only the project's direct image input.+ * Thin wrapper over the shared `localImageFilename` helper. Scene video renders+ * are NOT covered here: they live in the project's linked media collection,+ * which federates as its own record (so its bytes ride that collection's+ * manifest). This covers only the project's direct image input.*/export function startingImageFilename(startingImageFile) {- if (!isStr(startingImageFile)) return null;- const url = startingImageFile.trim();- if (!url) return null;- if (/^(https?:|data:|blob:)/i.test(url)) return null;- let name = url;- const imagesPrefix = '/data/images/';- if (url.startsWith(imagesPrefix)) name = url.slice(imagesPrefix.length);- else if (url.startsWith('/')) return null; // some other absolute path → not a gallery image- name = name.split(/[?#]/)[0];- const base = name.split('/').pop();- return base || null;+ return localImageFilename(startingImageFile);}/**