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
address review (claude): stop the preflight lying about what it verified
[._.]/ Adam Eivya883f45db90c
diff --git a/client/src/components/games/GameBindings.jsx b/client/src/components/games/GameBindings.jsxindex 100f7ce347..a84144e17d 100644--- a/client/src/components/games/GameBindings.jsx+++ b/client/src/components/games/GameBindings.jsx@@ -1,19 +1,25 @@import { useMemo, useState } from 'react';-import { AlertTriangle, CheckCircle2, Music2, PersonStanding, Plus, Unlink } from 'lucide-react';+import { AlertTriangle, CheckCircle2, HelpCircle, Music2, PersonStanding, Plus, Unlink } from 'lucide-react';import Pill from '../ui/Pill.jsx';const selectClass = 'w-full min-h-[44px] rounded-lg border border-port-border bg-port-bg px-3 py-2 text-sm text-white';const actionClass = 'inline-flex min-h-[44px] items-center justify-center gap-2 rounded-lg bg-port-accent px-3 py-2 text-sm font-medium text-white disabled:opacity-50';-// Anything the preflight didn't mark `ready` — including an asset it hasn't-// reported on yet — reads as needing attention. Sprites and music share the-// mapping so a new status can't render one way in one list and another in the-// other.+// Sprites and music share this mapping so a new status can't render one way in+// one list and another in the other. Three outcomes, deliberately distinct:+// no preflight result at all (it hasn't loaded, or the fetch failed) is+// UNKNOWN, not a warning — painting every asset amber because verification is+// unavailable claims a problem nobody detected. An unrecognized status still+// falls to `blocked`, which is the conservative read for a real verdict.const HEALTH_TONES = {ready: { Icon: CheckCircle2, className: 'text-emerald-400' },blocked: { Icon: AlertTriangle, className: 'text-amber-400' },+ unknown: { Icon: HelpCircle, className: 'text-gray-500' },+};+const healthTone = (health) => {+ if (!health) return HEALTH_TONES.unknown;+ return HEALTH_TONES[health.status] || HEALTH_TONES.blocked;};-const healthTone = (health) => HEALTH_TONES[health?.status] || HEALTH_TONES.blocked;function BindingRow({ label, detail, health, disabled, onUnbind, unbindTitle }) {const { Icon, className } = healthTone(health);diff --git a/client/src/components/games/GameCompilePanel.jsx b/client/src/components/games/GameCompilePanel.jsxindex b67e47db80..c99c247663 100644--- a/client/src/components/games/GameCompilePanel.jsx+++ b/client/src/components/games/GameCompilePanel.jsx@@ -3,6 +3,7 @@ import {Boxes,CheckCircle2,CircleDashed,+ HelpCircle,Play,RefreshCw,ShieldCheck,@@ -31,6 +32,14 @@ const statusStyle = {label: 'Not built',className: 'border-port-border bg-port-bg/60 text-gray-400',},+ // "The preflight could not be read" is NOT "nothing is built" — collapsing+ // the two would show "Not built" above a details block describing the bundle+ // that exists, and would leave Build enabled on an unverified tree.+ unavailable: {+ icon: HelpCircle,+ label: 'Unverified',+ className: 'border-port-warning/30 bg-port-warning/10 text-port-warning',+ },};export default function GameCompilePanel({@@ -42,11 +51,17 @@ export default function GameCompilePanel({compileError,onCompile,onLaunch,+ onRetryIntegrity,}) {const current = game.compiledManifest;- const bundleStatus = statusStyle[integrity?.bundle?.status] || statusStyle.missing;+ // Three distinct states, deliberately not collapsed: still fetching, fetched+ // and reporting, and fetch failed. Only the middle one can unblock a build.+ const unavailable = !loadingIntegrity && !integrity;+ const bundleStatus = unavailable+ ? statusStyle.unavailable+ : statusStyle[integrity?.bundle?.status] || statusStyle.missing;const StatusIcon = bundleStatus.icon;- const blocked = integrity && !integrity.readyToCompile;+ const blocked = !integrity || !integrity.readyToCompile;const issues = integrity?.issues || [];return (<section className="rounded-xl border border-port-border bg-port-card p-4">@@ -66,7 +81,9 @@ export default function GameCompilePanel({onClick={onCompile}disabled={compiling || loadingIntegrity || blocked}className="inline-flex min-h-[44px] items-center justify-center gap-2 rounded-lg bg-port-accent px-4 py-2 text-sm font-medium text-white disabled:opacity-50"- title={blocked ? 'Resolve the asset integrity blockers first' : undefined}+ title={unavailable+ ? 'Asset verification is unavailable — retry it first'+ : blocked ? 'Resolve the asset integrity blockers first' : undefined}><RefreshCw className={`h-4 w-4 ${compiling ? 'animate-spin' : ''}`} aria-hidden="true" />{compiling ? 'Verifying…' : current ? 'Rebuild & verify' : 'Build & verify'}@@ -104,6 +121,29 @@ export default function GameCompilePanel({</div></div>+ {unavailable && (+ <Banner+ tone="warning"+ size="md"+ icon={AlertTriangle}+ title="Asset verification is unavailable"+ className="mt-4"+ actions={onRetryIntegrity ? (+ <button+ type="button"+ onClick={onRetryIntegrity}+ className="inline-flex min-h-[44px] items-center gap-2 rounded-lg border border-port-warning/40 px-3 py-2 text-sm font-medium"+ >+ <RefreshCw className="h-4 w-4" aria-hidden="true" />+ Retry+ </button>+ ) : undefined}+ >+ The preflight could not be read, so nothing below reflects the current state of this+ game's assets. Building and starting stay disabled until it succeeds.+ </Banner>+ )}+{issues.length > 0 && (<Bannertone="warning"diff --git a/client/src/components/games/GameCompilePanel.test.jsx b/client/src/components/games/GameCompilePanel.test.jsxindex 2a82ff112d..578714e35a 100644--- a/client/src/components/games/GameCompilePanel.test.jsx+++ b/client/src/components/games/GameCompilePanel.test.jsx@@ -60,6 +60,48 @@ describe('GameCompilePanel', () => {expect(screen.getByRole('alert')).toHaveTextContent('does not match its recorded hash');});+ it('reports a failed preflight as unverified, not as "not built"', () => {+ // A failed integrity fetch must not read the same as "no bundle exists" —+ // that would leave Build enabled on an unverified tree and label an existing+ // bundle "Not built" right above the block describing it.+ const onRetryIntegrity = vi.fn();+ render(+ <GameCompilePanel+ game={{ compiledManifest: { version: 2, spriteCount: 1, musicCount: 0, builtAt: '2026-07-28T12:00:00.000Z', manifestPath: 'manifests/game-assets-v2.json' } }}+ integrity={null}+ loadingIntegrity={false}+ onCompile={() => {}}+ onLaunch={() => {}}+ onRetryIntegrity={onRetryIntegrity}+ />,+ );++ expect(screen.getByText('Unverified')).toBeInTheDocument();+ expect(screen.queryByText('Not built')).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Rebuild & verify' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Start game' })).toBeDisabled();++ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(onRetryIntegrity).toHaveBeenCalledOnce();+ });++ it('does not offer to build while the preflight is still loading', () => {+ render(+ <GameCompilePanel+ game={game}+ integrity={null}+ loadingIntegrity+ onCompile={() => {}}+ onLaunch={() => {}}+ />,+ );++ expect(screen.getByText('Checking…')).toBeInTheDocument();+ // Loading is not the same as failed — no error banner, no retry.+ expect(screen.queryByRole('button', { name: 'Retry' })).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Build & verify' })).toBeDisabled();+ });+it('allows a verified bundle to launch', () => {const onLaunch = vi.fn();render(diff --git a/client/src/pages/Game.jsx b/client/src/pages/Game.jsxindex 763b304a24..9630843732 100644--- a/client/src/pages/Game.jsx+++ b/client/src/pages/Game.jsx@@ -48,8 +48,13 @@ export default function Game() {const [apps, setApps] = useState([]);const [sprites, setSprites] = useState([]);const [tracks, setTracks] = useState([]);- const [integrity, setIntegrity] = useState(null);- const [integrityLoading, setIntegrityLoading] = useState(false);+ // Integrity is keyed by the game it describes, never stored bare. `/game/A` →+ // `/game/B` reuses the same route, so the component does NOT remount: unkeyed+ // state would render B's panel with A's verdict — enabling "Start game" for a+ // game with no verified bundle — and an in-flight fetch for A that resolves+ // after B's would overwrite B's result permanently, with nothing to clear it.+ const [integrityFor, setIntegrityFor] = useState(null);+ const [integrityFetching, setIntegrityFetching] = useState(false);const [compileError, setCompileError] = useState('');const [loading, setLoading] = useState(true);const [busy, setBusy] = useState('');@@ -80,18 +85,25 @@ export default function Game() {const refreshIntegrity = useCallback(async () => {if (!id) {- setIntegrity(null);+ setIntegrityFor(null);return;}- setIntegrityLoading(true);- setIntegrity(await getGameIntegrity(id, silent).catch(() => null));- setIntegrityLoading(false);+ setIntegrityFetching(true);+ const data = await getGameIntegrity(id, silent).catch(() => null);+ setIntegrityFor({ gameId: id, data });+ setIntegrityFetching(false);}, [id]);useEffect(() => {refreshIntegrity();}, [refreshIntegrity]);+ // Only a result carrying THIS game's id counts. Anything else — another+ // game's verdict, or nothing fetched yet — reads as "still loading", which+ // keeps every gate closed rather than open on a stale `canLaunch`.+ const integrity = integrityFor?.gameId === id ? integrityFor.data : null;+ const integrityLoading = integrityFetching || integrityFor?.gameId !== id;+const game = useMemo(() => games.find((entry) => entry.id === id) || null, [games, id]);const app = apps.find((entry) => entry.id === game?.appId);const replaceGame = (updated) => setGames((current) =>@@ -131,14 +143,23 @@ export default function Game() {const refreshed = result ? await getGame(game.id, silent).catch(() => null) : null;await refreshIntegrity();setBusy('');- if (!refreshed) {+ if (!result) {setCompileError(message || 'Bundle compilation failed');return;}- replaceGame(refreshed);- toast.success(result.created+ const built = result.created? `Built and verified bundle v${result.version}`- : `Bundle v${result.version} is already verified`);+ : `Bundle v${result.version} is already verified`;+ // The build landed — say so. A failed re-read is a separate, lesser problem+ // (this view is out of date), not evidence the build failed; reporting it as+ // "Bundle compilation failed" would contradict the Verified badge that the+ // independent integrity refresh just set.+ toast.success(built);+ if (!refreshed) {+ setCompileError('The bundle was built, but this page could not reload it. Refresh to see the new version.');+ return;+ }+ replaceGame(refreshed);};const launch = async () => {@@ -302,6 +323,7 @@ export default function Game() {compileError={compileError}onCompile={compile}onLaunch={launch}+ onRetryIntegrity={refreshIntegrity}/></div>)}diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex 66e37cf81b..a6ae8c8d3a 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -1414,20 +1414,34 @@ export function assertSafeFilename(filename, { extensions, subject = 'filename',if (filename.includes('\0')) {throw new ServerError(`Invalid ${subjectText}`, { status: 400, code: 'VALIDATION_ERROR' });}- const isExactTraversal = filename === '.' || filename === '..';- const hasSeparator = filename.includes('/') || filename.includes('\\');- const isPureBasename = basename(filename) === filename;- // Leading dot is fine for normal hidden files, but combined with the no-- // separator rule it's already covered above for `.`/`..`. We keep the- // basename equality check so e.g. `subdir\foo.png` (which has a `\` and- // also has basename `foo.png`) is still rejected by hasSeparator.- const lower = filename.toLowerCase();- const extOk = extensions.some((ext) => lower.endsWith(String(ext).toLowerCase()));- if (!extOk || hasSeparator || isExactTraversal || !isPureBasename) {+ if (!isSafeFilename(filename, extensions)) {throw new ServerError(`Invalid ${subjectText}`, { status: 400, code: 'VALIDATION_ERROR' });}}+/**+ * `assertSafeFilename`'s non-throwing twin: the same rule as a predicate, for+ * callers that must report a bad name as *data* rather than fail the request —+ * e.g. a read-only preflight that names one corrupt record as a blocked row+ * instead of 400-ing the whole sweep. Both share this implementation so the+ * thrown gate and the reported verdict can never disagree.+ *+ * Rejects: empty/non-string, null bytes (they terminate C strings, so some+ * POSIX syscalls treat the prefix as a separate path), `.`/`..`, any path+ * separator, anything that isn't already a pure basename, and any extension+ * outside `extensions`. The basename equality check is kept alongside the+ * separator check so e.g. `subdir\foo.png` is rejected on both counts.+ */+export function isSafeFilename(filename, extensions) {+ if (!filename || typeof filename !== 'string') return false;+ if (filename.includes('\0')) return false;+ if (filename === '.' || filename === '..') return false;+ if (filename.includes('/') || filename.includes('\\')) return false;+ if (basename(filename) !== filename) return false;+ const lower = filename.toLowerCase();+ return extensions.some((ext) => lower.endsWith(String(ext).toLowerCase()));+}+/*** True when `candidatePath` resolves to a location strictly inside `dir`.*diff --git a/server/services/games/compile.test.js b/server/services/games/compile.test.jsindex 16e98b9cc4..d5bc8a1163 100644--- a/server/services/games/compile.test.js+++ b/server/services/games/compile.test.js@@ -70,6 +70,7 @@ vi.mock('../tracks/index.js', () => ({vi.mock('../pipeline/musicLibrary.js', () => ({statMusicTrack: vi.fn(async (filename) => ({ filename, sizeBytes: 100 })),+ isSafeMusicFilename: vi.fn((name) => /\.(?:mp3|wav|m4a|ogg|flac)$/i.test(String(name || ''))),}));import { atomicWrite } from '../../lib/fileUtils.js';diff --git a/server/services/games/integrity.js b/server/services/games/integrity.jsindex 657c5f9e53..5439a028c8 100644--- a/server/services/games/integrity.js+++ b/server/services/games/integrity.js@@ -17,7 +17,7 @@ import {} from '../../lib/fileUtils.js';import { canonicalStringify } from '../../lib/objects.js';import { getAppById } from '../apps.js';-import { statMusicTrack } from '../pipeline/musicLibrary.js';+import { isSafeMusicFilename, statMusicTrack } from '../pipeline/musicLibrary.js';import { getAtlasState } from '../sprites/atlas.js';import {listRuntimeAtlasAssets,@@ -50,7 +50,18 @@ const blocked = (assetType, identity, code, message, shortMessage = message) =>summary: { ...identity, status: 'blocked', message: shortMessage },});-const hashIfPresent = (path) => sha256File(path).catch(() => null);+// A null hash means "no verifiable bytes" — absent, or present but unreadable.+// The verdict is the same either way (it can never match a recorded hash), but+// the CAUSE is not: a permissions/descriptor failure on intact bytes reads to+// the user as corruption and sends them to recompile a perfectly good atlas.+// ENOENT is the expected case and stays quiet; anything else leaves a+// breadcrumb naming the real errno.+const hashIfPresent = (path) => sha256File(path).catch((err) => {+ if (err?.code !== 'ENOENT') {+ console.error(`❌ Unreadable game asset ${path}: ${err?.code || ''} ${err?.message || err}`);+ }+ return null;+});async function resolveRuntimeAtlas(record, current) {const identity = { assetId: record.id, name: record.name, kind: record.kind };@@ -82,7 +93,7 @@ async function resolveRuntimeAtlas(record, current) {'sprite',identity,'SPRITE_ATLAS_INTEGRITY_FAILED',- `The runtime atlas for "${record.name}" is missing or does not match its recorded hash`,+ `The runtime atlas for "${record.name}" is missing, unreadable, or does not match its recorded hash`,'Runtime atlas integrity failed',);}@@ -196,7 +207,12 @@ async function resolveMusic(binding) {}const identity = { assetId: track.id, bindingId: binding.id, name: track.title };- if (!track.audioFilename || !(await statMusicTrack(track.audioFilename))) {+ // `statMusicTrack` THROWS a 400 on an unsupported filename, and `sanitizeTrack`+ // only trims the top-level `audioFilename` — so a legacy or peer-synced track+ // can reach here with one. Screen it first, or one bad track fails the whole+ // read-only preflight instead of naming itself (same reason the sprite path+ // guards on `isValidSpriteId`).+ if (!isSafeMusicFilename(track.audioFilename) || !(await statMusicTrack(track.audioFilename))) {return blocked('music',identity,@@ -315,6 +331,13 @@ export async function getGameIntegrity(id) {getAppById(game.appId),resolveGameAssets(game),]);+ // Inspect the bundle against the ASSET issues only, BEFORE the app blocker is+ // appended: `inspectCurrentBundle` reads a non-empty issue list as evidence+ // the bound assets drifted, so a missing managed app would otherwise report a+ // byte-perfect bundle as `stale` — "Bound assets changed after this bundle was+ // built" — which is a false statement about the assets, and pairs an amber+ // "Needs rebuild" badge with a disabled Rebuild button.+ const bundle = await inspectCurrentBundle(game, resolved);if (!app) {resolved.issues.push(issue('app',@@ -324,7 +347,6 @@ export async function getGameIntegrity(id) {'The bound managed app no longer exists',));}- const bundle = await inspectCurrentBundle(game, resolved);const readyToCompile = resolved.issues.length === 0 && Boolean(app);return {schemaVersion: BUNDLE_SCHEMA_VERSION,diff --git a/server/services/games/integrity.test.js b/server/services/games/integrity.test.jsindex 37d50a389a..ed6d35089d 100644--- a/server/services/games/integrity.test.js+++ b/server/services/games/integrity.test.js@@ -6,6 +6,15 @@ const state = vi.hoisted(() => ({atlases: {},assets: {},manifest: null,+ // On-disk bytes, keyed by the suffix `sha256File` is asked for. Tests mutate+ // this to simulate a file whose bytes changed under a recorded hash, or that+ // vanished (`null`) — without it the mock always echoes the hash the fixture+ // pointer declares, so the mismatch comparison can never be false and a+ // regression that inverted it would ship green.+ hashes: {},+ // Distinct from `hashes[path] === null` (missing): an unreadable file, which+ // must produce the same verdict but a different diagnosis.+ unreadable: new Set(),}));vi.mock('./records.js', () => ({@@ -50,19 +59,27 @@ vi.mock('../tracks/index.js', () => ({vi.mock('../pipeline/musicLibrary.js', () => ({statMusicTrack: vi.fn(async () => ({ sizeBytes: 128 })),+ isSafeMusicFilename: vi.fn((name) => /\.(?:mp3|wav|m4a|ogg|flac)$/i.test(String(name || ''))),}));vi.mock('../../lib/fileUtils.js', () => ({PATHS: { music: '/tmp/music' },readJSONFile: vi.fn(async () => state.manifest),- sha256Text: vi.fn((value) => `text-sha:${String(value).length}`),+ // Content-exact, not length-based — a canonical-stringify change that happened+ // to preserve length must still register as a changed input.+ sha256Text: vi.fn((value) => `text-sha:${String(value)}`),+ // Mirrors the real `sha256File`: REJECTS on a file it can't read (the caller+ // owns the catch), so a test can drive the missing/unreadable branches.sha256File: vi.fn(async (path) => {- if (path.includes('/games/')) return 'bundle-sha';- if (path.endsWith('native.png')) return 'native-atlas-sha';- if (path.endsWith('native.json')) return 'native-manifest-sha';- if (path.endsWith('props.png')) return 'props-sha';- if (path.endsWith('.ogg')) return 'music-sha';- return null;+ const key = Object.keys(state.hashes).find((suffix) => path.endsWith(suffix));+ if (state.unreadable.has(key)) {+ throw Object.assign(new Error(`EACCES: permission denied, open '${path}'`), { code: 'EACCES' });+ }+ const hash = key ? state.hashes[key] : null;+ if (hash === null || hash === undefined) {+ throw Object.assign(new Error(`ENOENT: no such file, open '${path}'`), { code: 'ENOENT' });+ }+ return hash;}),}));@@ -102,6 +119,15 @@ describe('Game bundle integrity', () => {state.assets = {props: [{ path: 'atlas/props.png', size: 512 }],};+ // Every file present and matching what its pointer records.+ state.hashes = {+ 'native.png': 'native-atlas-sha',+ 'native.json': 'native-manifest-sha',+ 'props.png': 'props-sha',+ 'example-theme.ogg': 'music-sha',+ 'game-assets-v3.json': 'bundle-sha',+ };+ state.unreadable = new Set();state.manifest = null;});@@ -167,4 +193,157 @@ describe('Game bundle integrity', () => {verifiedFiles: 4,});});++ // A "verified" bundle is only worth the hash comparisons behind it. These+ // drive the branches that decide missing / unreadable / changed bytes — the+ // detection the whole feature exists for.+ describe('hash verification', () => {+ const buildableGame = () => {+ state.game.spriteBindings = [{ spriteId: 'native' }];+ state.game.musicBindings = [];+ };++ it('blocks a sprite whose atlas bytes changed under its recorded hash', async () => {+ buildableGame();+ state.hashes['native.png'] = 'someone-recompressed-the-png';+ const resolved = await resolveGameAssets(state.game);+ expect(resolved.sprites).toEqual([]);+ expect(resolved.issues).toEqual([+ expect.objectContaining({+ assetId: 'native',+ code: 'SPRITE_ATLAS_INTEGRITY_FAILED',+ }),+ ]);+ });++ it('blocks a sprite whose atlas file is gone', async () => {+ buildableGame();+ state.hashes['native.png'] = null;+ const resolved = await resolveGameAssets(state.game);+ expect(resolved.issues[0]).toMatchObject({ code: 'SPRITE_ATLAS_INTEGRITY_FAILED' });+ });++ it('blocks a sprite whose atlas file is present but unreadable', async () => {+ // Same verdict as missing (no verifiable bytes), but the cause is a+ // permissions failure on intact bytes — `hashIfPresent` must not let the+ // EACCES escape and fail the whole read-only sweep.+ buildableGame();+ state.unreadable.add('native.png');+ const resolved = await resolveGameAssets(state.game);+ expect(resolved.issues[0]).toMatchObject({ code: 'SPRITE_ATLAS_INTEGRITY_FAILED' });+ });++ it('blocks an imported runtime asset that is unreadable', async () => {+ state.game.spriteBindings = [{ spriteId: 'props' }];+ state.game.musicBindings = [];+ state.unreadable.add('props.png');+ const resolved = await resolveGameAssets(state.game);+ expect(resolved.sprites).toEqual([]);+ expect(resolved.issues[0]).toMatchObject({+ assetId: 'props',+ code: 'SPRITE_ATLAS_INTEGRITY_FAILED',+ });+ });++ it('blocks a track whose stored filename is not a supported music name', async () => {+ // `sanitizeTrack` only trims the top-level audioFilename, so a legacy or+ // peer-synced track can carry one `statMusicTrack` would THROW a 400 on.+ // It has to become one blocked row, not a failed preflight.+ state.game.spriteBindings = [];+ const { getTrack } = await import('../tracks/index.js');+ getTrack.mockResolvedValueOnce({ id: 'theme', title: 'Legacy Theme', audioFilename: 'theme.opus' });+ const resolved = await resolveGameAssets(state.game);+ expect(resolved.music).toEqual([]);+ expect(resolved.issues).toEqual([+ expect.objectContaining({ assetId: 'theme', code: 'TRACK_AUDIO_REQUIRED' }),+ ]);+ });+ });++ describe('bundle status', () => {+ const withBuiltBundle = async (overrides = {}) => {+ state.game.spriteBindings = [{ spriteId: 'native' }];+ state.game.musicBindings = [];+ const resolved = await resolveGameAssets(state.game);+ state.game.compiledManifest = {+ version: 3,+ manifestPath: 'manifests/game-assets-v3.json',+ manifestSha256: 'bundle-sha',+ inputSha256: resolved.inputSha256,+ ...overrides,+ };+ state.manifest = { kind: 'portos-game-assets', game: { id: 'game-1' }, version: 3 };+ return resolved;+ };++ it('goes stale when a bound asset changes after the build', async () => {+ await withBuiltBundle();+ // Re-point the sprite at a new atlas version: same files, different+ // recorded hashes, so the resolved input no longer matches the pointer.+ state.atlases.native = { ...state.atlases.native, version: 5 };+ state.hashes['native.png'] = 'v5-atlas-sha';+ state.atlases.native.atlasSha256 = 'v5-atlas-sha';++ const integrity = await getGameIntegrity('game-1');+ expect(integrity.bundle.status).toBe('stale');+ expect(integrity.canLaunch).toBe(false);+ });++ it('goes stale when a bound asset is blocked, without launching', async () => {+ await withBuiltBundle();+ state.hashes['native.png'] = null;+ const integrity = await getGameIntegrity('game-1');+ expect(integrity.bundle.status).toBe('stale');+ expect(integrity.canLaunch).toBe(false);+ });++ it('is corrupt when the manifest file no longer matches its recorded hash', async () => {+ await withBuiltBundle();+ state.hashes['game-assets-v3.json'] = 'edited-by-hand';+ const integrity = await getGameIntegrity('game-1');+ expect(integrity.bundle.status).toBe('corrupt');+ expect(integrity.canLaunch).toBe(false);+ });++ it('is corrupt when the manifest file is gone', async () => {+ await withBuiltBundle();+ state.hashes['game-assets-v3.json'] = null;+ const integrity = await getGameIntegrity('game-1');+ expect(integrity.bundle.status).toBe('corrupt');+ });++ it('is corrupt when the manifest describes a different game or version', async () => {+ await withBuiltBundle();+ state.manifest = { kind: 'portos-game-assets', game: { id: 'other-game' }, version: 3 };+ expect((await getGameIntegrity('game-1')).bundle.status).toBe('corrupt');++ state.manifest = { kind: 'portos-game-assets', game: { id: 'game-1' }, version: 9 };+ expect((await getGameIntegrity('game-1')).bundle.status).toBe('corrupt');++ state.manifest = { kind: 'something-else', game: { id: 'game-1' }, version: 3 };+ expect((await getGameIntegrity('game-1')).bundle.status).toBe('corrupt');+ });++ it('is corrupt when the pointer records no manifest path at all', async () => {+ await withBuiltBundle({ manifestPath: '' });+ expect((await getGameIntegrity('game-1')).bundle.status).toBe('corrupt');+ });++ it('keeps a byte-perfect bundle current when only the managed app is missing', async () => {+ // The app blocker is not asset drift. Reporting `stale` here would tell+ // the user "Bound assets changed after this bundle was built" — false —+ // and pair a "Needs rebuild" badge with a disabled Rebuild button.+ await withBuiltBundle();+ const { getAppById } = await import('../apps.js');+ getAppById.mockResolvedValueOnce(null);++ const integrity = await getGameIntegrity('game-1');+ expect(integrity.bundle.status).toBe('current');+ expect(integrity.issues).toEqual([+ expect.objectContaining({ code: 'APP_MISSING', assetType: 'app' }),+ ]);+ expect(integrity.readyToCompile).toBe(false);+ expect(integrity.canLaunch).toBe(false);+ });+ });});diff --git a/server/services/pipeline/musicLibrary.js b/server/services/pipeline/musicLibrary.jsindex 146e32b2e8..787f3f3dc6 100644--- a/server/services/pipeline/musicLibrary.js+++ b/server/services/pipeline/musicLibrary.js@@ -18,7 +18,13 @@ import { stat, copyFile, unlink } from 'fs/promises';import { existsSync } from 'fs';import { join, extname, basename } from 'path';import { randomUUID } from 'crypto';-import { PATHS, ensureDir, assertSafeFilename, listDirectoryByExtension } from '../../lib/fileUtils.js';+import {+ PATHS,+ ensureDir,+ assertSafeFilename,+ isSafeFilename,+ listDirectoryByExtension,+} from '../../lib/fileUtils.js';// Mirror of the sanitizer's MUSIC_SOURCES set in `services/pipeline/issues.js`.// Exported so routes don't sprinkle bare strings; `'gen'` is reserved for the@@ -67,6 +73,17 @@ export function assertSafeMusicFilename(filename) {});}+/**+ * The same rule as a predicate, for read-only callers that must treat a bad+ * stored filename as data. `sanitizeTrack` only `trimTo`s the top-level+ * `audioFilename` (unlike `renders[]`, which goes through+ * `trackAudioFilename`), so a legacy or peer-synced track can carry an+ * unsupported name — a preflight has to report that as one blocked asset, not+ * 400 the whole sweep via `assertSafeMusicFilename`.+ */+export const isSafeMusicFilename = (filename) =>+ isSafeFilename(filename, SUPPORTED_AUDIO_EXTENSIONS);+/*** Generate a fresh deterministic basename for a newly-uploaded track. Keeps* the original extension so the static handler picks the right Content-Type.diff --git a/server/services/sprites/paths.js b/server/services/sprites/paths.jsindex 570cdb3b22..d2e2ba63d6 100644--- a/server/services/sprites/paths.js+++ b/server/services/sprites/paths.js@@ -284,7 +284,10 @@ export function __resetSpriteMetadataCache() {* should not pay a probe per image on every call.*/export async function listSpriteAssets(recordId, { subdir = '', metadata = true } = {}) {- const dir = subdir ? join(spriteDir(recordId), subdir) : spriteDir(recordId);+ // `subdir` goes through the confinement gate rather than a bare join — every+ // other path this module hands out is confined, and a future caller passing a+ // request-influenced value shouldn't be the thing that discovers otherwise.+ const dir = subdir ? resolveSpriteAssetPath(recordId, subdir) : spriteDir(recordId);const out = [];async function walk(current, relPrefix) {let entries;