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: make video downloads save reliably on mobile Safari
[._.]/ Adam Eivy3f29fdf44fe3
diff --git a/client/src/components/DownloadManager.jsx b/client/src/components/DownloadManager.jsxnew file mode 100644index 0000000000..dcf4adebf5--- /dev/null+++ b/client/src/components/DownloadManager.jsx@@ -0,0 +1,58 @@+import { useEffect, useRef, useState } from 'react';+import Modal from './ui/Modal.jsx';+import { assetDownloadUrl, installStandaloneDownloadHandler, prepareDownload } from '../lib/standaloneDownload.js';++// One app-level surface for all same-origin download links on share-capable+// touch browsers and Home Screen apps. The file stays available after canceling+// a share sheet, so another Save tap never downloads the video again.+export default function DownloadManager() {+ const [download, setDownload] = useState(null);+ const [file, setFile] = useState(null);+ const [error, setError] = useState('');+ const [sharing, setSharing] = useState(false);+ const pending = useRef(null);++ useEffect(() => {+ const uninstall = installStandaloneDownloadHandler((next) => {+ pending.current?.abort();+ const controller = new AbortController();+ pending.current = controller;+ setDownload(next);+ setFile(null);+ setError('');+ setSharing(false);+ prepareDownload(next, controller.signal).then((ready) => {+ if (!controller.signal.aborted) setFile(ready);+ }).catch((err) => {+ if (!controller.signal.aborted) setError(`Download failed: ${err.message}`);+ });+ });+ return () => { uninstall(); pending.current?.abort(); };+ }, []);++ const close = () => { pending.current?.abort(); setDownload(null); setFile(null); };+ const save = () => {+ const controller = pending.current;+ setSharing(true);+ setError('');+ // Invoke synchronously inside the tap, with no fetch/await before share.+ navigator.share({ files: [file] }).then(() => {+ if (!controller.signal.aborted) close();+ }).catch((err) => {+ if (!controller.signal.aborted && err.name !== 'AbortError') setError(`Could not open the share sheet: ${err.message}`);+ }).finally(() => { if (!controller.signal.aborted) setSharing(false); });+ };++ return <Modal open={Boolean(download)} onClose={close} ariaLabel="Save download" size="sm"+ panelClassName="bg-port-card border border-port-border rounded-xl p-4 space-y-3">+ <h2 className="text-lg font-semibold">Save download</h2>+ <p className="text-sm break-all">{download?.filename}</p>+ <p role="status" className="text-sm text-port-text-muted">{file ? 'Ready. Tap Save, then choose Save Video or Save to Files.' : error ? 'Use the browser download or close and try again.' : 'Preparing download…'}</p>+ {error && <p role="alert" className="text-sm text-port-error">{error}</p>}+ <div className="flex flex-wrap items-center gap-3">+ <button type="button" disabled={!file || sharing} onClick={save} className="min-h-[44px] rounded bg-port-accent text-port-bg px-4 disabled:opacity-50">{sharing ? 'Saving…' : 'Save'}</button>+ <button type="button" onClick={close} className="min-h-[44px] px-3">Close</button>+ {download && <a href={assetDownloadUrl(download.url)} download={download.filename} data-native-download target="_blank" rel="noopener noreferrer" className="min-h-[44px] inline-flex items-center text-sm text-port-accent">Browser download</a>}+ </div>+ </Modal>;+}diff --git a/client/src/components/DownloadManager.test.jsx b/client/src/components/DownloadManager.test.jsxnew file mode 100644index 0000000000..1b67d3dcb3--- /dev/null+++ b/client/src/components/DownloadManager.test.jsx@@ -0,0 +1,91 @@+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import DownloadManager from './DownloadManager.jsx';+import MediaCard from './media/MediaCard.jsx';+import RenderStatusPanel from './musicVideo/RenderStatusPanel.jsx';++const share = vi.fn();+beforeEach(() => {+ vi.stubGlobal('matchMedia', vi.fn(query => ({ matches: query === '(pointer: coarse)', addEventListener: vi.fn(), removeEventListener: vi.fn() })));+ vi.stubGlobal('navigator', { share, canShare: () => true });+ share.mockReset().mockResolvedValue();+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, blob: async () => new Blob(['video'], { type: 'application/octet-stream' }) }));+});+afterEach(() => { cleanup(); vi.unstubAllGlobals(); });++it.each(['touch browser', 'Home Screen app'])('prepares both video downloads in a %s, then shares only from a fresh Save tap', async (mode) => {+ if (mode === 'Home Screen app') window.matchMedia.mockImplementation(query => ({ matches: query === '(display-mode: standalone)' }));+ let finish;+ fetch.mockReturnValueOnce(new Promise(resolve => { finish = resolve; }));+ render(<>+ <DownloadManager />+ <MediaCard item={{ kind: 'video', key: 'video:clip', id: 'clip', downloadUrl: '/data/videos/clip.mp4', prompt: 'Example clip' }} showCollectionMenu={false} showMoodBoardMenu={false} />+ <RenderStatusPanel renderHistoryId="draft" finalVideo={{ src: '/data/videos/draft.mp4' }} />+ </>);+ fireEvent.click(screen.getByRole('link', { name: 'Download' }));+ expect(screen.getByRole('status')).toHaveTextContent('Preparing download');+ expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled();+ await act(async () => finish({ ok: true, blob: async () => new Blob(['video'], { type: 'application/octet-stream' }) }));+ expect(share).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ expect(share).toHaveBeenCalledWith({ files: [expect.objectContaining({ name: 'clip.mp4', type: 'video/mp4' })] });+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());+ fireEvent.click(screen.getByRole('link', { name: 'Download MP4' }));+ await waitFor(() => expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled());+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ expect(share.mock.calls[1][0].files[0].name).toBe('draft.mp4');+ expect(fetch.mock.calls.map(([url]) => new URL(url).search)).toEqual(['?download=1', '?download=1']);+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());+});++function renderLink() {+ return render(<><DownloadManager /><a href="/data/videos/example.mp4" download>Download example</a></>);+}++it('keeps the prepared file after share cancellation or refusal so Save can be retried', async () => {+ share.mockRejectedValueOnce(Object.assign(new Error('Canceled'), { name: 'AbortError' }))+ .mockRejectedValueOnce(new Error('Sharing blocked'));+ renderLink();+ fireEvent.click(screen.getByRole('link', { name: 'Download example' }));+ await waitFor(() => expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled());+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ await waitFor(() => expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled());+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ expect(await screen.findByRole('alert')).toHaveTextContent('Sharing blocked');+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());+ expect(fetch).toHaveBeenCalledTimes(1);+});++it.each(['HTTP error', 'unsupported file'])('shows a visible %s and provides a native fallback that bypasses interception', async (failure) => {+ if (failure === 'HTTP error') fetch.mockResolvedValue({ ok: false, status: 404 });+ else navigator.canShare = () => false;+ renderLink();+ fireEvent.click(screen.getByRole('link', { name: 'Download example' }));+ expect(await screen.findByRole('alert')).toHaveTextContent('Download failed');+ const fallback = screen.getByRole('link', { name: 'Browser download' });+ expect(fallback).toHaveAttribute('href', '/data/videos/example.mp4?download=1');+ expect(fallback).toHaveAttribute('target', '_blank');+ // Observe the capture handler's decision, then suppress actual happy-dom+ // navigation so this contract test never makes a real network request.+ fallback.addEventListener('click', event => {+ expect(event.defaultPrevented).toBe(false);+ event.preventDefault();+ }, { once: true });+ fireEvent.click(fallback);+ expect(fetch).toHaveBeenCalledTimes(1);+});++it('aborts a closed download and ignores its late response', async () => {+ let finish;+ fetch.mockReturnValueOnce(new Promise(resolve => { finish = resolve; }));+ renderLink();+ fireEvent.click(screen.getByRole('link', { name: 'Download example' }));+ const { signal } = fetch.mock.calls[0][1];+ fireEvent.click(screen.getByRole('button', { name: 'Close' }));+ expect(signal.aborted).toBe(true);+ await act(async () => finish({ ok: true, blob: async () => new Blob(['late']) }));+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();+ expect(share).not.toHaveBeenCalled();+});diff --git a/client/src/components/media/MediaCard.jsx b/client/src/components/media/MediaCard.jsxindex b47b80ee91..064abe301b 100644--- a/client/src/components/media/MediaCard.jsx+++ b/client/src/components/media/MediaCard.jsx@@ -6,6 +6,7 @@ import PinToMoodBoardMenu from './PinToMoodBoardMenu';import InlineConfirmRow from '../ui/InlineConfirmRow';import { loraDisplayName } from './normalize';import { formatDurationMs } from '../../utils/formatters';+import { assetDownloadUrl } from '../../lib/standaloneDownload.js';// Single card used everywhere a generated image/video appears in a grid:// the Image Gen page's recent gallery, the Video Gen page's recent renders,@@ -242,7 +243,7 @@ function MediaCard({{showCollectionMenu && <AddToCollectionMenu item={item} />}{showMoodBoardMenu && <PinToMoodBoardMenu item={item} />}<a- href={downloadUrl}+ href={assetDownloadUrl(downloadUrl)}downloadclassName="shrink-0 px-1.5 py-1 bg-port-border hover:bg-port-border/70 text-white text-[10px] rounded flex items-center justify-center"title="Download"diff --git a/client/src/components/musicVideo/RenderStatusPanel.jsx b/client/src/components/musicVideo/RenderStatusPanel.jsxindex 36b2df0221..9cdadf6297 100644--- a/client/src/components/musicVideo/RenderStatusPanel.jsx+++ b/client/src/components/musicVideo/RenderStatusPanel.jsx@@ -2,6 +2,7 @@ import Banner from '../ui/Banner.jsx';import { useRef } from 'react';import { Film, Download, Maximize2, AlertTriangle } from 'lucide-react';import { STALE_RENDER_MESSAGE } from '../../lib/musicVideoStages.js';+import { assetDownloadUrl } from '../../lib/standaloneDownload.js';// The final-render surface: a progress bar while the assemble job runs, and the// finished MP4 (inline player + download + Media History deep link) once the@@ -40,9 +41,9 @@ export default function RenderStatusPanel({<div className="flex items-center gap-2 text-xs">{finalVideo?.src && (<a- href={finalVideo.src}+ href={assetDownloadUrl(finalVideo.src)}download- className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1 hover:bg-port-border/40"+ className="min-h-[44px] sm:min-h-0 flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1 hover:bg-port-border/40"><Download size={13} /> Download MP4</a>diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 686c8f9c8d..ecdcb27b5a 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -174,7 +174,7 @@ grep -i "what you want to do" client/src/lib/README.md| `dndKeyboardCoordinates.js` | `createFreeDroppableKeyboardCoordinates({ isSkipped? })` + `keyboardAwareCollisionDetection` — build a `KeyboardSensor` `coordinateGetter` for a `DndContext` whose drop targets are free `useDroppable` zones (no `SortableContext`): arrow keys JUMP to the adjacent zone in visual order instead of nudging 25px. Use it in `LibraryPane` / `GoalsListView`-shaped surfaces; a sortable list uses `@dnd-kit/sortable`'s `sortableKeyboardCoordinates` instead. Pair the getter with `keyboardAwareCollisionDetection` (keeps `rectIntersection` for pointer drags, `closestCenter` for keyboard ones) so adding keyboard support does not change where a mouse drop lands. || `dndTransform.js` | `dndTransformToCss(transform)` — render a dnd-kit `useSortable` transform (`{ x, y, scaleX, scaleY }` or `null`) as a CSS `transform` string. Owned replacement for `@dnd-kit/utilities`' `CSS.Transform.toString()`; use it in every `useSortable` style object instead of re-adding that dependency. || `downloadBlob.js` | `downloadBlob(data, filename, type?)` — trigger a browser "Save as…" for a Blob / ArrayBuffer / typed array / string, with object-URL + temporary `<a>` cleanup. Use instead of inlining `URL.createObjectURL` + `<a download>`. |-| `standaloneDownload.js` | `installStandaloneDownloadHandler()` — in an iOS Home Screen PWA, routes same-origin `<a download>` clicks through the native share sheet instead of navigating to a dead-end Quick Look page; `isStandalonePwa()`. |+| `standaloneDownload.js` | `installStandaloneDownloadHandler(onDownload)` delegates same-origin download links on share-capable touch browsers / Home Screen apps to `DownloadManager`; `prepareDownload` fetches a File for a fresh Save tap, `assetDownloadUrl` requests an attachment from static mounts, and `isStandalonePwa` detects Home Screen mode. || `extensionErrors.js` | `isExtensionError(payload)` — true when an error report came from a browser extension's injected content script rather than from PortOS. Re-exported from `server/lib/extensionErrors.js`, which the ingest route filters on. || `firstRunMissions.js` | Dashboard first-run missions (#5640). `FIRST_RUN_MISSIONS` is the four-slice catalog (Creative studio → `/start-story`, Personal knowledge → `/brain/inbox`, Run my machines → `/apps`, Delegate work → `/cos/tasks`) plus the matching Settings → Features ids each mission writes. `shouldShowFirstRunCard` / `parseFirstRunQueryParam` / `featuresToEnable` are the show/hide and write-set helpers — `/` only, session dismiss vs durable `hideFirstRunCard`, `?firstRun=` force on/off. Pure / React-free; the card lives in `components/onboarding/`. || `genUtils.js` | Shared bits between Image Gen and Video Gen pages. |diff --git a/client/src/lib/standaloneDownload.js b/client/src/lib/standaloneDownload.jsindex 20350074be..7dd525bf4f 100644--- a/client/src/lib/standaloneDownload.js+++ b/client/src/lib/standaloneDownload.js@@ -1,9 +1,6 @@-// iOS Home Screen (standalone) PWAs have no browser chrome: a tap on-// `<a download>` navigates the whole app to Quick Look's file preview, which has-// no back affordance, so the user must swipe-kill and relaunch. In that mode we-// intercept same-origin `a[download]` clicks, fetch the bytes, and hand them to-// the native share sheet (Save Image / Save Video / Files) — the app never-// navigates. Everywhere else the default download behavior is untouched.+// Mobile downloads use a visible preparation step, followed by a fresh tap to+// share/save. Fetching a large video can outlive Safari's transient activation;+// never call navigator.share automatically after the network request.export function isStandalonePwa() {if (typeof window === 'undefined') return false;@@ -24,35 +21,39 @@ function filenameFor(anchor, url) {return last || 'download';}-export async function shareDownload(anchor) {- const url = new URL(anchor.href, window.location.href);- const filename = filenameFor(anchor, url);- const res = await fetch(url.href, { credentials: 'same-origin' });+// Ask the static mount for an attachment while leaving preview URLs inline.+export function assetDownloadUrl(href) {+ if (!href) return href;+ const url = new URL(href, window.location.href);+ if (url.origin !== window.location.origin || !url.pathname.startsWith('/data/')) return href;+ url.searchParams.set('download', '1');+ return `${url.pathname}${url.search}${url.hash}`;+}++export async function prepareDownload({ url, filename }, signal) {+ const res = await fetch(url, { credentials: 'same-origin', signal });if (!res.ok) throw new Error(`HTTP ${res.status}`);const blob = await res.blob();const ext = filename.split('.').pop()?.toLowerCase();const type = blob.type && blob.type !== 'application/octet-stream' ? blob.type : (MIME_BY_EXT[ext] || blob.type);const file = new File([blob], filename, { type });- if (!navigator.canShare?.({ files: [file] })) throw new Error('share unsupported');- await navigator.share({ files: [file] });+ if (!navigator.canShare?.({ files: [file] })) throw new Error('This file cannot be saved with the share sheet. Use the browser download below.');+ return file;}// Returns an uninstall function. Capture phase so it runs before the browser's// default download navigation.-export function installStandaloneDownloadHandler() {- if (!isStandalonePwa() || typeof navigator.share !== 'function') return () => {};+export function installStandaloneDownloadHandler(onDownload) {+ const mobile = isStandalonePwa() || window.matchMedia?.('(pointer: coarse)')?.matches;+ if (!mobile || typeof navigator.share !== 'function' || typeof navigator.canShare !== 'function') return () => {};const onClick = (event) => {- if (event.defaultPrevented || event.button > 0) return;+ if (event.defaultPrevented || event.button > 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;const anchor = event.target?.closest?.('a[download][href]');- if (!anchor) return;+ if (!anchor || anchor.hasAttribute('data-native-download')) return;const url = new URL(anchor.href, window.location.href);if (url.origin !== window.location.origin) return;event.preventDefault();- shareDownload(anchor).catch((err) => {- // User dismissing the share sheet is not an error.- if (err?.name === 'AbortError') return;- console.error(`❌ Download share failed: ${err.message}`);- });+ onDownload({ url: url.href, filename: filenameFor(anchor, url) });};document.addEventListener('click', onClick, true);return () => document.removeEventListener('click', onClick, true);diff --git a/client/src/lib/standaloneDownload.test.js b/client/src/lib/standaloneDownload.test.jsindex e24fad56e2..dde3d02260 100644--- a/client/src/lib/standaloneDownload.test.js+++ b/client/src/lib/standaloneDownload.test.js@@ -1,33 +1,41 @@-// @vitest-environment happy-dom-import { describe, it, expect, vi, afterEach } from 'vitest';-import { installStandaloneDownloadHandler } from './standaloneDownload.js';+import { afterEach, expect, it, vi } from 'vitest';+import { installStandaloneDownloadHandler, assetDownloadUrl } from './standaloneDownload.js';-describe('installStandaloneDownloadHandler', () => {- afterEach(() => { vi.unstubAllGlobals(); document.body.innerHTML = ''; });+afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); document.body.innerHTML = ''; });- it('shares a same-origin a[download] instead of navigating when standalone', async () => {- const share = vi.fn().mockResolvedValue();- Object.defineProperty(window.navigator, 'standalone', { value: true, configurable: true });- Object.defineProperty(navigator, 'share', { value: share, configurable: true });- Object.defineProperty(navigator, 'canShare', { value: () => true, configurable: true });- vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, blob: async () => new Blob(['x'], { type: 'video/mp4' }) }));- const off = installStandaloneDownloadHandler();- document.body.innerHTML = '<a id="a" href="/data/videos/clip.mp4" download>d</a>';- const ev = new MouseEvent('click', { bubbles: true, cancelable: true });- document.getElementById('a').dispatchEvent(ev);- expect(ev.defaultPrevented).toBe(true);- await vi.waitFor(() => expect(share).toHaveBeenCalled());- expect(share.mock.calls[0][0].files[0].name).toBe('clip.mp4');- off();- });+it('leaves native downloads alone on desktop, without file sharing, and for external or modified links', () => {+ const onDownload = vi.fn();+ vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: false })));+ vi.stubGlobal('navigator', { share: vi.fn(), canShare: () => true });+ document.body.innerHTML = '<a href="/data/videos/clip.mp4" download>Download</a>';+ const click = (options) => {+ const event = new MouseEvent('click', { bubbles: true, cancelable: true, ...options });+ const anchor = document.querySelector('a');+ anchor.addEventListener('click', event => {+ expect(event.defaultPrevented).toBe(false);+ event.preventDefault();+ }, { once: true });+ anchor.dispatchEvent(event);+ };+ let off = installStandaloneDownloadHandler(onDownload);+ click();+ off();+ vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true })));+ vi.stubGlobal('navigator', {});+ off = installStandaloneDownloadHandler(onDownload);+ click();+ off();+ vi.stubGlobal('navigator', { share: vi.fn(), canShare: () => true });+ off = installStandaloneDownloadHandler(onDownload);+ click({ ctrlKey: true });+ document.querySelector('a').href = 'https://example.org/clip.mp4';+ click();+ off();+ expect(onDownload).not.toHaveBeenCalled();+});- it('leaves clicks alone outside standalone mode', () => {- Object.defineProperty(window.navigator, 'standalone', { value: false, configurable: true });- const off = installStandaloneDownloadHandler();- document.body.innerHTML = '<a id="a" href="/x.mp4" download>d</a>';- const ev = new MouseEvent('click', { bubbles: true, cancelable: true });- document.getElementById('a').dispatchEvent(ev);- expect(ev.defaultPrevented).toBe(false);- off();- });+it('adds attachment semantics only to local data URLs and preserves cache parameters', () => {+ expect(assetDownloadUrl('/data/videos/clip.mp4?_t=2')).toBe('/data/videos/clip.mp4?_t=2&download=1');+ expect(assetDownloadUrl('https://example.org/clip.mp4')).toBe('https://example.org/clip.mp4');+ expect(assetDownloadUrl('/api/music-video/example/sharing-copy/download')).toBe('/api/music-video/example/sharing-copy/download');});diff --git a/client/src/main.jsx b/client/src/main.jsxindex e492f28183..7172c8e8ac 100644--- a/client/src/main.jsx+++ b/client/src/main.jsx@@ -10,14 +10,13 @@ import { ThemeProvider } from './components/ThemeContext';import { isStaleChunkError, reloadOnceForStaleChunk } from './utils/staleChunkReload';import { reportClientError } from './lib/clientErrorReporter';import { registerServiceWorker } from './lib/registerServiceWorker';-import { installStandaloneDownloadHandler } from './lib/standaloneDownload';+import DownloadManager from './components/DownloadManager';import App from './App';import './index.css';// Offline app-shell + low-bandwidth asset caching (production, secure-context// only — no-op in dev and over plain-HTTP Tailnet). See lib/registerServiceWorker.registerServiceWorker();-installStandaloneDownloadHandler();// Start checking for a newer build as soon as a chunk preload fails. Vite also// emits this for module evaluation errors, so the recovery helper reloads only@@ -74,6 +73,7 @@ const router = createBrowserRouter([element: (<><App />+ <DownloadManager />{/* Theme effects (scanlines, grid floor, aurora, sweep, grain) paint onthis element's pseudo-elements and children — see the "Theme effectslayer" in index.css. Each child is unstyled, and so inert, until itsdiff --git a/server/services/assetMounts.js b/server/services/assetMounts.jsindex 0e150c4578..65e4f38950 100644--- a/server/services/assetMounts.js+++ b/server/services/assetMounts.js@@ -16,6 +16,7 @@*/import express from 'express';import { join } from 'path';+import { z } from 'zod';import { PATHS } from '../lib/fileUtils.js';import { ServerError, sendErrorResponse } from '../lib/errorHandler.js';import { ASSET_ROUTE_PREFIXES, SERVER_OWNED_PREFIXES } from '../lib/assetRoutePrefixes.js';@@ -32,7 +33,8 @@ import { hostedAssetFallback } from './peerHostedMedia.js';// retry to restart from byte 0 on a multi-MB PNG / video.const ASSET_STATIC_OPTS = {acceptRanges: true,- setHeaders: (res) => {+ setHeaders: (res, filePath) => {+ if (res.locals.assetDownload) res.attachment(filePath);// 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');@@ -41,6 +43,15 @@ const ASSET_STATIC_OPTS = {};const IMAGE_THUMBNAIL_STATIC_OPTS = { ...ASSET_STATIC_OPTS, maxAge: 24 * 60 * 60 * 1000 };+const assetDownloadQuerySchema = z.object({ download: z.literal('1').optional() }).passthrough();+const markDownloadRequest = (req, res, next) => {+ const query = assetDownloadQuerySchema.safeParse(req.query);+ // Set attachment headers only when a local file or hosted stream succeeds,+ // so a missing/invalid asset still returns the ordinary error response.+ res.locals.assetDownload = query.success && query.data.download === '1';+ next();+};+// 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// of those URLs can never change — a rebuild produces new names, and the@@ -182,7 +193,7 @@ function toRouteMatcher(pattern) {export function mountAssetRoutes(app, ownedPrefixes = SERVER_OWNED_PREFIXES) {ASSET_MOUNTS.forEach(({ route, dir, gate }) => {const options = route === '/data/image-thumbnails' ? IMAGE_THUMBNAIL_STATIC_OPTS : ASSET_STATIC_OPTS;- app.use(route, ...(gate ? [gate] : []), express.static(dir(), options));+ app.use(route, ...(gate ? [gate] : []), markDownloadRequest, express.static(dir(), options));// Media a `host`-mode peer keeps: local file absent → stream from the peer.if (HOSTED_FALLBACK_ROUTES.has(route)) app.use(route, hostedAssetFallback(route));});diff --git a/server/services/assetMounts.test.js b/server/services/assetMounts.test.jsindex b9efa26c43..27d12f9d16 100644--- a/server/services/assetMounts.test.js+++ b/server/services/assetMounts.test.js@@ -72,6 +72,28 @@ beforeAll(async () => {});describe('the server-owned namespace terminators', () => {+ it('serves explicit video downloads as attachments while previews retain inline and range behavior', async () => {+ mkdirSync(join(tempRoot, 'videos'), { recursive: true });+ writeFileSync(join(tempRoot, 'videos', 'example.mp4'), 'VIDEOBYTES');+ const preview = await request(app).get('/data/videos/example.mp4');+ expect(preview.status).toBe(200);+ expect(preview.headers['content-disposition']).toBeUndefined();+ const download = await request(app).get('/data/videos/example.mp4?download=1');+ expect(download.status).toBe(200);+ expect(download.headers['content-disposition']).toBe('attachment; filename="example.mp4"');+ expect(download.headers['content-type']).toContain('video/mp4');+ expect(download.headers['content-security-policy']).toContain('sandbox');+ expect(download.headers['x-content-type-options']).toBe('nosniff');+ const range = await request(app).get('/data/videos/example.mp4?download=1').set('Range', 'bytes=0-3');+ expect(range.status).toBe(206);+ expect(range.headers['content-range']).toBe('bytes 0-3/10');+ expect(range.headers['content-disposition']).toContain('attachment;');+ const missing = await request(app).get('/data/videos/missing.mp4?download=1');+ expect(missing.status).toBe(404);+ expect(missing.body).toMatchObject({ code: 'NOT_FOUND' });+ expect(missing.headers['content-disposition']).toBeUndefined();+ });+it('never serves the private API key store even when the file exists', async () => {mkdirSync(join(tempRoot, 'private'), { recursive: true });writeFileSync(join(tempRoot, 'private/api-keys.json'), '{"example":"example-secret"}');diff --git a/server/services/peerHostedMedia.js b/server/services/peerHostedMedia.jsindex 3f33020bad..7ae764fa82 100644--- a/server/services/peerHostedMedia.js+++ b/server/services/peerHostedMedia.js@@ -224,6 +224,7 @@ async function streamFromPeer(peer, path, req, res, drop) {return;}res.status(upstream.status);+ if (res.locals.assetDownload) res.attachment(decodeURIComponent(basename(path)));for (const name of ['content-type', 'content-length', 'content-range', 'accept-ranges', 'last-modified', 'etag']) {const value = upstream.headers[name];if (value) res.setHeader(name, value);diff --git a/server/services/peerHostedMedia.test.js b/server/services/peerHostedMedia.test.jsindex 1ae1e64bed..7d7e3a0e84 100644--- a/server/services/peerHostedMedia.test.js+++ b/server/services/peerHostedMedia.test.js@@ -111,11 +111,12 @@ describe('static-mount fallback', () => {expect(streamRequest).not.toHaveBeenCalled();});- it('forwards Range so a hosted video can be scrubbed', async () => {+ it('forwards Range and retains attachment semantics when downloading a hosted video', async () => {await markHosted(PEER.instanceId, [{ kind: 'video', filename: 'clip.mp4' }]);streamRequest.mockResolvedValue(upstream('PART', 206, { 'content-type': 'video/mp4', 'content-range': 'bytes 0-3/100' }));- const res = await request(app).get('/data/videos/clip.mp4').set('Range', 'bytes=0-3');+ const res = await request(app).get('/data/videos/clip.mp4?download=1').set('Range', 'bytes=0-3');expect(res.status).toBe(206);+ expect(res.headers['content-disposition']).toBe('attachment; filename="clip.mp4"');expect(streamRequest.mock.calls[0][1].headers.Range).toBe('bytes=0-3');});