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
feat(sharing): content-addressed asset blobs in share buckets (#301)
[._.]/ Adam Eivy8aa01291ba33
diff --git a/DONE.md b/DONE.mdindex 3fde88f3bd..5f04b2ce99 100644--- a/DONE.md+++ b/DONE.md@@ -8,6 +8,10 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./## 2026-05+### 2026-05-18++- **[content-addressed-asset-dedup-today-asset-copies] Content-addressed asset dedup.** Share-bucket asset blobs are now stored content-addressed at `<bucket>/assets/blobs/<sha256>` (sidecar metadata at `<sha256>.metadata.json`) instead of filename-addressed at `assets/{images,videos}/<filename>`. Two manifests referencing identical bytes under different filenames now share one on-disk blob — every additional reference is a no-op file-existence check on the same hash. New shared helper `sha256File` in `server/lib/fileUtils.js` (one-shot < 512 KB / streaming ≥ 512 KB); `server/services/backup.js#generateManifest` migrated to the same helper (its inline reimplementation deleted). Path/sidecar helpers (`bucketBlobsDir`, `bucketBlobPath`, `bucketBlobSidecarPath`, `imageSidecarName`, `IMAGE_EXT_RE`) live in `server/services/sharing/buckets.js` so storage-layout changes touch one file. `exporter.js#copyAssetIfPresent` computes the hash and returns `{ kind, ref, hash }` per asset; `importer.js#copyAssetsLocally` resolves bucket paths via a `resolveBucketAssetPaths` helper that prefers `assets/blobs/<hash>` when present and falls back to legacy `assets/{kind}/<filename>` for v1 manifests still in-bucket. `SHARING_SCHEMA_VERSION` bumped 1 → 2; bucket layout adds `assets/blobs/` in `ensureBucketLayout`. `annotationsSync.js#listBucketAssetKeys` now derives the user-facing filename set by scanning manifests' `assetRefs` (with the legacy dir scan retained as a fall-through for v1 buckets). Coverage: 4 new unit tests in `fileUtils.test.js` (small/large split, cross-path identical-bytes equality, distinct-bytes inequality) + 2 new integration tests in `integration.test.js` (two manifests with different filenames + identical bytes share one blob and import cleanly; v1 manifest without `hash` field still imports via legacy path) + updated existing integration assertions to expect `assets/blobs/<hash>` paths. All 249 server test files / 5452 tests pass. Two performance follow-ups captured in PLAN.md: per-source hash caching on the exporter, and per-bucket manifest-scan caching on the annotation flush path.+### 2026-05-17- **[extract-upsertbyidprepend-helper-universe-builder] Extract `upsertByIdPrepend(list, item)` helper.** New `client/src/lib/upsertByIdPrepend.js` collapses the "filter-by-id then prepend" worlds-list upsert into one helper. The PLAN line called out 3 sites; the actual count was 7 — all collapsed to `setWorlds((prev) => upsertByIdPrepend(prev, entity))`: 1 in `client/src/hooks/useUniverseAction.js` (LLM-action result merge) + 6 in `client/src/pages/UniverseBuilder.jsx` (`handleCreate`, `handleSave`, expand auto-save, refine auto-save, `handleMoveCategoryToTrunk`, `handleGenerateInCategory`). 4 new vitest cases in `upsertByIdPrepend.test.js` (new-id prepend, id replacement, empty-list, no input mutation).diff --git a/PLAN.md b/PLAN.mdindex ac7e0bbcf5..6d08fc1cc0 100644--- a/PLAN.md+++ b/PLAN.md@@ -12,7 +12,6 @@ _Nothing currently parked — pick the next item from the Backlog._### Sharing-- [ ] [content-addressed-asset-dedup-today-asset-copies] **Content-addressed asset dedup.** Today asset copies skip-if-filename-exists. Hash-based dedup would let multiple manifests share the same blob even when filenames differ.- [ ] [extend-syncorchestrator-to-cover-pipeline-universe] **Extend `syncOrchestrator` to cover pipeline/universe over Tailscale.** Same-network peers should sync these categories without going through a bucket.- [ ] [multi-hop-provenance-chains-re-share-authors-a] **Multi-hop provenance chains.** Re-share authors a fresh `origin` block; `chain[]` would preserve full attribution. Defer until users ask.- [ ] [same-collection-export-pattern-for-pipeline-series] **Same collection-export pattern for pipeline series with auto-collections.** Series renders that get auto-filed into a per-series collection should also flow through `manifest.collection`.@@ -100,6 +99,11 @@ _Nothing currently parked — pick the next item from the Backlog._- [ ] [world-builder-phase-2-external-sd-api-per-bucket] **World Builder Phase 2 — external SD-API + per-bucket model overrides.** Wire Together / Replicate / Fal into world-builder batch path so high-end renders are practical; let each bucket pick its own model.- [ ] [unify-videogen-resolutions-with-shared-image-gen] **Unify VideoGen `RESOLUTIONS` with shared image-gen list.** Move to `client/src/lib/videoGenResolutions.js` (or extend imageGenResolutions with `media: 'image'|'video'`) so dropdown + custom-fallback live in one place.+### Sharing — performance follow-ups (deferred from content-addressed asset dedup, 2026-05-18)++- [ ] [sharing-exporter-cache-sourcefile-hash-by-mtime] **Cache `sha256File` results in the exporter by `(sourcePath, mtime, size)`.** `copyAssetIfPresent` (`server/services/sharing/exporter.js`) re-hashes every referenced asset on every export, even when the blob already exists in the bucket. A subscription re-export of a 200MB series re-reads 200MB just to confirm "blob already there." Maintain a sidecar `<bucket>/assets/blobs/.index.json` mapping `<sourcePath>:<mtime>:<size> → <hash>`; skip the hash + copy when the cached entry matches and the blob is present. Invalidate purely on mtime change. ~30 LOC + one JSON file.+- [ ] [sharing-annotationssync-cache-bucket-asset-keys] **Cache `listBucketAssetKeys` per (bucket, manifests-dir mtime).** Today `annotationsSync.js#listBucketAssetKeys` re-scans every manifest in every auto-merge bucket on every 2s-debounced annotation flush (post-v2 because content-addressed blob paths don't carry filenames, so manifests are the only source of truth). Memoize `Map<bucketPath, { mtime, keys }>` keyed on the manifests dir mtime; invalidate when mtime advances. The legacy `assets/{images,videos}/` dir scan is still needed as a fall-through for pre-v2 buckets and can run un-cached.+### Code quality / dedup (from `/simplify` passes)- [ ] [tabpills-pipelineissue-status-dot-trailing-slot] **Extend `<TabPills>` with a `trailing` slot to migrate `PipelineIssue.jsx`.** That page's tab row renders a per-tab status dot (`<span className="w-1.5 h-1.5 rounded-full ${STATUS_DOT[status]}" />`) after the label (see `client/src/pages/PipelineIssue.jsx:298-319`). Add an optional `t.trailing` ReactNode to the tab shape (rendered after the count), then migrate the call site. Defer until the next time a tab-bar variant lands so the API surface grows in response to a concrete second user, not in anticipation.diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex 3151e8b57d..c48ac31e13 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -5,10 +5,10 @@*/import { mkdir, readFile, readdir, stat, writeFile, rename, unlink } from 'fs/promises';-import { existsSync, statSync } from 'fs';+import { existsSync, statSync, createReadStream } from 'fs';import { execFile } from 'child_process';import { promisify } from 'util';-import { randomUUID } from 'crypto';+import { createHash, randomUUID } from 'crypto';import { join, dirname, basename, extname, resolve as resolvePath, sep as PATH_SEP } from 'path';import { fileURLToPath } from 'url';import { homedir } from 'os';@@ -715,3 +715,25 @@ export async function dirSize(path) {const kb = parseInt(result.stdout.split('\t')[0], 10) || 0;return kb * 1024;}++/**+ * SHA-256 a file as hex. One-shot read under 512 KB; streams above so multi-GB+ * videos don't blow heap. Threshold matches `server/services/backup.js`'s+ * snapshot manifest generator.+ */+const SHA256_STREAM_THRESHOLD = 512 * 1024;+export async function sha256File(path) {+ const info = await stat(path);+ if (info.size < SHA256_STREAM_THRESHOLD) {+ const buf = await readFile(path);+ return createHash('sha256').update(buf).digest('hex');+ }+ return new Promise((resolve, reject) => {+ const hasher = createHash('sha256');+ const stream = createReadStream(path);+ stream.on('error', reject);+ stream.pipe(hasher);+ hasher.on('finish', () => resolve(hasher.digest('hex')));+ hasher.on('error', reject);+ });+}diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.jsindex 7885dfe8bc..dc5f2b21d9 100644--- a/server/lib/fileUtils.test.js+++ b/server/lib/fileUtils.test.js@@ -1,7 +1,9 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { writeFile, rm, mkdir } from 'fs/promises';+import { mkdtempSync, rmSync, writeFileSync } from 'fs';import { join } from 'path';import { tmpdir } from 'os';+import { createHash } from 'crypto';import {assertSafeFilename,isValidJSON,@@ -10,7 +12,8 @@ import {safeJSONLParse,readJSONFile,readJSONLFile,- formatDuration+ formatDuration,+ sha256File,} from './fileUtils.js';describe('fileUtils', () => {@@ -508,4 +511,39 @@ describe('fileUtils', () => {).rejects.toThrow(/mapEntry must be a function/);});});++ describe('sha256File', () => {+ let dir;+ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'portos-sha256-')); });+ afterEach(() => { rmSync(dir, { recursive: true, force: true }); });++ it('hashes a small file in one shot and matches createHash digest', async () => {+ const p = join(dir, 'small.bin');+ writeFileSync(p, 'hello world');+ const expected = createHash('sha256').update('hello world').digest('hex');+ expect(await sha256File(p)).toBe(expected);+ });++ it('hashes a large file via streaming (>= 512KB)', async () => {+ const p = join(dir, 'big.bin');+ const buf = Buffer.alloc(600 * 1024, 0x42);+ writeFileSync(p, buf);+ const expected = createHash('sha256').update(buf).digest('hex');+ expect(await sha256File(p)).toBe(expected);+ });++ it('returns identical digests for identical content under different paths', async () => {+ const a = join(dir, 'a.bin'); const b = join(dir, 'b.bin');+ writeFileSync(a, 'same-content');+ writeFileSync(b, 'same-content');+ expect(await sha256File(a)).toBe(await sha256File(b));+ });++ it('returns different digests for different content', async () => {+ const a = join(dir, 'a.bin'); const b = join(dir, 'b.bin');+ writeFileSync(a, 'one');+ writeFileSync(b, 'two');+ expect(await sha256File(a)).not.toBe(await sha256File(b));+ });+ });});diff --git a/server/services/backup.js b/server/services/backup.jsindex ba0de18baa..53f43bd7dc 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -7,12 +7,10 @@*/import { spawn } from 'child_process';-import { createHash } from 'crypto';-import { createReadStream } from 'fs';-import { access, readFile, readdir, stat, writeFile } from 'fs/promises';+import { access, readdir, stat, writeFile } from 'fs/promises';import { hostname } from 'os';import { join, resolve, relative, isAbsolute } from 'path';-import { PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';+import { PATHS, ensureDir, readJSONFile, sha256File } from '../lib/fileUtils.js';import { getEvent } from './eventScheduler.js';import { checkHealth } from '../lib/db.js';@@ -269,27 +267,7 @@ export async function generateManifest(snapshotDataDir, manifestPath) {const filePath = join(snapshotDataDir, entry);const info = await stat(filePath).catch(() => null);if (!info || !info.isFile()) continue;-- const relativePath = entry;- let hash;-- if (info.size < 512 * 1024) {- // Small file: read all at once- const content = await readFile(filePath);- hash = createHash('sha256').update(content).digest('hex');- } else {- // Large file: streaming hash- hash = await new Promise((resolve, reject) => {- const stream = createReadStream(filePath);- const hasher = createHash('sha256');- stream.pipe(hasher);- stream.on('error', reject);- hasher.on('finish', () => resolve(hasher.digest('hex')));- hasher.on('error', reject);- });- }-- files[relativePath] = hash;+ files[entry] = await sha256File(filePath);}const manifest = {diff --git a/server/services/sharing/annotationsSync.js b/server/services/sharing/annotationsSync.jsindex 1167559449..f05d4874ab 100644--- a/server/services/sharing/annotationsSync.js+++ b/server/services/sharing/annotationsSync.js@@ -11,7 +11,7 @@ import { readdir } from 'fs/promises';import { existsSync } from 'fs';import { ensureDir, atomicWrite, readJSONFile } from '../../lib/fileUtils.js';import { listBuckets } from './buckets.js';-import { buildManifest, writeManifest, annotationManifestFilename } from './manifest.js';+import { buildManifest, writeManifest, annotationManifestFilename, readManifest, listManifestFilenames } from './manifest.js';import { getProducedByVersion } from './version.js';import { getInstanceId } from '../instances.js';import { resolveLocalAuthorName } from './annotationIdentity.js';@@ -21,8 +21,31 @@ const DEBOUNCE_MS = 2000;let pendingTimer = null;let installed = false;+/**+ * Set of `${kind}:${filename}` keys for every asset referenced by any manifest+ * in the bucket. v2's content-addressed `assets/blobs/<hash>` paths don't+ * carry filenames, so the manifests are the only source-of-truth for which+ * user-facing filenames the bucket holds; the legacy `assets/{images,videos}/`+ * scan covers v1 buckets that never wrote a manifest's `hash` field.+ */async function listBucketAssetKeys(bucketPath) {const keys = new Set();+ const filenames = await listManifestFilenames(bucketPath);+ await Promise.all(filenames.map(async (filename) => {+ const m = await readManifest(bucketPath, filename).catch(() => null);+ for (const ref of m?.assetRefs || []) {+ if (!ref?.ref || typeof ref.ref !== 'string') continue;+ const kind = ref.kind === 'video' ? 'video' : 'image';+ keys.add(`${kind}:${ref.ref}`);+ }+ for (const item of m?.collection?.items || []) {+ if (!item?.ref || typeof item.ref !== 'string') continue;+ const kind = item.kind === 'video' ? 'video' : 'image';+ keys.add(`${kind}:${item.ref}`);+ }+ }));+ // Legacy v1 buckets predate manifest-as-authority: fall through to a+ // direct dir scan so existing buckets still advertise their assets.for (const [subdir, kind] of [['images', 'image'], ['videos', 'video']]) {const dir = join(bucketPath, 'assets', subdir);if (!existsSync(dir)) continue;diff --git a/server/services/sharing/buckets.js b/server/services/sharing/buckets.jsindex 4c559cb671..e98e53bb4e 100644--- a/server/services/sharing/buckets.js+++ b/server/services/sharing/buckets.js@@ -76,6 +76,33 @@ async function assertPathUsable(path) {}}+/**+ * Path helpers for the per-bucket content-addressed blob store. v2 manifests+ * (`SHARING_SCHEMA_VERSION >= 2`) reference assets via their SHA-256 hash;+ * blobs and their `.metadata.json` sidecars live alongside each other under+ * `assets/blobs/` so storage-layout changes only touch this file.+ *+ * Hashes from manifests are UNTRUSTED — a hostile peer could ship+ * `hash: '../../../../etc/hosts'` to traverse out of the blob dir on import.+ * `isHexHash` enforces the SHA-256 shape (64 lowercase hex chars) so+ * `bucketBlobPath(...)` can never produce a path outside `assets/blobs/`.+ * The path helpers throw on bad input; the importer also drops bad refs at+ * the manifest boundary so a single broken entry doesn't poison a batch.+ */+export const IMAGE_EXT_RE = /\.(png|jpe?g|webp)$/i;+const HEX_HASH_RE = /^[0-9a-f]{64}$/;+export function isHexHash(v) { return typeof v === 'string' && HEX_HASH_RE.test(v); }+export function bucketBlobsDir(bucketPath) { return join(bucketPath, 'assets', 'blobs'); }+export function bucketBlobPath(bucketPath, hash) {+ if (!isHexHash(hash)) throw makeErr(`Invalid asset hash: ${hash}`, ERR_VALIDATION);+ return join(bucketBlobsDir(bucketPath), hash);+}+export function bucketBlobSidecarPath(bucketPath, hash) {+ if (!isHexHash(hash)) throw makeErr(`Invalid asset hash: ${hash}`, ERR_VALIDATION);+ return join(bucketBlobsDir(bucketPath), `${hash}.metadata.json`);+}+export function imageSidecarName(filename) { return filename.replace(IMAGE_EXT_RE, '') + '.metadata.json'; }+/** Lay out the canonical bucket structure (idempotent). */export async function ensureBucketLayout(bucket) {const base = bucket.path;@@ -87,6 +114,7 @@ export async function ensureBucketLayout(bucket) {await ensureDir(join(base, 'records', 'media'));await ensureDir(join(base, 'assets', 'images'));await ensureDir(join(base, 'assets', 'videos'));+ await ensureDir(join(base, 'assets', 'blobs'));const bucketJsonPath = join(base, 'bucket.json');const existing = await readJSONFile(bucketJsonPath, null, { logError: false });if (!existing) {diff --git a/server/services/sharing/buckets.test.js b/server/services/sharing/buckets.test.jsindex 58a90a4928..5095de1186 100644--- a/server/services/sharing/buckets.test.js+++ b/server/services/sharing/buckets.test.js@@ -45,6 +45,7 @@ describe('sharing/buckets', () => {expect(fs.existsSync(join(bucketTargetDir, 'records', 'media'))).toBe(true);expect(fs.existsSync(join(bucketTargetDir, 'assets', 'images'))).toBe(true);expect(fs.existsSync(join(bucketTargetDir, 'assets', 'videos'))).toBe(true);+ expect(fs.existsSync(join(bucketTargetDir, 'assets', 'blobs'))).toBe(true);expect(fs.existsSync(join(bucketTargetDir, 'bucket.json'))).toBe(true);});diff --git a/server/services/sharing/exporter.js b/server/services/sharing/exporter.jsindex 5830bfb371..429de214a8 100644--- a/server/services/sharing/exporter.js+++ b/server/services/sharing/exporter.js@@ -6,18 +6,20 @@* for full-fidelity re-render metadata) into the bucket, then writes a manifest* pointing at the bundled records.*- * Asset filenames are already UUIDs (data/images/<uuid>.png), so collisions- * between peers' exports are extremely unlikely. We skip-if-present rather than- * overwrite — a re-share that includes the same asset is a no-op for the blob- * copy, but the manifest still references it so the recipient knows the asset- * belongs to the latest share.+ * Asset blobs are content-addressed by SHA-256 and stored at+ * `<bucket>/assets/blobs/<hash>` (sidecar metadata at `<hash>.metadata.json`).+ * Two manifests that reference identical content under different filenames+ * share one blob on disk — the recipient maps the manifest's per-entry+ * filename back to the local `data/{kind}/<filename>` location. The asset ref+ * carries `{ kind, ref, hash }`; legacy v1 manifests without `hash` still+ * import via the `assets/{kind}/<filename>` fallback path.*/import { join, basename } from 'path';import { copyFile, readFile, writeFile, stat } from 'fs/promises';import { existsSync } from 'fs';-import { PATHS, ensureDir, atomicWrite, readJSONFile } from '../../lib/fileUtils.js';-import { getBucket, ensureBucketLayout } from './buckets.js';+import { PATHS, ensureDir, atomicWrite, readJSONFile, sha256File } from '../../lib/fileUtils.js';+import { getBucket, ensureBucketLayout, bucketBlobsDir, bucketBlobPath, bucketBlobSidecarPath, imageSidecarName } from './buckets.js';import { buildManifest, writeManifest, pruneBucketManifests } from './manifest.js';import { listSeries, getSeries } from '../pipeline/series.js';import { listIssues } from '../pipeline/issues.js';@@ -57,33 +59,40 @@ async function resolveSourceBio(bucket) {return null;}-/** Copy an asset file from `data/images` or `data/videos` into the bucket. Returns ref entry. */+/**+ * Copy `<sourceDir>/<filename>` into the bucket's content-addressed blob store.+ * Returns `{ kind, ref, hash }`; the recipient maps `ref` (the original+ * filename) back to its `data/{kind}/<ref>` slot. Two manifests that ship+ * identical bytes under different filenames share one blob.+ *+ * First-writer wins on sidecar collision: identical bytes imply identical+ * gen params in practice, so the second writer's (possibly missing) sidecar+ * doesn't overwrite the first's.+ */async function copyAssetIfPresent(filename, kind, bucketPath) {if (!filename || typeof filename !== 'string') return null;const base = basename(filename);if (!base || base !== filename) return null; // refuse path traversalconst sourceDir = kind === 'video' ? PATHS.videos : PATHS.images;- const targetDir = join(bucketPath, 'assets', kind === 'video' ? 'videos' : 'images');- await ensureDir(targetDir);+ await ensureDir(bucketBlobsDir(bucketPath));const sourcePath = join(sourceDir, base);if (!existsSync(sourcePath)) {console.log(`⚠️ sharing.exporter: asset not found locally, skipping: ${sourcePath}`);return null;}- const targetPath = join(targetDir, base);- if (!existsSync(targetPath)) {- await copyFile(sourcePath, targetPath);+ const hash = await sha256File(sourcePath);+ const blobPath = bucketBlobPath(bucketPath, hash);+ if (!existsSync(blobPath)) {+ await copyFile(sourcePath, blobPath);}- // Also copy the sidecar metadata.json (image-gen path stamps prompts there).if (kind === 'image') {- const sidecarBase = base.replace(/\.(png|jpe?g|webp)$/i, '') + '.metadata.json';- const sidecarSource = join(sourceDir, sidecarBase);+ const sidecarSource = join(sourceDir, imageSidecarName(base));if (existsSync(sidecarSource)) {- const sidecarTarget = join(targetDir, sidecarBase);+ const sidecarTarget = bucketBlobSidecarPath(bucketPath, hash);if (!existsSync(sidecarTarget)) await copyFile(sidecarSource, sidecarTarget);}}- return { kind, ref: base };+ return { kind, ref: base, hash };}/**diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.jsindex dfd9679c87..145d3af49a 100644--- a/server/services/sharing/importer.js+++ b/server/services/sharing/importer.js@@ -13,10 +13,12 @@* the manifest before its assets, the importer applies/copies what is available* and leaves the manifest retryable until the remaining blobs arrive.*- * Asset blobs referenced by the manifest are copied from the bucket's- * `assets/{images,videos}/` into the local `data/{images,videos}/` directories- * (skip-if-present). Media-job records bundled in `records/media/` are merged- * into `data/media-jobs.json` so re-render workflows have the prompt + params.+ * Asset blobs referenced by the manifest are copied from the bucket into the+ * local `data/{images,videos}/` directories (skip-if-present). v2+ manifests+ * use a content-addressed source at `assets/blobs/<hash>`; legacy v1 manifests+ * fall back to `assets/{images,videos}/<filename>`. Media-job records bundled+ * in `records/media/` are merged into `data/media-jobs.json` so re-render+ * workflows have the prompt + params.*/import { join, basename } from 'path';@@ -24,7 +26,7 @@ import { copyFile, readdir } from 'fs/promises';import { existsSync } from 'fs';import { EventEmitter } from 'events';import { PATHS, ensureDir, atomicWrite, readJSONFile } from '../../lib/fileUtils.js';-import { getBucket } from './buckets.js';+import { getBucket, bucketBlobPath, bucketBlobSidecarPath, imageSidecarName, isHexHash } from './buckets.js';import { readManifest, markProcessed, readCursor, hasBeenProcessed, forgetProcessed } from './manifest.js';import { SHARING_SCHEMA_VERSION, isManifestCompatible } from './version.js';import { insertSeriesWithId, updateSeries, getSeries } from '../pipeline/series.js';@@ -143,7 +145,27 @@ function manifestAssetRefs(manifest) {const key = `${kind}:${filename}`;if (seen.has(key)) return;seen.add(key);- refs.push({ kind, ref: filename });+ // hash is optional — only v2+ manifests carry it. Collection items have+ // never carried per-item hashes (they reference filenames in the user's+ // local data dir), so the legacy filename path covers them.+ //+ // Hashes are UNTRUSTED peer input. Accept only well-formed SHA-256+ // (64 lowercase hex chars) so `bucketBlobPath(bucketPath, hash)` can't+ // be coerced into a `path.join('.../assets/blobs', '../../etc/hosts')`+ // path-traversal primitive that would `copyFile` an arbitrary file from+ // the user's filesystem into `data/{images,videos}/`. A malformed hash+ // means the manifest is broken or hostile — drop the ref entirely+ // rather than fall back to the legacy filename path (a v2 manifest+ // that sets a bogus hash isn't a v1 manifest).+ const entry = { kind, ref: filename };+ if (raw.hash !== undefined && raw.hash !== null) {+ if (!isHexHash(raw.hash)) {+ console.log(`⚠️ sharing.importer: dropping asset ref with invalid hash: ${kind}/${filename}`);+ return;+ }+ entry.hash = raw.hash;+ }+ refs.push(entry);};for (const ref of manifest?.assetRefs || []) push(ref);// Universe collection payloads are also asset membership. Import from the@@ -153,6 +175,27 @@ function manifestAssetRefs(manifest) {return refs;}+/**+ * Resolve the bucket-side blob + optional sidecar paths for an asset ref.+ * v2 manifests carry `hash` and read from `assets/blobs/`; legacy v1+ * manifests fall back to `assets/{images,videos}/<filename>`. Videos have no+ * sidecar convention.+ */+function resolveBucketAssetPaths(bucketPath, ref) {+ const isVideo = ref.kind === 'video';+ if (ref.hash) {+ return {+ blobPath: bucketBlobPath(bucketPath, ref.hash),+ sidecarPath: isVideo ? null : bucketBlobSidecarPath(bucketPath, ref.hash),+ };+ }+ const legacyDir = join(bucketPath, 'assets', isVideo ? 'videos' : 'images');+ return {+ blobPath: join(legacyDir, ref.ref),+ sidecarPath: isVideo ? null : join(legacyDir, imageSidecarName(ref.ref)),+ };+}+/** Copy bundled assets from the bucket into local data dirs. Runs in parallel. */async function copyAssetsLocally(bucketPath, assetRefs) {await ensureDir(PATHS.images);@@ -164,26 +207,22 @@ async function copyAssetsLocally(bucketPath, assetRefs) {if (!ref || !isStr(ref.ref)) return;const filename = basename(ref.ref);const isVideo = ref.kind === 'video';- const sourceDir = join(bucketPath, 'assets', isVideo ? 'videos' : 'images');+ const kind = isVideo ? 'video' : 'image';const targetDir = isVideo ? PATHS.videos : PATHS.images;- const sourcePath = join(sourceDir, filename);const targetPath = join(targetDir, filename);- if (!existsSync(sourcePath)) {- missing.push({ kind: isVideo ? 'video' : 'image', ref: filename });+ const { blobPath, sidecarPath } = resolveBucketAssetPaths(bucketPath, ref);+ if (!existsSync(blobPath)) {+ missing.push({ kind, ref: filename });return;}- available.push({ kind: isVideo ? 'video' : 'image', ref: filename });+ available.push({ kind, ref: filename });if (!existsSync(targetPath)) {- await copyFile(sourcePath, targetPath);- copied.push({ kind: isVideo ? 'video' : 'image', ref: filename });+ await copyFile(blobPath, targetPath);+ copied.push({ kind, ref: filename });}- if (!isVideo) {- const sidecarBase = filename.replace(/\.(png|jpe?g|webp)$/i, '') + '.metadata.json';- const sidecarSource = join(sourceDir, sidecarBase);- if (existsSync(sidecarSource)) {- const sidecarTarget = join(targetDir, sidecarBase);- if (!existsSync(sidecarTarget)) await copyFile(sidecarSource, sidecarTarget);- }+ if (sidecarPath && existsSync(sidecarPath)) {+ const sidecarTarget = join(targetDir, imageSidecarName(filename));+ if (!existsSync(sidecarTarget)) await copyFile(sidecarPath, sidecarTarget);}}));return { copied, available, missing };diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.jsindex 6c97e38bbe..23413ff80e 100644--- a/server/services/sharing/integration.test.js+++ b/server/services/sharing/integration.test.js@@ -12,6 +12,11 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import { mkdtempSync, rmSync, writeFileSync, existsSync, mkdirSync, readFileSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';+import { createHash } from 'crypto';++function sha256Hex(buf) {+ return createHash('sha256').update(buf).digest('hex');+}// Universe builder evaluates `join(PATHS.data, …)` at module-top, so PATHS// must point at a real dir from the very first import. Allocate a single@@ -103,11 +108,12 @@ describe('sharing round-trip', () => {expect(exp.recordCount).toBe(3); // series + issue + universeexpect(exp.assetCount).toBeGreaterThanOrEqual(1);- // Verify the bucket layout.+ // Verify the bucket layout. v2 stores blobs content-addressed.expect(existsSync(join(tempBucket, 'manifests', exp.filename))).toBe(true);expect(existsSync(join(tempBucket, 'records', 'series', `${s.id}.json`))).toBe(true);expect(existsSync(join(tempBucket, 'records', 'issues', `${iss.id}.json`))).toBe(true);- expect(existsSync(join(tempBucket, 'assets', 'images', 'fakeasset.png'))).toBe(true);+ const fakeHash = sha256Hex('PNGSTUB');+ expect(existsSync(join(tempBucket, 'assets', 'blobs', fakeHash))).toBe(true);// Process as inbox (the bucket mode is 'inbox'). The manifest should// queue, not auto-apply.@@ -233,7 +239,7 @@ describe('sharing round-trip', () => {const manifest = JSON.parse(fs.readFileSync(join(tempBucket, 'manifests', manifestFile), 'utf-8'));expect(manifest.collection).toMatchObject({ universeId: u.id });expect(manifest.collection.items).toHaveLength(2);- expect(fs.existsSync(join(tempBucket, 'assets', 'images', 'second.png'))).toBe(true);+ expect(fs.existsSync(join(tempBucket, 'assets', 'blobs', sha256Hex('PNG2')))).toBe(true);// Drop the local collection + universe, then re-process: the importer// should recreate both, find-or-create the local collection by@@ -300,7 +306,8 @@ describe('sharing round-trip', () => {await mediaCollections.addItem(collection.id, { kind: 'image', ref: 'late.png' });const exp = await exporter.exportUniverse(u.id, bucket.id);- fs.rmSync(join(tempBucket, 'assets', 'images', 'late.png'), { force: true });+ const lateHash = sha256Hex('LATEPNG');+ fs.rmSync(join(tempBucket, 'assets', 'blobs', lateHash), { force: true });fs.rmSync(join(tempData, 'images', 'late.png'), { force: true });await mediaCollections.deleteCollection(collection.id);await universeBuilder.deleteUniverse(u.id);@@ -317,7 +324,7 @@ describe('sharing round-trip', () => {let cursor = await readCursor(bucket.id);expect(hasBeenProcessed(cursor, exp.filename, exp.manifestId)).toBe(false);- fs.writeFileSync(join(tempBucket, 'assets', 'images', 'late.png'), 'LATEPNG');+ fs.writeFileSync(join(tempBucket, 'assets', 'blobs', lateHash), 'LATEPNG');const retry = await importer.processBacklog(bucket.id);expect(retry.processed).toBe(1);@@ -597,6 +604,199 @@ describe('sharing round-trip', () => {expect(updates).toHaveLength(1);});+ it('content-addressed blob is shared when two manifests reference identical bytes under different filenames', async () => {+ const bucket = await buckets.createBucket({ name: 'DedupBucket', path: tempBucket, mode: 'auto-merge' });+ const fs = await import('fs');+ const universeBuilder = await import('../universeBuilder.js');+ const mediaCollections = await import('../mediaCollections.js');++ // Two distinct filenames, identical bytes.+ const sharedBytes = 'SHARED-PNG-PAYLOAD';+ fs.writeFileSync(join(tempData, 'images', 'alpha.png'), sharedBytes);+ fs.writeFileSync(join(tempData, 'images', 'beta.png'), sharedBytes);+ const hash = sha256Hex(sharedBytes);++ // Universe A references alpha.png.+ const uniA = await universeBuilder.createUniverse({ name: 'UA' });+ const collA = await mediaCollections.findOrCreateCollectionByName({+ name: `Universe: ${uniA.name}`, description: '', universeId: uniA.id,+ });+ await mediaCollections.addItem(collA.id, { kind: 'image', ref: 'alpha.png' });+ const expA = await exporter.exportUniverse(uniA.id, bucket.id);++ // Universe B references beta.png — same bytes, different filename.+ const uniB = await universeBuilder.createUniverse({ name: 'UB' });+ const collB = await mediaCollections.findOrCreateCollectionByName({+ name: `Universe: ${uniB.name}`, description: '', universeId: uniB.id,+ });+ await mediaCollections.addItem(collB.id, { kind: 'image', ref: 'beta.png' });+ const expB = await exporter.exportUniverse(uniB.id, bucket.id);++ // Both manifests point at the same blob path; only one on-disk file exists.+ expect(fs.existsSync(join(tempBucket, 'assets', 'blobs', hash))).toBe(true);+ expect(fs.readdirSync(join(tempBucket, 'assets', 'blobs'))).toEqual([hash]);++ // Each manifest's assetRef carries the hash + its own original filename.+ const mA = JSON.parse(fs.readFileSync(join(tempBucket, 'manifests', expA.filename), 'utf-8'));+ const mB = JSON.parse(fs.readFileSync(join(tempBucket, 'manifests', expB.filename), 'utf-8'));+ expect(mA.assetRefs).toContainEqual({ kind: 'image', ref: 'alpha.png', hash });+ expect(mB.assetRefs).toContainEqual({ kind: 'image', ref: 'beta.png', hash });++ // Import path: each manifest restores its filename in the local data dir.+ fs.rmSync(join(tempData, 'images', 'alpha.png'), { force: true });+ fs.rmSync(join(tempData, 'images', 'beta.png'), { force: true });+ await mediaCollections.deleteCollection(collA.id);+ await mediaCollections.deleteCollection(collB.id);+ await universeBuilder.deleteUniverse(uniA.id);+ await universeBuilder.deleteUniverse(uniB.id);++ simulateRemoteSender(tempBucket, expA.filename);+ simulateRemoteSender(tempBucket, expB.filename);+ await importer.processManifest(bucket.id, expA.filename);+ await importer.processManifest(bucket.id, expB.filename);++ expect(fs.existsSync(join(tempData, 'images', 'alpha.png'))).toBe(true);+ expect(fs.existsSync(join(tempData, 'images', 'beta.png'))).toBe(true);+ expect(fs.readFileSync(join(tempData, 'images', 'alpha.png'), 'utf-8')).toBe(sharedBytes);+ expect(fs.readFileSync(join(tempData, 'images', 'beta.png'), 'utf-8')).toBe(sharedBytes);+ });++ it('importer rejects manifest asset refs whose hash is not a 64-char hex string (path-traversal guard)', async () => {+ const bucket = await buckets.createBucket({ name: 'HostileBucket', path: tempBucket, mode: 'auto-merge' });+ const fs = await import('fs');+ const { SHARING_SCHEMA_VERSION } = await import('./version.js');++ // Plant a file outside the blob dir that a path-traversal attempt would target.+ const secretsDir = mkdtempSync(join(tmpdir(), 'portos-sharing-hostile-secret-'));+ const secretPath = join(secretsDir, 'secret.txt');+ fs.writeFileSync(secretPath, 'SECRET-CONTENT-DO-NOT-LEAK');++ // Compute the traversal that would escape <bucket>/assets/blobs/ and+ // land on the planted secret. Use forward slashes — path.join normalizes.+ const rel = ['..', '..', '..', '..', '..', '..', '..', '..', '..'].join('/')+ + secretPath.replace(/\\/g, '/');++ const universeBuilder = await import('../universeBuilder.js');+ const u = await universeBuilder.createUniverse({ name: 'Hostile Universe' });+ fs.mkdirSync(join(tempBucket, 'records', 'universes'), { recursive: true });+ fs.writeFileSync(join(tempBucket, 'records', 'universes', `${u.id}.json`), JSON.stringify({+ ...u,+ origin: {+ bucketId: bucket.id, bucketName: bucket.name,+ source: 'hostile-peer', sourceBio: null,+ manifestId: 'mfst-hostile', importedAt: new Date().toISOString(),+ },+ }));+ await universeBuilder.deleteUniverse(u.id);++ // Hostile manifest: hash is a relative path traversing out of the blob dir.+ const hostileManifest = {+ id: 'mfst-hostile',+ schemaVersion: SHARING_SCHEMA_VERSION,+ sharingSchemaVersion: SHARING_SCHEMA_VERSION,+ producedByVersion: '9.9.9',+ createdAt: new Date().toISOString(),+ kind: 'universe',+ senderInstanceId: 'hostile-peer',+ source: 'Hostile Peer',+ sourceBio: null,+ bucketId: bucket.id,+ bucketName: bucket.name,+ recordIds: [u.id],+ assetRefs: [{ kind: 'image', ref: 'pwned.png', hash: rel }],+ note: null,+ };+ const filename = `2099-01-01T00-00-00-000Z-hostile-peer-${hostileManifest.id}.json`;+ fs.mkdirSync(join(tempBucket, 'manifests'), { recursive: true });+ fs.writeFileSync(join(tempBucket, 'manifests', filename), JSON.stringify(hostileManifest));++ const result = await importer.processManifest(bucket.id, filename);+ // The universe record imports fine; the asset ref is dropped at the+ // manifest-parse boundary so no file copy is attempted.+ expect(result.processed).toBe(true);+ // The hostile file MUST NOT have been copied into the local data dirs.+ expect(fs.existsSync(join(tempData, 'images', 'pwned.png'))).toBe(false);+ expect(fs.existsSync(join(tempData, 'images', 'secret.txt'))).toBe(false);++ // The secret on disk should be untouched.+ expect(fs.readFileSync(secretPath, 'utf-8')).toBe('SECRET-CONTENT-DO-NOT-LEAK');++ rmSync(secretsDir, { recursive: true, force: true });+ });++ it('bucketBlobPath / bucketBlobSidecarPath throw on malformed hash (defense-in-depth)', async () => {+ const bogus = [+ '../../../../etc/hosts',+ 'ABCDEF', // uppercase — must be lowercase+ 'g'.repeat(64), // not hex+ '0'.repeat(63), // wrong length+ '0'.repeat(65),+ '',+ null,+ undefined,+ 42,+ ];+ for (const h of bogus) {+ expect(() => buckets.bucketBlobPath(tempBucket, h)).toThrow();+ expect(() => buckets.bucketBlobSidecarPath(tempBucket, h)).toThrow();+ }+ // Valid hash passes.+ const ok = sha256Hex('whatever');+ expect(buckets.bucketBlobPath(tempBucket, ok)).toBe(join(tempBucket, 'assets', 'blobs', ok));+ expect(buckets.bucketBlobSidecarPath(tempBucket, ok)).toBe(join(tempBucket, 'assets', 'blobs', `${ok}.metadata.json`));+ });++ it('importer falls back to legacy assets/<kind>/<filename> when manifest asset ref omits hash (v1 compat)', async () => {+ const bucket = await buckets.createBucket({ name: 'LegacyImportBucket', path: tempBucket, mode: 'auto-merge' });+ const fs = await import('fs');+ const { SHARING_SCHEMA_VERSION } = await import('./version.js');++ // Hand-craft a v1-style bucket: blob lives at assets/images/<filename>,+ // manifest's assetRefs has no `hash` field, schemaVersion: 1.+ fs.mkdirSync(join(tempBucket, 'assets', 'images'), { recursive: true });+ fs.writeFileSync(join(tempBucket, 'assets', 'images', 'legacy-v1.png'), 'V1BYTES');++ const universeBuilder = await import('../universeBuilder.js');+ const u = await universeBuilder.createUniverse({ name: 'Legacy v1 Universe' });+ fs.writeFileSync(join(tempBucket, 'records', 'universes', `${u.id}.json`), JSON.stringify({+ ...u,+ origin: {+ bucketId: bucket.id, bucketName: bucket.name,+ source: 'old-peer', sourceBio: null,+ manifestId: 'mfst-v1', importedAt: new Date().toISOString(),+ },+ }));+ await universeBuilder.deleteUniverse(u.id);++ const v1Manifest = {+ id: 'mfst-v1',+ schemaVersion: 1,+ sharingSchemaVersion: 1,+ producedByVersion: '1.0.0',+ createdAt: new Date().toISOString(),+ kind: 'universe',+ senderInstanceId: 'old-peer',+ source: 'Old Peer',+ sourceBio: null,+ bucketId: bucket.id,+ bucketName: bucket.name,+ recordIds: [u.id],+ assetRefs: [{ kind: 'image', ref: 'legacy-v1.png' }], // no hash+ note: null,+ };+ const filename = `2000-01-01T00-00-00-000Z-old-peer-${v1Manifest.id}.json`;+ fs.writeFileSync(join(tempBucket, 'manifests', filename), JSON.stringify(v1Manifest));+ expect(SHARING_SCHEMA_VERSION).toBeGreaterThanOrEqual(2); // sanity++ const result = await importer.processManifest(bucket.id, filename);+ expect(result.processed).toBe(true);+ expect(result.pending).toBeFalsy();++ // Asset blob made it to the local data dir via the legacy path.+ expect(fs.existsSync(join(tempData, 'images', 'legacy-v1.png'))).toBe(true);+ expect(fs.readFileSync(join(tempData, 'images', 'legacy-v1.png'), 'utf-8')).toBe('V1BYTES');+ });+it('refuses a manifest with a sharingSchemaVersion newer than local + emits incompatible event', async () => {const { SHARING_SCHEMA_VERSION } = await import('./version.js');const { sharingEvents } = await import('./importer.js');diff --git a/server/services/sharing/version.js b/server/services/sharing/version.jsindex 6b34da16c0..af5f87f86a 100644--- a/server/services/sharing/version.js+++ b/server/services/sharing/version.js@@ -11,6 +11,14 @@* source, sourceBio?, bucketId, bucketName, recordIds[], assetRefs[], note? }.* assetRefs use { kind: 'image'|'video', ref: '<filename>' }.* Record bundles in `records/{series,issues,universes,media}/<id>.json`.+ * Asset blobs at `assets/{images,videos}/<filename>`.+ * 2 — content-addressed asset blobs. assetRefs now `{ kind, ref, hash }`+ * (sha256). Blobs live at `assets/blobs/<hash>`; sidecar metadata at+ * `assets/blobs/<hash>.metadata.json`. The importer prefers the hash+ * lookup and falls back to `assets/<kind>/<filename>` when `hash` is+ * absent (so v1 manifests still in-bucket continue to import). Two+ * manifests that reference identical bytes under different filenames+ * share one on-disk blob, eliminating duplicate-blob storage.** Compatibility rules:* - A peer can read a manifest with `sharingSchemaVersion <= local@@ -28,7 +36,7 @@* load-bearing for compat decisions.*/-export const SHARING_SCHEMA_VERSION = 1;+export const SHARING_SCHEMA_VERSION = 2;let cachedAppVersion = null;let cachedAt = 0;