Skip to content

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

fix: sandbox peer media and restrict inbound asset formats (#8402)

[._.]/ Adam Eivyf2d68ab81ac0
diff --git a/server/services/assetMounts.js b/server/services/assetMounts.js
index 8e3b94e341..e646dc0100 100644
--- a/server/services/assetMounts.js
+++ b/server/services/assetMounts.js
@@ -28,7 +28,15 @@ import { escapeRegExp } from '../lib/textUtils.js';
// URLs and relies on HTTP Range to resume partial downloads over flaky
// Tailnet links — losing range support here would silently force every
// retry to restart from byte 0 on a multi-MB PNG / video.
-const ASSET_STATIC_OPTS = { acceptRanges: true };
+const ASSET_STATIC_OPTS = {
+ acceptRanges: true,
+ setHeaders: (res) => {
+ // A peer can supply asset bytes. Keep even a directly opened HTML/SVG file
+ // from executing with the PortOS origin's host-control privileges.
+ res.setHeader('X-Content-Type-Options', 'nosniff');
+ res.setHeader('Content-Security-Policy', "sandbox; default-src 'none'; img-src 'self' data: blob:; media-src 'self'; style-src 'unsafe-inline'");
+ },
+};
// Vite names every chunk, entry, stylesheet and imported asset it emits under
// `dist/assets/` by content hash (`index-B5J1S4I5.js`), so the bytes behind one
diff --git a/server/services/assetMounts.test.js b/server/services/assetMounts.test.js
index e013eac0e0..93d057dd85 100644
--- a/server/services/assetMounts.test.js
+++ b/server/services/assetMounts.test.js
@@ -136,6 +136,18 @@ describe('the server-owned namespace terminators', () => {
expect(res.text).toBe('PNGBYTES');
});
+ it('sandboxes directly opened peer asset files on every media mount', async () => {
+ for (const dir of ['images', 'image-refs', 'videos', 'music', 'audio']) {
+ mkdirSync(join(tempRoot, dir), { recursive: true });
+ writeFileSync(join(tempRoot, dir, 'peer.html'), '<script>window.exploited = true</script>');
+ const res = await request(app).get(`/data/${dir}/peer.html`);
+ expect(res.status, dir).toBe(200);
+ expect(res.headers['x-content-type-options'], dir).toBe('nosniff');
+ expect(res.headers['content-security-policy'], dir).toContain('sandbox');
+ expect(res.headers['content-security-policy'], dir).toContain("default-src 'none'");
+ }
+ });
+
it('serves a local voice-profile benchmark from its dedicated mount', async () => {
const res = await request(app).get('/data/voice-profiles/voice-profile-1/benchmarks/v1/01-identity.wav');
expect(res.status).toBe(200);
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index f03f706ace..6cd5bf4545 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -3363,6 +3363,28 @@ describe('peerSync', () => {
expect(result.missingAssets).toHaveLength(1);
});
+ it('never schedules a navigable peer asset from an incoming push', async () => {
+ const result = await applyIncomingPush({
+ kind: 'universe',
+ record: { id: 'u1' },
+ 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) },
+ ],
+ 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();
+ expect(await readFile(join(PATHS.images, 'peer.svg')).catch(() => null)).toBeNull();
+ });
+
it('returns ackedDeletesUpTo for the sender (does NOT advance the local cursor on receive)', async () => {
// Cursors track "what peer X has acked of OUR local deletions" so
// tombstoneGc can prune our local tombstones once every subscribed
diff --git a/server/services/sharing/peerSyncAssets.js b/server/services/sharing/peerSyncAssets.js
index 1e4fd8665e..f27f5feb47 100644
--- a/server/services/sharing/peerSyncAssets.js
+++ b/server/services/sharing/peerSyncAssets.js
@@ -9,7 +9,7 @@
*
* Split out of the former 4,004-line peerSync.js (#1830).
*/
-import { join } from 'path';
+import { extname, join } from 'path';
import { existsSync } from 'fs';
import { createHash } from 'crypto';
import { PATHS, atomicWrite, readJSONFile, ensureDir, sha256File } from '../../lib/fileUtils.js';
@@ -192,6 +192,7 @@ export async function diffAssetManifestAgainstLocal(manifest) {
// entry. Reject anything that isn't a bare basename before any FS op.
const safeName = sanitizeAssetFilename(entry.filename);
if (!safeName) continue;
+ if (!hasAllowedAssetExtension(entry.kind, safeName)) continue;
// Build a sanitized projection: only the known fields the receiver needs
// to pull. Echoing the raw peer-supplied entry would amplify any
// junk fields it shipped (large strings, extra kinds, prototype-pollution
@@ -254,6 +255,24 @@ export async function diffAssetManifestAgainstLocal(manifest) {
return missing;
}
+// The receiving peer must never persist navigable HTML or SVG into an asset
+// mount on the PortOS origin. Keep these in step with the writers into each
+// directory, including catalog voice memos (.webm) and video uploads (.ogv).
+const ASSET_KIND_EXTENSIONS = {
+ image: new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.avif']),
+ 'image-ref': new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.avif']),
+ video: new Set(['.mp4', '.webm', '.mov', '.m4v', '.ogv']),
+ music: new Set(['.mp3', '.wav', '.ogg', '.m4a', '.flac', '.aac', '.opus']),
+ audio: new Set(['.mp3', '.wav', '.ogg', '.m4a', '.flac', '.aac', '.opus', '.webm']),
+};
+
+function hasAllowedAssetExtension(kind, filename) {
+ if (ASSET_KIND_EXTENSIONS[kind]?.has(extname(filename).toLowerCase())) return true;
+ // Do not echo a peer-controlled filename into the log (it can contain CR/LF).
+ console.warn(`peerSync: skipped unsupported ${kind} asset extension`);
+ return false;
+}
+
export function directoryForAssetKind(kind) {
if (kind === 'image') return PATHS.images;
if (kind === 'image-ref') return PATHS.imageRefs;
@@ -933,6 +952,7 @@ async function pullOneAsset(peer, base, entry) {
// against any future refactor that bypasses the diff path.
const safeName = sanitizeAssetFilename(entry.filename);
if (!urlPrefix || !localDir || !safeName) return;
+ if (!hasAllowedAssetExtension(entry.kind, safeName)) return;
// Dedup in-flight pulls — if the same (peer, kind, filename) is already
// being downloaded, skip rather than starting a second concurrent pull.
// The first pull's `asset-arrived` event will resolve the UI for both
diff --git a/server/services/sharing/peerSyncAssets.test.js b/server/services/sharing/peerSyncAssets.test.js
index 75cbadb74c..95a091c6bc 100644
--- a/server/services/sharing/peerSyncAssets.test.js
+++ b/server/services/sharing/peerSyncAssets.test.js
@@ -413,6 +413,16 @@ describe('pullMissingAssetsFromPeer — unsafe and incomplete downloads (#5230)'
expect(listAssetFiles('audio')).toEqual([]);
});
+ it('rejects unsupported extensions even when the pull worker is called directly', async () => {
+ const arrivals = await captureAssetArrivals(() => pullMissingAssetsFromPeer('peer-a', [
+ { filename: 'peer.svg', kind: 'image', sha256: 'unused' },
+ { filename: 'peer.html', kind: 'image', sha256: 'unused' },
+ ]));
+ expect(peerFetch).not.toHaveBeenCalled();
+ expect(arrivals).toEqual([]);
+ expect(listAssetFiles('images')).toEqual([]);
+ });
+
it('discards a truncated response without leaving destination or temporary files', async () => {
const body = Buffer.from('partial');
vi.mocked(peerFetch).mockResolvedValue(mkAssetResponse(body, body.length + 10));
diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.js
index 4c8d3ffb7e..fe48a0b9b2 100644
--- a/server/services/syncOrchestrator.js
+++ b/server/services/syncOrchestrator.js
@@ -127,7 +127,7 @@ async function syncImageFromPeer(peer, avatarPath) {
// Validate avatarPath is a safe relative image path under /data/images/
if (!avatarPath || avatarPath.includes('..') || !avatarPath.startsWith('/data/images/')) return;
const filename = avatarPath.split('/').pop();
- if (!filename || !/\.(png|jpg|jpeg|gif|webp|svg)$/i.test(filename)) return;
+ if (!filename || !/\.(png|jpg|jpeg|gif|webp|avif)$/i.test(filename)) return;
const localPath = join(PATHS.images, filename);
// Skip if we already have it
diff --git a/server/services/syncOrchestrator.test.js b/server/services/syncOrchestrator.test.js
index 9213df6bb7..68c40e386d 100644
--- a/server/services/syncOrchestrator.test.js
+++ b/server/services/syncOrchestrator.test.js
@@ -250,6 +250,18 @@ describe('syncOrchestrator', () => {
applyRemote.mockResolvedValue({ applied: false, count: 0 });
});
+ it('does not fetch or store a peer-supplied SVG avatar', async () => {
+ const { applyRemote } = await import('./dataSync.js');
+ applyRemote.mockResolvedValue({ applied: true, count: 1 });
+ mockFetch.mockResolvedValue({ ok: true, json: async () => ({
+ data: { avatarPath: '/data/images/peer.svg' }, checksum: 'avatar',
+ }) });
+ await syncWithPeer({ ...mockPeer, syncCategories: { brain: false, memory: false, character: true } });
+ expect(mockFetch.mock.calls.some(([url]) => String(url).includes('/data/images/peer.svg'))).toBe(false);
+ expect(writeFileGuarded).not.toHaveBeenCalled();
+ applyRemote.mockResolvedValue({ applied: false, count: 0 });
+ });
+
it.each([
['non-success response', () => new Response('unavailable', { status: 503 })],
['malformed JSON', () => new Response('{')],