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
fix: protect local media from unrelated or stale peer pushes (#8403)
[._.]/ Adam Eivyd54dce6a83de
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex 6cd5bf4545..5d9f34c37a 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -3353,10 +3353,77 @@ describe('peerSync', () => {);});+ it('never pulls assets for an asset-less kind, even if the payload invents image references', async () => {+ await writeFile(join(PATHS.images, 'protected.png'), 'local image');+ const result = await applyIncomingPush({+ kind: 'commissionFeedback',+ record: { id: 'feedback-1', imageRefs: ['protected.png'] },+ assetManifest: [{ filename: 'protected.png', kind: 'image', sha256: 'a'.repeat(64) }],+ sourceInstanceId: 'peer-a',+ });+ expect(result.missingAssets).toEqual([]);+ expect(await readFile(join(PATHS.images, 'protected.png'), 'utf8')).toBe('local image');+ });++ it.each([false, true])('scopes a manifest to its record and replaces existing bytes only on an applied merge (%s)', async (applied) => {+ await writeFile(join(PATHS.images, 'existing.png'), 'local image');+ await writeFile(join(PATHS.images, 'existing.metadata.json'), '{"prompt":"local prompt"}');+ vi.mocked(mergeUniversesFromSync).mockResolvedValue({ applied, count: applied ? 1 : 0 });+ const manifest = ['missing.png', 'existing.png', 'unrelated.png'].map((filename) => ({+ filename, kind: 'image', sha256: 'a'.repeat(64), sidecarSha256: 'b'.repeat(64),+ }));+ const result = await applyIncomingPush({+ kind: 'universe',+ record: { id: 'u1', imageRefs: ['missing.png', 'existing.png'] },+ assetManifest: manifest,+ sourceInstanceId: 'peer-a',+ });+ expect(result.missingAssets).toEqual(applied ? manifest.slice(0, 2) : manifest.slice(0, 1));+ expect(await readFile(join(PATHS.images, 'existing.png'), 'utf8')).toBe('local image');+ if (!applied) {+ expect(await readFile(join(PATHS.images, 'existing.metadata.json'), 'utf8')).toBe('{"prompt":"local prompt"}');+ }+ });++ it('admits only referenced series, child-issue and linked-collection assets', async () => {+ const manifest = [+ { kind: 'image', filename: 'series.png' },+ { kind: 'image', filename: 'issue.png' },+ { kind: 'video', filename: 'collection-clip.mp4' },+ { kind: 'image', filename: 'private.png' },+ { kind: 'image', filename: 'deleted.png' },+ { kind: 'image', filename: 'unrelated.png' },+ ];+ const result = await applyIncomingPush({+ kind: 'series', record: { id: 'ser-1', imageRefs: ['series.png'] },+ issues: [+ { id: 'issue-1', seriesId: 'ser-1', imageRefs: ['issue.png'] },+ { id: 'issue-2', seriesId: 'ser-1', ephemeral: true, imageRefs: ['private.png'] },+ { id: 'issue-3', seriesId: 'ser-1', deleted: true, imageRefs: ['deleted.png'] },+ ],+ linkedCollection: { id: 'collection-1', items: [{ kind: 'video', ref: 'collection-clip' }] },+ assetManifest: manifest, sourceInstanceId: 'peer-a',+ });+ expect(result.missingAssets).toEqual(manifest.slice(0, 3));+ });++ it('admits track render history and deck images but drops other asset kinds', async () => {+ for (const [kind, record, own] of [+ ['track', { id: 'track-1', audioFilename: 'active.mp3', renders: [{ audioFilename: 'older.mp3' }] },+ [{ kind: 'music', filename: 'active.mp3' }, { kind: 'music', filename: 'older.mp3' }]],+ ['deck', { id: 'deck-1', cards: [{ primaryImageRef: 'card.png', imageRefs: ['render.png'] }], samples: [{ imageRef: 'style.png' }] },+ ['card.png', 'render.png', 'style.png'].map((filename) => ({ kind: 'image', filename }))],+ ]) {+ const result = await applyIncomingPush({ kind, record, sourceInstanceId: 'peer-a',+ assetManifest: [...own, { kind: 'audio', filename: 'unrelated.mp3' }] });+ expect(result.missingAssets).toEqual(own);+ }+ });+it('reports missing assets in the response', async () => {const result = await applyIncomingPush({kind: 'universe',- record: { id: 'u1' },+ record: { id: 'u1', imageRefs: ['absent.png'] },assetManifest: [{ filename: 'absent.png', kind: 'image', sha256: 'a'.repeat(64) }],sourceInstanceId: 'peer-a',});@@ -3366,19 +3433,17 @@ describe('peerSync', () => {it('never schedules a navigable peer asset from an incoming push', async () => {const result = await applyIncomingPush({kind: 'universe',- record: { id: 'u1' },+ record: { id: 'u1', imageRefs: ['peer.html', 'peer.svg', 'peer.png'], videoPath: 'clip.ogv' },assetManifest: [{ filename: 'peer.html', kind: 'image', sha256: 'a'.repeat(64) },{ filename: 'peer.svg', kind: 'image', sha256: 'b'.repeat(64) },{ filename: 'peer.png', kind: 'image', sha256: 'c'.repeat(64) },- { filename: 'memo.webm', kind: 'audio', sha256: 'd'.repeat(64) },- { filename: 'clip.ogv', kind: 'video', sha256: 'e'.repeat(64) },+ { filename: 'clip.ogv', kind: 'video', sha256: 'e'.repeat(64) },],sourceInstanceId: 'peer-a',});expect(result.missingAssets).toEqual([{ filename: 'peer.png', kind: 'image', sha256: 'c'.repeat(64) },- { filename: 'memo.webm', kind: 'audio', sha256: 'd'.repeat(64) },{ filename: 'clip.ogv', kind: 'video', sha256: 'e'.repeat(64) },]);expect(await readFile(join(PATHS.images, 'peer.html')).catch(() => null)).toBeNull();diff --git a/server/services/sharing/peerSyncAssets.js b/server/services/sharing/peerSyncAssets.jsindex f27f5feb47..ff9bd60d37 100644--- a/server/services/sharing/peerSyncAssets.js+++ b/server/services/sharing/peerSyncAssets.js@@ -39,12 +39,31 @@ import { peerSyncEvents, findPeerById } from './peerSyncShared.js';import { isStr } from '../../lib/textUtils.js';import { mapWithConcurrency } from '../../lib/mapWithConcurrency.js';-// In-flight gallery-image hashes while building one deck's manifest. Sized to-// libuv's default 4-thread fs pool with a little headroom, so a deck push can't-// starve unrelated fs work in the process.-const DECK_HASH_CONCURRENCY = 8;+// Bound file hashing to avoid starving unrelated filesystem work when a+// large record (especially a deck) advertises hundreds of images.+const ASSET_HASH_CONCURRENCY = 8;+// Filename-only references are shared by the sender builders and receiver+// admission. Never hash local files to decide whether a missing asset is owed.+function assetReference(filename, kind) {+ const safeName = sanitizeAssetFilename(filename);+ return safeName ? { filename: safeName, kind } : null;+}++function imageAssetReference(filename) {+ return assetReference(filename, 'image');+}++async function hashAssetReferences(references) {+ const entries = await mapWithConcurrency(references, ASSET_HASH_CONCURRENCY, (entry) => (+ entry.kind === 'image'+ ? hashImageForManifest(entry.filename)+ : hashSimpleAsset(entry.filename, entry.kind, directoryForAssetKind(entry.kind))+ ));+ return entries.filter(Boolean);+}+// --- Asset manifest -----------------------------------------------------/**@@ -63,23 +82,22 @@ const DECK_HASH_CONCURRENCY = 8;* diff report the asset as missing even though the sender can't fulfill.*/export async function buildAssetManifest(record) {+ return hashAssetReferences(referenceAssetManifest(record));+}++function referenceAssetManifest(record) {const refs = collectAssetReferences(record);const out = [];- // Each kind maps to a different on-disk directory. We compute SHA only- // for images via the sidecar cache (the canonical content-addressed path);- // image-refs + videos use `sha256File` on demand and DON'T persist a- // sidecar — they don't carry the gen-params provenance images do, and- // adding cache writes here would surprise the broader system.for (const filename of refs.directImageFilenames) {- const entry = await hashImageForManifest(filename);+ const entry = imageAssetReference(filename);if (entry) out.push(entry);}for (const filename of refs.directImageRefFilenames) {- const entry = await hashSimpleAsset(filename, 'image-ref', PATHS.imageRefs);+ const entry = assetReference(filename, 'image-ref');if (entry) out.push(entry);}for (const filename of refs.directVideoFilenames) {- const entry = await hashSimpleAsset(filename, 'video', PATHS.videos);+ const entry = assetReference(filename, 'video');if (entry) out.push(entry);}return out;@@ -116,14 +134,18 @@ export function collectionVideoRefToFilename(ref) {}export async function buildCollectionAssetManifest(collection) {+ return hashAssetReferences(referenceCollectionAssetManifest(collection));+}++export function referenceCollectionAssetManifest(collection) {const refs = collectCollectionAssetReferences(collection);const out = [];for (const filename of refs.directImageFilenames) {- const entry = await hashImageForManifest(filename);+ const entry = imageAssetReference(filename);if (entry) out.push(entry);}for (const ref of refs.directVideoFilenames) {- const entry = await hashSimpleAsset(collectionVideoRefToFilename(ref), 'video', PATHS.videos);+ const entry = assetReference(collectionVideoRefToFilename(ref), 'video');if (entry) out.push(entry);}return out;@@ -176,10 +198,13 @@ export async function hashSimpleAsset(filename, kind, sourceDir) {* does NOT have on disk OR whose local hash differs (peer has a newer* render under the same UUID — rare but possible during concurrent edits).*+ * `includeMismatched: false` admits only absent files, preserving existing+ * image bytes AND sidecars after a rejected record merge.+ ** The receiver will background-fetch each missing asset from the sender's* `/data/{images,image-refs,videos}/<filename>` static mount.*/-export async function diffAssetManifestAgainstLocal(manifest) {+export async function diffAssetManifestAgainstLocal(manifest, { includeMismatched = true } = {}) {if (!Array.isArray(manifest)) return [];const missing = [];for (const entry of manifest) {@@ -209,6 +234,7 @@ export async function diffAssetManifestAgainstLocal(manifest) {missing.push(sanitizedEntry);continue;}+ if (!includeMismatched) continue;// For images, compute the hash result once up front: it carries both the// sha256 AND the parsed sidecar JSON, so the sidecarSha256 comparison below// reuses it instead of re-reading the same file (one sidecar read per image@@ -290,27 +316,43 @@ export function directoryForAssetKind(kind) {* `hashImageForManifest` — can't ship bytes we don't have.*/export async function buildAuthorAssetManifest(author) {+ return hashAssetReferences(referenceAuthorAssetManifest(author));+}++export function referenceAuthorAssetManifest(author) {const filename = headshotImageFilename(author?.headshotImageUrl);if (!filename) return [];- const entry = await hashImageForManifest(filename);+ const entry = imageAssetReference(filename);return entry ? [entry] : [];}export async function buildArtistAssetManifest(artist) {+ return hashAssetReferences(referenceArtistAssetManifest(artist));+}++export function referenceArtistAssetManifest(artist) {const filename = portraitImageFilename(artist?.portraitImageUrl);if (!filename) return [];- const entry = await hashImageForManifest(filename);+ const entry = imageAssetReference(filename);return entry ? [entry] : [];}export async function buildAlbumAssetManifest(album) {+ return hashAssetReferences(referenceAlbumAssetManifest(album));+}++export function referenceAlbumAssetManifest(album) {const filename = coverImageFilename(album?.coverImageUrl);if (!filename) return [];- const entry = await hashImageForManifest(filename);+ const entry = imageAssetReference(filename);return entry ? [entry] : [];}export async function buildTrackAssetManifest(track) {+ return hashAssetReferences(referenceTrackAssetManifest(track));+}++export function referenceTrackAssetManifest(track) {// A track now carries a render history — every render's audio must ride the// manifest, not just the active pointer, so a peer can play any received card.// Union the active filename with each render's; de-dup (the active render's@@ -322,9 +364,7 @@ export async function buildTrackAssetManifest(track) {const f = trackAudioFilename(r?.audioFilename);if (f) filenames.add(f);}- const entries = await Promise.all(- [...filenames].map((filename) => hashSimpleAsset(filename, 'music', PATHS.music)),- );+ const entries = [...filenames].map((filename) => assetReference(filename, 'music'));return entries.filter(Boolean);}@@ -345,31 +385,35 @@ export async function buildTrackAssetManifest(track) {* asset is missing-local-file skipped silently (mirrors buildAuthorAssetManifest).*/export async function buildProjectAssetManifest(project) {+ return hashAssetReferences(referenceProjectAssetManifest(project));+}++export function referenceProjectAssetManifest(project) {const entries = [];const imageFilename = startingImageFilename(project?.startingImageFile);if (imageFilename) {- const imageEntry = await hashImageForManifest(imageFilename);+ const imageEntry = imageAssetReference(imageFilename);if (imageEntry) entries.push(imageEntry);}const musicBedFilename = project?.musicBed?.filename;if (isStr(musicBedFilename)) {- const musicEntry = await hashSimpleAsset(musicBedFilename, 'music', PATHS.music);+ const musicEntry = assetReference(musicBedFilename, 'music');if (musicEntry) entries.push(musicEntry);}const planSteps = Array.isArray(project?.plan?.steps) ? project.plan.steps : [];- const renderEntries = await Promise.all(planSteps.map((step) => {+ const renderEntries = planSteps.map((step) => {const jobId = step?.status === 'done' && isStr(step?.result?.jobId) && step.result.jobId.trim()? step.result.jobId.trim(): null;if (!jobId) return null;if (step.toolName === 'media_enqueueImageJob') {- return hashImageForManifest(`${jobId}.png`);+ return imageAssetReference(`${jobId}.png`);}if (step.toolName === 'media_enqueueVideoJob') {- return hashSimpleAsset(`${jobId}.mp4`, 'video', PATHS.videos);+ return assetReference(`${jobId}.mp4`, 'video');}return null;- }));+ });const seen = new Set(entries.map((entry) => `${entry.kind}:${entry.filename}`));for (const entry of renderEntries) {const key = entry && `${entry.kind}:${entry.filename}`;@@ -480,6 +524,10 @@ async function reconcileVideoThumbnail(filename, videoPath, peerId) {* dedup by `<kind>:<filename>` so two scenes pointing at the same render ship once.*/export async function buildMusicVideoAssetManifest(project) {+ return hashAssetReferences(await referenceMusicVideoAssetManifest(project));+}++export async function referenceMusicVideoAssetManifest(project, { linkedTrack } = {}) {const dedup = new Map();// Master audio: the uploaded basename and/or the linked track's audioFilename// (the create-UI path stores trackId with uploadedAudioFilename: null, so a@@ -487,7 +535,9 @@ export async function buildMusicVideoAssetManifest(project) {const audioNames = [];if (isStr(project?.uploadedAudioFilename)) audioNames.push(project.uploadedAudioFilename);if (isStr(project?.trackId)) {- const track = await getTrack(project.trackId).catch(() => null);+ const track = linkedTrack?.id === project.trackId+ ? linkedTrack+ : await getTrack(project.trackId).catch(() => null);if (isStr(track?.audioFilename)) audioNames.push(track.audioFilename);}// MuScriptor MIDI transcription of the master audio — lands under PATHS.music@@ -495,7 +545,7 @@ export async function buildMusicVideoAssetManifest(project) {// a `midiTranscription.filename` pointer whose bytes never arrive.if (isStr(project?.midiTranscription?.filename)) audioNames.push(project.midiTranscription.filename);for (const name of [...new Set(audioNames)]) {- const audio = await hashSimpleAsset(name, 'music', PATHS.music);+ const audio = assetReference(name, 'music');if (audio) dedup.set(`${audio.kind}:${audio.filename}`, audio);}const scenes = Array.isArray(project?.scenes) ? project.scenes : [];@@ -504,9 +554,9 @@ export async function buildMusicVideoAssetManifest(project) {)];if (videoIds.length) {const byId = await videoHistoryFilenamesById();- const entries = await Promise.all(videoIds.map((id) =>- hashSimpleAsset(byId.get(id) || collectionVideoRefToFilename(id), 'video', PATHS.videos),- ));+ const entries = videoIds.map((id) =>+ assetReference(byId.get(id) || collectionVideoRefToFilename(id), 'video'));+for (const entry of entries) {if (entry) dedup.set(`${entry.kind}:${entry.filename}`, entry);}@@ -515,7 +565,7 @@ export async function buildMusicVideoAssetManifest(project) {scenes.map((s) => (isStr(s?.referenceImageId) ? s.referenceImageId : null)).filter(Boolean),)];if (imageNames.length) {- const entries = await Promise.all(imageNames.map((name) => hashImageForManifest(name)));+ const entries = imageNames.map(imageAssetReference);for (const entry of entries) {if (entry) dedup.set(`${entry.kind}:${entry.filename}`, entry);}@@ -529,13 +579,17 @@ export async function buildMusicVideoAssetManifest(project) {* player resolves them directly as managed `<id>.mp4` files.*/export async function buildFableLoomAssetManifest(loom) {+ return hashAssetReferences(referenceFableLoomAssetManifest(loom));+}++export function referenceFableLoomAssetManifest(loom) {const nodes = (Array.isArray(loom?.episodes) ? loom.episodes : []).flatMap((episode) => (Array.isArray(episode?.nodes) ? episode.nodes : []));const dedup = new Map();const imageNames = [...new Set(- nodes.flatMap((node) => [node?.image, ...(node?.visualCanon?.characterAppearances || []).map((appearance) => appearance.referenceImage)]).filter(isStr),+ nodes.flatMap((node) => [node?.image, ...(Array.isArray(node?.visualCanon?.characterAppearances) ? node.visualCanon.characterAppearances : []).map((appearance) => appearance.referenceImage)]).filter(isStr),)];- for (const entry of await Promise.all(imageNames.map((name) => hashImageForManifest(name)))) {+ for (const entry of imageNames.map(imageAssetReference)) {if (entry) dedup.set(`${entry.kind}:${entry.filename}`, entry);}// Typed playback assets (hold loops, transition exit clips, and an explicit@@ -556,8 +610,8 @@ export async function buildFableLoomAssetManifest(loom) {}),)];if (videoIds.length > 0) {- const entries = await Promise.all(videoIds.map((id) =>- hashSimpleAsset(collectionVideoRefToFilename(id), 'video', PATHS.videos)));+ const entries = videoIds.map((id) =>+ assetReference(collectionVideoRefToFilename(id), 'video'));for (const entry of entries) {if (entry) dedup.set(`${entry.kind}:${entry.filename}`, entry);}@@ -580,8 +634,12 @@ export async function buildFableLoomAssetManifest(loom) {* file ship once. Text items carry no bytes.*/export async function buildBoardAssetManifest(board) {+ return hashAssetReferences(referenceBoardAssetManifest(board));+}++export function referenceBoardAssetManifest(board) {const dedup = new Map();- for (const it of board?.items || []) {+ for (const it of Array.isArray(board?.items) ? board.items : []) {// `video` items (#4188) carry a `video:<filename>` mediaKey (the ref IS// the on-disk filename, so collectionVideoRefToFilename passes it through// untouched) plus an optional poster-thumbnail imageUrl. Thumbnails under@@ -595,8 +653,8 @@ export async function buildBoardAssetManifest(board) {const safeName = sanitizeAssetFilename(parsed.ref);if (safeName) {pending.push(parsed.kind === 'video'- ? hashSimpleAsset(collectionVideoRefToFilename(safeName), 'video', PATHS.videos)- : hashImageForManifest(safeName));+ ? assetReference(collectionVideoRefToFilename(safeName), 'video')+ : imageAssetReference(safeName));}}}@@ -608,11 +666,11 @@ export async function buildBoardAssetManifest(board) {// universe-canon manifest uses); gallery `image` bytes go through the// sidecar-aware hashImageForManifest.pending.push(asset.kind === 'image-ref'- ? hashSimpleAsset(safeName, 'image-ref', PATHS.imageRefs)- : hashImageForManifest(safeName));+ ? assetReference(safeName, 'image-ref')+ : imageAssetReference(safeName));}}- for (const entry of await Promise.all(pending)) {+ for (const entry of pending) {if (entry) dedup.set(`${entry.kind}:${entry.filename}`, entry);}}@@ -639,6 +697,10 @@ export async function buildBoardAssetManifest(board) {* per mood-board item).*/export async function buildDeckAssetManifest(deck) {+ return hashAssetReferences(referenceDeckAssetManifest(deck));+}++export function referenceDeckAssetManifest(deck) {const filenames = new Set();for (const card of Array.isArray(deck?.cards) ? deck.cards : []) {for (const ref of Array.isArray(card?.imageRefs) ? card.imageRefs : []) {@@ -652,21 +714,25 @@ export async function buildDeckAssetManifest(deck) {const safe = sanitizeAssetFilename(sample?.imageRef);if (safe) filenames.add(safe);}- const entries = await mapWithConcurrency([...filenames], DECK_HASH_CONCURRENCY, hashImageForManifest);+ const entries = [...filenames].map(imageAssetReference);return entries.filter(Boolean);}export async function buildAssetManifestForSeries(series, issues, linkedCollection = null) {- const seriesAssets = await buildAssetManifest(series);+ return hashAssetReferences(referenceAssetManifestForSeries(series, issues, linkedCollection));+}++export function referenceAssetManifestForSeries(series, issues, linkedCollection = null) {+ const seriesAssets = referenceAssetManifest(series);const dedup = new Map(seriesAssets.map((a) => [`${a.kind}:${a.filename}`, a]));for (const issue of issues) {- const issueAssets = await buildAssetManifest(issue);+ const issueAssets = referenceAssetManifest(issue);for (const a of issueAssets) {dedup.set(`${a.kind}:${a.filename}`, a);}}if (linkedCollection) {- const collectionAssets = await buildAssetManifestForCollection(linkedCollection);+ const collectionAssets = referenceAssetManifestForCollection(linkedCollection);for (const a of collectionAssets) {dedup.set(`${a.kind}:${a.filename}`, a);}@@ -681,10 +747,14 @@ export async function buildAssetManifestForSeries(series, issues, linkedCollecti* `items[]` only ships once.*/export async function buildAssetManifestWithCollection(record, linkedCollection) {- const recordAssets = await buildAssetManifest(record);+ return hashAssetReferences(referenceAssetManifestWithCollection(record, linkedCollection));+}++export function referenceAssetManifestWithCollection(record, linkedCollection) {+ const recordAssets = referenceAssetManifest(record);const dedup = new Map(recordAssets.map((a) => [`${a.kind}:${a.filename}`, a]));if (linkedCollection) {- const collectionAssets = await buildAssetManifestForCollection(linkedCollection);+ const collectionAssets = referenceAssetManifestForCollection(linkedCollection);for (const a of collectionAssets) {dedup.set(`${a.kind}:${a.filename}`, a);}@@ -705,8 +775,12 @@ export async function buildAssetManifestWithCollection(record, linkedCollection)* `collectAssetReferences` and the `directoryForAssetKind` map.*/export async function buildAssetManifestForCollection(collection) {+ return hashAssetReferences(referenceAssetManifestForCollection(collection));+}++function referenceAssetManifestForCollection(collection) {const out = [];- for (const it of collection?.items || []) {+ for (const it of Array.isArray(collection?.items) ? collection.items : []) {if (!it || typeof it.ref !== 'string') continue;// Path-traversal guard: collection items can arrive from a peer (via// `linkedCollection` push or the snapshot-sync mediaCollections@@ -722,14 +796,14 @@ export async function buildAssetManifestForCollection(collection) {// Bare videoId → `<id>.mp4` via the shared helper (see// collectionVideoRefToFilename). `sanitizeAssetFilename` already ran on// `it.ref` above; the extension append is purely the on-disk naming rule.- const entry = await hashSimpleAsset(collectionVideoRefToFilename(safeName), 'video', PATHS.videos);+ const entry = assetReference(collectionVideoRefToFilename(safeName), 'video');if (entry) out.push(entry);} else {// Treat 'image' (and any unknown kind that isn't 'video') as a gallery// image — the receiver's diff path will only accept entries whose kind// maps to a known directory in `directoryForAssetKind`, so a junk kind// gets filtered there without polluting disk.- const entry = await hashImageForManifest(safeName);+ const entry = imageAssetReference(safeName);if (entry) out.push(entry);}}@@ -796,7 +870,7 @@ export function assetDestinationKey(kind, filename) {* cap. A future enhancement could pool 2-4 concurrent fetches if individual* universes routinely ship hundreds of assets.*/-export async function pullMissingAssetsFromPeer(senderInstanceId, missingAssets) {+export async function pullMissingAssetsFromPeer(senderInstanceId, missingAssets, { includeMismatched = true } = {}) {if (!isStr(senderInstanceId) || !Array.isArray(missingAssets) || missingAssets.length === 0) return;// Trust posture: `senderInstanceId` arrives in the push payload (the route// is Tailnet-only per the project's documented threat model — see@@ -818,7 +892,7 @@ export async function pullMissingAssetsFromPeer(senderInstanceId, missingAssets)}const base = peerBaseUrl(peer);for (const entry of missingAssets) {- await pullOneAsset(peer, base, entry).catch((err) => {+ await pullOneAsset(peer, base, entry, includeMismatched).catch((err) => {console.log(`⚠️ peerSync: asset pull ${entry.filename} from ${peer.name || senderInstanceId} failed: ${err.message}`);});}@@ -944,7 +1018,7 @@ async function pullOneWorkBody(peer, base, entry) {}}-async function pullOneAsset(peer, base, entry) {+async function pullOneAsset(peer, base, entry, includeMismatched) {const urlPrefix = ASSET_KIND_TO_URL_PREFIX[entry.kind];const localDir = directoryForAssetKind(entry.kind);// Re-validate the filename here even though the receiver already@@ -967,14 +1041,18 @@ async function pullOneAsset(peer, base, entry) {// (#3929). See assetWriteQueue.await assetWriteQueue(assetDestinationKey(entry.kind, safeName),- () => doPullOneAsset(peer, base, entry, urlPrefix, localDir, safeName),+ () => doPullOneAsset(peer, base, entry, urlPrefix, localDir, safeName, includeMismatched),);} finally {inflightPulls.delete(key);}}-async function doPullOneAsset(peer, base, entry, urlPrefix, localDir, safeName) {+async function doPullOneAsset(peer, base, entry, urlPrefix, localDir, safeName, includeMismatched) {+ // A missing asset can arrive while this stale push waits on the write queue.+ // Preserve its bytes and sidecar once another writer has filled the gap.+ const fullPath = join(localDir, safeName);+ if (!includeMismatched && existsSync(fullPath)) return;// Re-check disk against the advertised hash before spending a download. Two// distinct cases land here with the bytes already correct:// - sidecar-only divergence: the image bytes hash-match and@@ -1007,8 +1085,12 @@ async function doPullOneAsset(peer, base, entry, urlPrefix, localDir, safeName)const url = `${base}${urlPrefix}/${encodeURIComponent(safeName)}`;const buffer = await fetchCappedAssetBuffer(peer, url, safeName, ASSET_PULL_MAX_BYTES);if (!buffer) return;+ if (isStr(entry.sha256) && createHash('sha256').update(buffer).digest('hex') !== entry.sha256) {+ console.warn('⚠️ peerSync: discarded asset with mismatched sha256');+ return;+ }await ensureDir(localDir);- const fullPath = join(localDir, safeName);+ if (!includeMismatched && existsSync(fullPath)) return;// atomicWrite (temp + rename) so a crash mid-write doesn't leave a// half-written file that subsequent `diffAssetManifestAgainstLocal`// calls would see as "present" and stop re-requesting.diff --git a/server/services/sharing/peerSyncAssets.test.js b/server/services/sharing/peerSyncAssets.test.jsindex 95a091c6bc..03eff4e966 100644--- a/server/services/sharing/peerSyncAssets.test.js+++ b/server/services/sharing/peerSyncAssets.test.js@@ -1,5 +1,5 @@import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';-import { existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync, mkdirSync } from 'fs';+import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import { createHash } from 'crypto';@@ -400,6 +400,34 @@ describe('pullMissingAssetsFromPeer — unsafe and incomplete downloads (#5230)'if (tempRoot) rmSync(tempRoot, { recursive: true, force: true });});+ it('discards bytes whose advertised sha256 does not match before replacing local assets', async () => {+ const original = Buffer.from('local audio');+ const wrong = Buffer.from('wrong downloaded audio');+ writeMusic('protected.mp3', original);+ vi.mocked(peerFetch).mockResolvedValue(mkAssetResponse(wrong));+ const arrivals = await captureAssetArrivals(() => pullMissingAssetsFromPeer('peer-a', [+ { filename: 'protected.mp3', kind: 'music', sha256: sha(Buffer.from('advertised audio')) },+ { filename: 'absent.mp3', kind: 'music', sha256: sha(Buffer.from('advertised audio')) },+ ]));+ expect(readFileSync(join(tempRoot, 'music', 'protected.mp3'))).toEqual(original);+ expect(existsSync(join(tempRoot, 'music', 'absent.mp3'))).toBe(false);+ expect(arrivals).toEqual([]);+ });++ it('preserves an asset that arrives during a stale push download', async () => {+ const newer = Buffer.from('new local audio');+ const stale = Buffer.from('old remote audio');+ vi.mocked(peerFetch).mockImplementation(async () => {+ writeMusic('racing.mp3', newer);+ return mkAssetResponse(stale);+ });+ const arrivals = await captureAssetArrivals(() => pullMissingAssetsFromPeer('peer-a', [+ { filename: 'racing.mp3', kind: 'music', sha256: sha(stale) },+ ], { includeMismatched: false }));+ expect(readFileSync(join(tempRoot, 'music', 'racing.mp3'))).toEqual(newer);+ expect(arrivals).toEqual([]);+ });+it('rejects traversal-shaped filenames before fetching or touching disk', async () => {const unsafeNames = ['..', '../../secret.json', '/etc/passwd', 'folder\\secret.json'];diff --git a/server/services/sharing/peerSyncReceive.js b/server/services/sharing/peerSyncReceive.jsindex 106047966d..52c9ba8251 100644--- a/server/services/sharing/peerSyncReceive.js+++ b/server/services/sharing/peerSyncReceive.js@@ -384,7 +384,16 @@ export async function applyIncomingPush(payload, authorization) {// For local-ephemeral records, skip the diff entirely so we don't even// report a non-empty missingAssets back to the sender (which would// surface a "still syncing" UI for a record we silently refused).- const missingAssets = localEphemeral ? [] : await diffAssetManifestAgainstLocal(assetManifest);+ const references = !localEphemeral && record.deleted !== true && desc.referencedAssets+ ? await desc.referencedAssets(record, { issues, linkedCollection, linkedTrack })+ : [];+ const referencedKeys = new Set(references.map((entry) => `${entry.kind}:${entry.filename}`));+ const incomingAssets = Array.isArray(assetManifest) ? assetManifest : [];+ const ownAssets = incomingAssets.filter((entry) => entry && referencedKeys.has(`${entry.kind}:${entry.filename}`));+ if (ownAssets.length < incomingAssets.length) {+ console.warn(`⚠️ peerSync: ignored ${incomingAssets.length - ownAssets.length} unreferenced push assets`);+ }+ const missingAssets = await diffAssetManifestAgainstLocal(ownAssets, { includeMismatched: mergeResult?.applied === true });// Compute the deletedAt water-mark we can ack. Use the maximum across the// record + its issues + a bundled linkedTrack tombstone (#1858 bundles the@@ -433,7 +442,7 @@ export async function applyIncomingPush(payload, authorization) {// (missingAssets is already [] for localEphemeral above, so the worker// can never schedule pulls for opted-out records.)if (missingAssets.length > 0) {- pullMissingAssetsFromPeer(sourceInstanceId, missingAssets).catch((err) => {+ pullMissingAssetsFromPeer(sourceInstanceId, missingAssets, { includeMismatched: mergeResult?.applied === true }).catch((err) => {console.log(`⚠️ peerSync: asset pull from ${sourceInstanceId} failed: ${err.message}`);});}diff --git a/server/services/sharing/recordKinds.js b/server/services/sharing/recordKinds.jsindex 2f398e9933..966c255591 100644--- a/server/services/sharing/recordKinds.js+++ b/server/services/sharing/recordKinds.js@@ -31,6 +31,10 @@* (writersRoomWork's prose rides the separate `draftBodyManifest`; the other* four are body-less LWW records).*+ * `referencedAssets(record, envelope)` derives filename-only references using+ * the same walk as the sender builder, without depending on local asset bytes.+ * The five asset-less kinds omit it and cannot admit any generic push assets.+ ** `merge` is called uniformly as `desc.merge(records, { source,* senderSchemaVersions })` — every merger destructures at least `{ source }`;* the dozen that don't also use `senderSchemaVersions` simply ignore the@@ -70,6 +74,18 @@ import {buildBoardAssetManifest,buildFableLoomAssetManifest,buildDeckAssetManifest,+ referenceCollectionAssetManifest,+ referenceAuthorAssetManifest,+ referenceArtistAssetManifest,+ referenceAlbumAssetManifest,+ referenceTrackAssetManifest,+ referenceProjectAssetManifest,+ referenceMusicVideoAssetManifest,+ referenceFableLoomAssetManifest,+ referenceBoardAssetManifest,+ referenceDeckAssetManifest,+ referenceAssetManifestForSeries,+ referenceAssetManifestWithCollection,} from './peerSyncAssets.js';import { isNonBlankStr } from '../../lib/textUtils.js';@@ -79,60 +95,71 @@ export const RECORD_KINDS = Object.freeze({load: (id) => getUniverse(id, { includeDeleted: true }),merge: mergeUniversesFromSync,buildAssetManifest: null, // bundle-aware builder lives in buildPushPayload's universe hook+ referencedAssets: (record, { linkedCollection }) => referenceAssetManifestWithCollection(record, linkedCollection),hasEphemeral: true,},series: {load: (id) => getSeries(id, { includeDeleted: true }),merge: mergeSeriesFromSync,buildAssetManifest: null, // bundle-aware builder lives in buildPushPayload's series hook+ referencedAssets: (record, { issues, linkedCollection }) => referenceAssetManifestForSeries(record,+ (Array.isArray(issues) ? issues : []).filter((issue) => issue?.deleted !== true && issue?.ephemeral !== true), linkedCollection),hasEphemeral: true,},mediaCollection: {load: (id) => getCollection(id, { includeDeleted: true }),merge: mergeMediaCollectionsFromSync,buildAssetManifest: buildCollectionAssetManifest,+ referencedAssets: referenceCollectionAssetManifest,hasEphemeral: false,},author: {load: (id) => getAuthor(id, { includeDeleted: true }),merge: mergeAuthorsFromSync,buildAssetManifest: buildAuthorAssetManifest,+ referencedAssets: referenceAuthorAssetManifest,hasEphemeral: false,},artist: {load: (id) => getArtist(id, { includeDeleted: true }),merge: mergeArtistsFromSync,buildAssetManifest: buildArtistAssetManifest,+ referencedAssets: referenceArtistAssetManifest,hasEphemeral: false,},album: {load: (id) => getAlbum(id, { includeDeleted: true }),merge: mergeAlbumsFromSync,buildAssetManifest: buildAlbumAssetManifest,+ referencedAssets: referenceAlbumAssetManifest,hasEphemeral: false,},track: {load: (id) => getTrack(id, { includeDeleted: true }),merge: mergeTracksFromSync,buildAssetManifest: buildTrackAssetManifest,+ referencedAssets: referenceTrackAssetManifest,hasEphemeral: false,},creativeDirectorProject: {load: (id) => getProject(id, { includeDeleted: true }),merge: mergeProjectsFromSync,buildAssetManifest: buildProjectAssetManifest,+ referencedAssets: referenceProjectAssetManifest,hasEphemeral: false,},moodBoard: {load: (id) => getBoard(id, { includeDeleted: true }),merge: mergeBoardsFromSync,buildAssetManifest: buildBoardAssetManifest,+ referencedAssets: referenceBoardAssetManifest,hasEphemeral: false,},fableLoom: {load: (id) => getLoom(id, { includeDeleted: true }),merge: mergeLoomsFromSync,buildAssetManifest: buildFableLoomAssetManifest,+ referencedAssets: referenceFableLoomAssetManifest,// No ephemeral concept (syncWire.js's fableLoom wire case: "always// wire-syncable when present"). `classifyLocalRecord` had NO arm for this// kind before this table — a found loom always fell through to the@@ -166,6 +193,7 @@ export const RECORD_KINDS = Object.freeze({load: (id) => getMusicVideoProject(id, { includeDeleted: true }),merge: mergeMusicVideoProjectsFromSync,buildAssetManifest: buildMusicVideoAssetManifest,+ referencedAssets: referenceMusicVideoAssetManifest,// Documented drift (pre-#6843): applyIncomingPush's local-ephemeral lookup// special-cased this kind (`local?.ephemeral === true`, added by #1858),// but the store carries no ephemeral flag at all@@ -194,6 +222,7 @@ export const RECORD_KINDS = Object.freeze({load: (id) => getDeckForSync(id),merge: mergeDecksFromSync,buildAssetManifest: buildDeckAssetManifest,+ referencedAssets: referenceDeckAssetManifest,hasEphemeral: false,},});diff --git a/server/services/sharing/recordKinds.test.js b/server/services/sharing/recordKinds.test.jsindex f162724339..5394fe2d60 100644--- a/server/services/sharing/recordKinds.test.js+++ b/server/services/sharing/recordKinds.test.js@@ -37,6 +37,11 @@ describe('RECORD_KINDS registry completeness (#6843)', () => {expect(typeof desc.merge).toBe('function');expect(typeof desc.hasEphemeral).toBe('boolean');expect(desc.buildAssetManifest === null || typeof desc.buildAssetManifest === 'function').toBe(true);+ if (desc.buildAssetManifest || kind === 'universe' || kind === 'series') {+ expect(typeof desc.referencedAssets).toBe('function');+ } else {+ expect(desc.referencedAssets).toBeUndefined();+ }});it('only universe and series carry hasEphemeral:true — every other kind (including fableLoom and musicVideoProject, both documented drift fixes in #6843) has no ephemeral concept', () => {