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

anchor user-entered backup excludes so a bare `cache/` can't match at every depth

[._.]/ Adam Eivybf661d9b8e57
diff --git a/client/src/components/settings/BackupTab.jsx b/client/src/components/settings/BackupTab.jsx
index 072c4a1c79..114dc7d2be 100644
--- a/client/src/components/settings/BackupTab.jsx
+++ b/client/src/components/settings/BackupTab.jsx
@@ -9,6 +9,7 @@ import Modal from '../ui/Modal';
import { getSettings, updateSettings, getBackupStatus, getBackupSnapshots, restoreDatabase } from '../../services/api';
import { formatBytes } from '../../utils/formatters';
import CronSchedulePicker from '../CronSchedulePicker';
+import { anchorUserExclude, anchorUserExcludes, isSafeExcludePattern } from '../../lib/backupExcludes';
// Set equality — rsync --exclude flags are order-independent, so reordering
// is NOT a dirty state; only membership changes (added/removed entries) are.
@@ -19,6 +20,12 @@ const sameSet = (a, b) => a.length === b.length && a.every(x => b.includes(x));
// null, or any other shape. Normalize before it reaches React state — otherwise
// downstream `.some` / `.includes` / `.filter` calls crash the Backup tab.
const asArray = (v) => Array.isArray(v) ? v : [];
+// Stored exclude patterns are now bounded at the settings boundary (`..`/NUL and
+// blanks rejected). A settings.json written before that — or hand-edited since —
+// can still hold an entry the PATCH would now 400 on, which would wedge the whole
+// Backup form. Drop those on load instead: the spelling of the survivors is left
+// untouched (anchoring is a read-time concern), so the form is not dirty.
+const asExcludeArray = (v) => asArray(v).filter(isSafeExcludePattern);
const snapshotIdentity = (snapshot) =>
snapshot.selectionKey || `${snapshot.source || 'current'}/${snapshot.id}`;
const snapshotSourceLabel = (snapshot) =>
@@ -28,6 +35,7 @@ export function BackupTab() {
const destPathId = useId();
const additionalExcludeId = useId();
const defaultExcludesPanelId = useId();
+ const effectiveExcludesPanelId = useId();
const [loading, setLoading] = useState(true);
// A settings response that never resolved is NOT 'the defaults' — the schedule
// fields stay null and the form is replaced by an error panel, so an unreachable
@@ -61,6 +69,9 @@ export function BackupTab() {
// edits — collapsed by default so the fields they came to change (destination,
// enabled, schedule) and the action bar are what the tab actually shows.
const [showDefaultExcludes, setShowDefaultExcludes] = useState(false);
+ // Same reasoning as the catalog above: the effective list is defaults + user
+ // entries, so it is longer still. Collapsed by default, one click from visible.
+ const [showEffectiveExcludes, setShowEffectiveExcludes] = useState(false);
useEffect(() => {
Promise.all([
@@ -71,7 +82,7 @@ export function BackupTab() {
.then(([settings, status, snaps]) => {
const backup = settings?.backup || {};
const saved = backup.destPath || '';
- const savedExcludes = asArray(backup.excludePaths);
+ const savedExcludes = asExcludeArray(backup.excludePaths);
const savedDisabled = asArray(backup.disabledDefaultExcludes);
setDestPath(saved);
setSavedDestPath(saved);
@@ -132,10 +143,13 @@ export function BackupTab() {
getBackupSnapshots({ silent: true }).then(s => setSnapshots(Array.isArray(s) ? s : [])).catch((err) => { console.warn(`⚠️ Failed to refresh snapshots: ${err?.message || err}`); });
});
+ // Anchor exactly as the server does on read, so the chip the user sees IS the
+ // rsync filter that will run. A bare `repos/` would otherwise match every
+ // `repos/` at any depth under data/ and silently drop unrelated records (#7241).
const addExclude = () => {
- const trimmed = newExclude.trim();
- if (!trimmed || excludePaths.includes(trimmed)) return;
- setExcludePaths([...excludePaths, trimmed]);
+ const anchored = anchorUserExclude(newExclude);
+ if (!anchored) return;
+ if (!excludePaths.includes(anchored)) setExcludePaths([...excludePaths, anchored]);
setNewExclude('');
};
@@ -183,6 +197,15 @@ export function BackupTab() {
const enabledDefaultCount = defaultExcludeRows.filter(d => d.defaultActive).length;
const disabledDefaultCount = defaultExcludeRows.length - enabledDefaultCount;
+ // The rsync filter list this configuration actually produces — the client half
+ // of `computeEffectiveExcludes`, built from the same anchoring helper so the
+ // preview cannot drift from the run. Rendering it is the point: without it the
+ // user never sees how a pattern was interpreted until a restore comes up short.
+ const effectiveExcludes = [...new Set([
+ ...defaultExcludeRows.filter(d => d.defaultActive).map(d => d.path),
+ ...anchorUserExcludes(excludePaths),
+ ])];
+
const renderPgStatus = () => {
if (!pgBackup) return <span className="text-gray-500">No backup run yet</span>;
if (pgBackup.status === 'ok') {
@@ -344,7 +367,7 @@ export function BackupTab() {
<div className="space-y-2">
<label htmlFor={additionalExcludeId} className="block text-sm text-gray-400">Additional Exclude Paths</label>
- <p className="text-xs text-gray-500">Custom directories/patterns to skip during backup (relative to data/). Additional rules still apply when a default exclusion is disabled. Disabling a default does not guarantee matching files will be backed up.</p>
+ <p className="text-xs text-gray-500">Custom directories/patterns to skip during backup (relative to data/). Patterns are anchored to the data root, so <code>repos/</code> is stored as <code>/repos/</code> and skips only <code>data/repos/</code>. Start a pattern with <code>**/</code> to match at any depth instead. Additional rules still apply when a default exclusion is disabled. Disabling a default does not guarantee matching files will be backed up.</p>
<div className="flex gap-2">
<input
id={additionalExcludeId}
@@ -353,11 +376,11 @@ export function BackupTab() {
onChange={e => setNewExclude(e.target.value)}
onKeyDown={e => e.key === 'Enter' && addExclude()}
className="flex-1 bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"
- placeholder="repos/"
+ placeholder="/repos/"
/>
<button
onClick={addExclude}
- disabled={!newExclude.trim()}
+ disabled={!anchorUserExclude(newExclude)}
aria-label="Add exclude path"
className="inline-flex items-center justify-center min-w-[40px] min-h-[40px] px-3 py-2 bg-port-border hover:bg-port-border/70 text-white rounded-lg transition-colors disabled:opacity-50 shrink-0"
>
@@ -376,6 +399,33 @@ export function BackupTab() {
))}
</div>
)}
+
+ {effectiveExcludes.length > 0 && (
+ <div className="space-y-2 pt-1">
+ <button
+ type="button"
+ onClick={() => setShowEffectiveExcludes(v => !v)}
+ aria-expanded={showEffectiveExcludes}
+ aria-controls={effectiveExcludesPanelId}
+ className="flex items-center gap-2 w-full text-left text-sm text-gray-400 hover:text-white transition-colors"
+ >
+ {showEffectiveExcludes ? <ChevronDown size={14} className="shrink-0" /> : <ChevronRight size={14} className="shrink-0" />}
+ <span>Effective exclude list — {effectiveExcludes.length} rsync {effectiveExcludes.length === 1 ? 'pattern' : 'patterns'}</span>
+ </button>
+ {showEffectiveExcludes && (
+ <div id={effectiveExcludesPanelId} className="space-y-2">
+ <p className="text-xs text-gray-500">The exact <code>--exclude</code> filters the next snapshot will use: enabled default rules plus your anchored patterns. Saved changes above are reflected here.</p>
+ <ul className="flex flex-wrap gap-1.5">
+ {effectiveExcludes.map((pattern) => (
+ <li key={pattern}>
+ <code className="inline-block px-1.5 py-0.5 bg-port-bg border border-port-border rounded text-xs text-gray-300 break-all">{pattern}</code>
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ </div>
+ )}
</div>
{snapshots.length > 0 && (
diff --git a/client/src/components/settings/BackupTab.test.jsx b/client/src/components/settings/BackupTab.test.jsx
index 51ddb0fc70..a3a7edf8bb 100644
--- a/client/src/components/settings/BackupTab.test.jsx
+++ b/client/src/components/settings/BackupTab.test.jsx
@@ -466,6 +466,47 @@ describe('BackupTab', () => {
expect(screen.getByRole('switch', { name: /Disable default exclusion \/models/i })).toBeTruthy();
});
+ // #7241: a bare directory name is an rsync any-depth filter, so the chip has
+ // to show the anchored form the server will actually run — otherwise the user
+ // discovers what `cache/` really matched at restore time.
+ it('anchors a newly added exclude and shows the effective rsync filter list', async () => {
+ getBackupStatus.mockResolvedValue({ status: 'never', defaultExcludes: EXCLUDES, pgBackup: null });
+ await renderTab();
+
+ fireEvent.change(screen.getByLabelText('Additional Exclude Paths'), { target: { value: 'cache/' } });
+ fireEvent.click(screen.getByLabelText('Add exclude path'));
+ expect(screen.getByText('/cache/')).toBeTruthy();
+ expect(screen.queryByText('cache/')).toBeNull();
+
+ // A wildcard-led pattern is the deliberate any-depth escape hatch and is
+ // left exactly as typed.
+ fireEvent.change(screen.getByLabelText('Additional Exclude Paths'), { target: { value: '**/raw/' } });
+ fireEvent.click(screen.getByLabelText('Add exclude path'));
+ expect(screen.getByText('**/raw/')).toBeTruthy();
+
+ // The effective list is the defaults plus those two, collapsed until asked
+ // for so it can't push the action bar below the fold.
+ const disclosure = screen.getByRole('button', { name: /Effective exclude list/i });
+ expect(disclosure.getAttribute('aria-expanded')).toBe('false');
+ expect(disclosure.textContent).toMatch(/4 rsync patterns/);
+ fireEvent.click(disclosure);
+ for (const pattern of ['/cache', '/models', '/cache/', '**/raw/']) {
+ expect(screen.getAllByText(pattern).length).toBeGreaterThan(0);
+ }
+ });
+
+ it('refuses an exclude pattern that would escape the data root', async () => {
+ getBackupStatus.mockResolvedValue({ status: 'never', defaultExcludes: [], pgBackup: null });
+ await renderTab();
+
+ fireEvent.change(screen.getByLabelText('Additional Exclude Paths'), { target: { value: '../../etc' } });
+ // The server rejects this at the settings boundary; the button stays
+ // disabled so the user never gets a chip that cannot be saved.
+ expect(screen.getByLabelText('Add exclude path').disabled).toBe(true);
+ fireEvent.click(screen.getByLabelText('Add exclude path'));
+ expect(screen.queryByText('../../etc')).toBeNull();
+ });
+
// Regression: wildcard rules must survive edits and reload without the UI
// promising that disabling a default includes the matching files.
it('preserves independent custom rules through default toggles, save, and reload', async () => {
@@ -497,12 +538,14 @@ describe('BackupTab', () => {
fireEvent.change(screen.getByLabelText('Additional Exclude Paths'), { target: { value: 'loras/**' } });
fireEvent.click(screen.getByLabelText('Add exclude path'));
await act(async () => { fireEvent.click(screen.getByRole('button', { name: /^Save$/ })); });
- expect(updateSettings).toHaveBeenLastCalledWith({ backup: { ...backup, disabledDefaultExcludes: ['/cache', loraPath], excludePaths: [...custom, 'loras/**'] } }, { silent: true });
+ // Anchored on the way in (#7241): `loras/**` is a path, not a wildcard-led
+ // any-depth pattern, so it becomes `/loras/**`.
+ expect(updateSettings).toHaveBeenLastCalledWith({ backup: { ...backup, disabledDefaultExcludes: ['/cache', loraPath], excludePaths: [...custom, '/loras/**'] } }, { silent: true });
expect(toast.error).not.toHaveBeenCalled();
cleanup();
await renderTab();
- for (const pattern of [...custom, 'loras/**']) expect(screen.getByText(pattern)).toBeTruthy();
+ for (const pattern of [...custom, '/loras/**']) expect(screen.getByText(pattern)).toBeTruthy();
fireEvent.click(screen.getByRole('button', { name: /Default exclusions/ }));
expect(screen.getByRole('switch', { name: `Disable default exclusion ${loraPath}` }).getAttribute('aria-checked')).toBe('true');
expect(screen.getByText('(Default exclusion disabled)')).toBeTruthy();
@@ -677,12 +720,14 @@ describe('BackupTab', () => {
updateSettings.mockResolvedValue({});
await renderTab();
- fireEvent.change(screen.getByPlaceholderText('repos/'), { target: { value: 'scratch/' } });
+ fireEvent.change(screen.getByPlaceholderText('/repos/'), { target: { value: 'scratch/' } });
fireEvent.click(screen.getByLabelText('Add exclude path'));
await act(async () => { fireEvent.click(screen.getByRole('button', { name: /^Save$/i })); });
+ // Anchored on the way in (#7241): an unanchored `scratch/` would match every
+ // scratch/ at any depth under data/, not the one the user meant.
expect(updateSettings).toHaveBeenCalledWith(
- { backup: expect.objectContaining({ enabled: true, cronExpression: '0 0 * * *', excludePaths: ['scratch/'] }) },
+ { backup: expect.objectContaining({ enabled: true, cronExpression: '0 0 * * *', excludePaths: ['/scratch/'] }) },
{ silent: true }
);
});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 4a38432794..d61a0bfa8b 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -51,6 +51,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `universeRunTag.js` | `buildUniverseSectionRenderTag(universe, kindKey, entry)` — the durable `universeRun` job tag the canon-render call sites (UniverseCanonSection, NounsStage, Story Builder characters step) pass to `generateImage` so the server auto-files the render into the universe collection AND appends it to the entry's `imageRefs[]` (no client follow-up PATCH). |
| `autopilotMilestones.js` | Series-Autopilot milestone map. `buildAutopilotMilestones(plan, progress, {terminal})` folds the run's projected plan (the `start` frame) and its live progress snapshot (`progress` frames / the status route) into ordered rows with a `MILESTONE_STATUS` each — a furthest-index cursor, so a gate the run revisits can't un-finish the milestones after it; `summarizeAutopilotMilestones(rows)` rolls them into the header meter (a settled-but-unstepped milestone counts as complete); `describeAutopilotVerification(kind, verification)` renders what a gate actually validated — shared with the panel's `frameLabel`, since the milestone row and the activity log render the same telemetry; `isStoppedTerminal(terminal)` is the one definition of "the run stopped mid-plan"; `autopilotMarkerTerminal(status)` translates a persisted `autopilot.status` into the terminal frame type the fold reads, so a map rebuilt from the marker after a reload (#4140) flags the step a paused run stopped on. Also owns `AUTOPILOT_STEP_LABELS` / `autopilotStepLabel(kind)`, the one set of human labels for conductor step kinds (shared by the map and the panel's live status line). Used by `components/pipeline/AutopilotMilestones.jsx` + `AutopilotPanel.jsx`. |
| `beeperMessageBody.js` | Beeper message bodies: `decodeHtmlEntities` (the five predefined entities plus `&nbsp;`, mirroring `server/lib/xmlEntities.js`), `looksLikeHtmlBody`, `parseMessageBody(body)` → blocks of marked spans (`p`/`div`/`br`/`blockquote`/`strong`/`b`/`em`/`i`/`a[href]`, `null` when the body carries none of them) and `messagePreviewText(body)` for the one-line rail row. Some networks deliver HTML (Discord, Matrix) and the mirror stores it verbatim, so the thread and the preview parse it into a data model and render React elements — never `dangerouslySetInnerHTML`; a non-http(s) `href` degrades to plain text. |
+| `backupExcludes.js` | CLIENT MIRROR of the backup-exclude block in `server/lib/sharedSchemas.js` (#7241) — `anchorUserExclude` / `anchorUserExcludes` / `isSafeExcludePattern` / `EXCLUDE_PATTERN_MAX_LENGTH`. The Backup settings tab anchors a newly added exclude and renders the effective list with these, so the chip the user sees is the rsync filter the server will actually run instead of an unanchored pattern that matches at any depth. |
| `beatColors.js` | `BEAT_KIND_COLORS` + `getBeatKindColor(kind)` — per-kind display colors for reader-map emotional beats (kinds defined server-side in `storyArc.js`). Keeps every beat visualization consistent. |
| `beatGrid.js` | Music-video beat-quantized timeline arranger (#1854). `buildBeatGridPoints(audioAnalysis)` merges beats/downbeats/section edges into one ranked snap-point list; `snapTimeToGrid(timeSec, gridPoints, toleranceSec)` finds the nearest point within tolerance; `computeSceneSpans(scenes, durationSec)` lays out scenes without a persisted `startSec`/`endSec` contiguously as a display-only fallback; `computeDragSpan({kind, startSpan, deltaSec, gridPoints, ...})` resolves a timeline drag gesture (`'move'` or `'right'` — no `'left'`, since the render can only trim from a clip's own frame 0) into a new span; `shouldMarkBeatAligned({kind, snapped, wasPersisted})` gates the `beatAligned` flag so a reposition-only drag can't silently promote an unpersisted scene's placeholder fallback duration into a "saved exactly" render duration; `autoArrangeScenes(scenes, audioAnalysis)` proposes a full `{ sceneId, startSec, endSec, beatAligned }[]` arrangement by distributing scenes across song sections weighted by each section's `energy` (#1915). Used by `components/musicVideo/BeatTimeline.jsx` and `pages/MusicVideo.jsx`. |
| `bibleLimits.js` | `BIBLE_LIMITS` re-exported from the pure leaf `server/lib/bibleLimits.js`, plus the client-only `capImageRefs` / `appendImageRefById` for the optimistic imageRefs-append paths. |
diff --git a/client/src/lib/backupExcludes.js b/client/src/lib/backupExcludes.js
new file mode 100644
index 0000000000..1d45b0a094
--- /dev/null
+++ b/client/src/lib/backupExcludes.js
@@ -0,0 +1,84 @@
+/**
+ * Anchoring rules for USER-entered backup exclude patterns.
+ *
+ * The backup exclude list is rsync FILTER syntax, not a glob list. rsync anchors
+ * a pattern to the transfer root only when it starts with `/`; anything else
+ * matches at EVERY level of the tree. So a user who types `cache/` to skip
+ * `data/cache/` also drops the per-run caches nested under training runs, and
+ * `raw/` reaches into sprite runs and universes. The snapshot still reports
+ * success — the omission surfaces only at restore, which is exactly when it
+ * cannot be fixed.
+ *
+ * `DEFAULT_EXCLUDES` has always been anchored by hand (and a test in
+ * `backup.test.js` fails if one entry is not). This module applies the same rule
+ * to the one list a user actually edits.
+ *
+ * Anchoring happens at READ time (`computeEffectiveExcludes`), never by
+ * rewriting stored settings: the stored value stays exactly what the user typed,
+ * so there is nothing to migrate and nothing is silently rewritten under them.
+ *
+ * CLIENT MIRROR of the backup-exclude block at the bottom of
+ * `server/lib/sharedSchemas.js` — keep the logic byte-for-byte in sync. It lives
+ * beside the Zod fragments there so `backupConfigSchema` and
+ * `services/backup.js` share one rule without adding a module to the import
+ * closure of `validation.js`, which the whole server suite reaches.
+ *
+ * The Backup settings tab anchors a newly added pattern and renders the
+ * effective list with these, so the chip the user sees is the pattern the
+ * server will hand rsync.
+ */
+
+/**
+ * Longest exclude pattern accepted, measured on the ANCHORED form — the string
+ * actually handed to rsync. Bounding the raw input instead would let a
+ * 256-character relative pattern pass validation and then anchor to 257, so the
+ * settings boundary would reject the very chip the UI had just shown as valid.
+ */
+export const EXCLUDE_PATTERN_MAX_LENGTH = 256;
+
+/**
+ * A pattern is left alone when it is already anchored (`/…`) or deliberately
+ * any-depth (`*…`, which covers rsync's `**` spelling). Everything else gets a
+ * leading `/`.
+ */
+const isAnchoredOrWildcardLed = (pattern) => pattern.startsWith('/') || pattern.startsWith('*');
+
+/**
+ * Normalize ONE user-entered pattern to the form rsync will be handed. This is
+ * the single declaration of what a legal pattern is — `isSafeExcludePattern`
+ * below is defined in terms of it, so the settings boundary can never accept
+ * something the read-time normalizer would then drop, or vice versa.
+ * @param {unknown} pattern
+ * @returns {string|null} the anchored pattern, or null when it is blank,
+ * non-string, or unsafe (caller drops it).
+ */
+export function anchorUserExclude(pattern) {
+ if (typeof pattern !== 'string') return null;
+ const trimmed = pattern.trim();
+ // A NUL would truncate the rsync argument; `..` in any segment (`../x`,
+ // `a/../../x`, the bare `..`) walks out of the data root.
+ if (!trimmed || trimmed.includes('\0')) return null;
+ if (trimmed.split('/').includes('..')) return null;
+ const anchored = isAnchoredOrWildcardLed(trimmed) ? trimmed : `/${trimmed}`;
+ return anchored.length <= EXCLUDE_PATTERN_MAX_LENGTH ? anchored : null;
+}
+
+/**
+ * Whether a stored/submitted pattern survives normalization. Shared with
+ * `lib/validation.js` so the settings boundary rejects exactly what
+ * `computeEffectiveExcludes` would have dropped.
+ * @param {unknown} pattern
+ * @returns {boolean}
+ */
+export const isSafeExcludePattern = (pattern) => anchorUserExclude(pattern) !== null;
+
+/**
+ * Normalize a whole user list, dropping blank/unsafe entries and duplicates
+ * that only differed by anchoring or whitespace.
+ * @param {unknown} patterns
+ * @returns {string[]}
+ */
+export function anchorUserExcludes(patterns) {
+ const list = Array.isArray(patterns) ? patterns : [];
+ return [...new Set(list.map(anchorUserExclude).filter(Boolean))];
+}
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 3465a79ecd..e6fa4248fb 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -25,6 +25,7 @@ export * from './universeStylePreset.js';
// === Pipeline / image-gen defaults ===
export * from './autopilotMilestones.js';
+export * from './backupExcludes.js';
export * from './beatColors.js';
export * from './beeperMessageBody.js';
export * from './beatGrid.js';
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 62f8afa0fa..e3a617c66b 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -34,10 +34,16 @@ A backup run (`runBackup` in `server/services/backup.js`) writes to:
The effective exclude list is computed by the pure `computeEffectiveExcludes()` helper (unit-tested in `backup.test.js`). The scheduled cron handler in `backupScheduler.js` re-reads settings on every run, so `destPath`, `excludePaths`, `disabledDefaultExcludes`, and `enabled` all take effect on the next run without a restart. See [Scheduling & status](#scheduling--status) for how the cron registration itself tracks settings.
-#### Why every default exclude must be anchored with a leading `/`
+#### Why every exclude must be anchored with a leading `/`
`DEFAULT_EXCLUDES` is **rsync filter syntax** — the leading `/` means "relative to the transfer root". Without the anchor, `loras/*.safetensors` also matches any `loras/` directory nested anywhere under `data/`, silently dropping unrelated user data (e.g. `brain/.../loras/`). An unanchored pattern is a data-loss bug, not a style nit.
+The same rule applies to **user-entered** Additional Exclude Paths, which is the list that is easy to get wrong: rsync matches a pattern with no leading `/` at *every* level of the tree, so typing `cache/` to skip `data/cache/` also drops `training-runs/*/cache/`, and `raw/` reaches into sprite runs. The failure is silent — the snapshot reports success, it is simply smaller, and the omission surfaces only at restore. So `computeEffectiveExcludes()` **anchors each user pattern on read** (`server/lib/backupExcludes.js`), prepending `/` to anything that is not already anchored and is not deliberately wildcard-led.
+
+- Anchoring happens at read time, never in storage: `settings.json` keeps exactly what you typed, so there is nothing to migrate and nothing is rewritten under you. The Backup tab anchors a pattern as you add it and renders the computed effective list, so the chip you see is the filter that will run.
+- **`**/name/` is the explicit way to ask for any-depth matching.** A pattern starting with `*` or `**` is passed through unchanged — that is how you deliberately say "every `cache/` anywhere", rather than getting it by accident.
+- Patterns are bounded at the settings boundary (`backupConfigSchema` in `server/lib/validation.js`), and a `..` segment or a NUL byte is rejected rather than sanitized. The 256-character cap is measured on the **anchored** form — the string rsync is handed — so the boundary accepts exactly what `computeEffectiveExcludes()` keeps, and a pattern can never be saved as valid and then silently dropped at run time.
+
The two `overridable` tiers are enforced, not advisory. A hand-edited `settings.json` that lists a non-overridable path in `disabledDefaultExcludes` is silently dropped server-side; `computeEffectiveExcludes()` enforces both the overridable allow-list and `Array.isArray` guards for hand-edited settings. The Backup tab switches describe default rule state: switching on disables that default exclusion, and switching off re-enables it. The summary counts enabled and disabled default rules, not included files.
Additional Exclude Paths is independent: toggling a default never removes custom patterns, and custom rsync patterns remain accepted even when they overlap defaults. Additional rules still apply when a default is disabled, so disabling `/loras/*.safetensors` does not guarantee weights will be backed up: `*.safetensors` or `/lo*/` can still exclude them. `computeEffectiveExcludes()` produces the filter list; rsync alone decides which paths match. The UI does not predict snapshot contents.
diff --git a/server/lib/README.md b/server/lib/README.md
index e4b10683ca..d23158f54b 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -32,7 +32,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `agentContextValidation.js` | Shared settings, MCP request/tool input/output schemas, result + approximate-token bounds, source-freshness status, and `advertiseAgentContextTools(scopes)` for the opt-in read-only agent-context surface. |
| `validation.js` | Catch-all Zod schemas (app/process/provider, social accounts, GitHub, backup/sharing, document/legacy-export) + the `validateRequest` middleware + shared helpers (`optionalBooleanMap`, `isSafeRecordId`, `parseIndexParam`, `parsePagination`). Re-exports the per-domain validation files below so existing deep imports keep working. |
| `taskDataInputCatalog.js` | Pure catalog and persisted ids for deterministic context sources that scheduled agent tasks can preload before dispatch. |
-| `sharedSchemas.js` | Cross-domain Zod fragments that `validation.js` and the per-domain `*Validation.js` files both need, kept in a leaf module so the domain files never import back through `validation.js` (its hoisted `export * from` lines would TDZ). `grokVideoDurationSchema` (grok clip-length union), `cloudModelIdString(message)` (cloud-CLI model-id charset/bounds), `recordRenderPinFields` (the `imageMode`/`imageModelId` per-record render pin pair), and `isSafeSubdirFilter(v)` (relative path with no wildcard, `..` segment, or leading `/`), and `csvIdsParam({ max, maxIdLength, truncate })` (the `?ids=a,b,c` batch-by-id query param: trims, drops empties, reads all-blank as absent, and either 400s or silently slices an over-cap batch). |
+| `sharedSchemas.js` | Cross-domain Zod fragments that `validation.js` and the per-domain `*Validation.js` files both need, kept in a leaf module so the domain files never import back through `validation.js` (its hoisted `export * from` lines would TDZ). `grokVideoDurationSchema` (grok clip-length union), `cloudModelIdString(message)` (cloud-CLI model-id charset/bounds), `recordRenderPinFields` (the `imageMode`/`imageModelId` per-record render pin pair), and `isSafeSubdirFilter(v)` (relative path with no wildcard, `..` segment, or leading `/`), and `csvIdsParam({ max, maxIdLength, truncate })` (the `?ids=a,b,c` batch-by-id query param: trims, drops empties, reads all-blank as absent, and either 400s or silently slices an over-cap batch). Also the backup-exclude anchoring rule (#7241): `anchorUserExclude` / `anchorUserExcludes` prepend the rsync root anchor (`/`) to any user pattern that is not already anchored and is not deliberately `*`/`**`-led, and `isSafeExcludePattern` (defined as `anchorUserExclude(x) !== null`, so the two can never disagree) rejects a `..` segment, a NUL, or a pattern longer than `EXCLUDE_PATTERN_MAX_LENGTH` once anchored — one rule shared by `backupConfigSchema` and `services/backup.js#computeEffectiveExcludes`, since an unanchored `cache/` is an rsync filter that matches at EVERY depth. Mirrored to `client/src/lib/backupExcludes.js`. |
| `generationModes.js` | Shared immutable image/video render-backend alphabets (`IMAGE_GEN_MODE[S]`, `QUEUEABLE_IMAGE_MODES`, `VIDEO_GEN_MODE[S]`, and cloud subsets) plus `mediaJobExecutionLane({ kind, mode, remote })` / `MEDIA_JOB_EXECUTION_LANES` — THE media-queue lane rule the scheduler and the public job projection share, kept below both validation and generation services so schemas never import orchestration modules. |
| `imageGenCapabilities.js` | Per-backend image-gen capability literals, a dependency-free leaf beside `generationModes.js`: `EDIT_INCAPABLE_IMAGE_MODES`/`isEditCapableMode` and the derived `I2I_CAPABLE_MODES`, the shipped defaults (`CODEX_IMAGEGEN_DEFAULT_MODEL`/`_EFFORT`, `AGY_IMAGEGEN_DEFAULT_MODEL`, `AGY_IMAGEGEN_IMAGE_MODEL`), the `AGY_`/`GROK_ASPECT_RATIOS` alphabets, and `IMAGE_GEN_PROVIDER_CAPABILITIES` (`supportsModelOverride`, `maxInputImages`, `promptRequiredWithInputImage`) with its `supportsCloudModelOverride`/`maxInputImages`/`cloudPromptRequired` readers. The `services/imageGen/*` modules re-export these, and `client/src/lib/imageGenModes.js` imports them instead of copying them (#6590). |
| `renderModeLadder.js` | Image-gen mode resolution ladder (#6815), a dependency-free leaf beside `generationModes.js`/`renderTargets.js` so the client imports it directly instead of hand-copying it: `isModeUsable(settings, mode)` (queueable + enabled gate, no per-provider spec lookup), `pickUsableMode(settings, candidates)` (first usable candidate, falling through disabled pins to the cloud-then-local tail), `renderTargetDefaults(settings, target)` (the normalized `settings.renderDefaults[target]` pin), and `imageModeCandidates(settings, target, record)` (the shared `[recordPin, targetPin, installDefault]` candidate order, declared once so a UI's own "what will Auto resolve to" display can't drift from the resolver). `services/imageGen/cloudProviderConfig.js` re-exports the first three for its existing callers. |
diff --git a/server/lib/sharedSchemas.js b/server/lib/sharedSchemas.js
index 9912d1e6d9..c664c4f6e0 100644
--- a/server/lib/sharedSchemas.js
+++ b/server/lib/sharedSchemas.js
@@ -110,3 +110,81 @@ export const isSafeSnapshotSource = (v) =>
&& v.length > 0
&& v.length <= 255
&& (v === '@legacy' || (v !== '.' && v !== '..' && /^[a-z0-9._-]+$/i.test(v)));
+
+// ---------------------------------------------------------------------------
+// Backup exclude patterns (#7241)
+//
+// The backup exclude list is rsync FILTER syntax, not a glob list. rsync anchors
+// a pattern to the transfer root only when it starts with `/`; anything else
+// matches at EVERY level of the tree. So a user who types `cache/` to skip
+// `data/cache/` also drops the per-run caches nested under training runs, and
+// `raw/` reaches into sprite runs and universes. The snapshot still reports
+// success — the omission surfaces only at restore, which is exactly when it
+// cannot be fixed.
+//
+// `DEFAULT_EXCLUDES` has always been anchored by hand (and a test in
+// `backup.test.js` fails if one entry is not); this is the same rule applied to
+// the one list a user actually edits. Lives here, beside `isSafeSubdirFilter`
+// and for the same reason: `backupConfigSchema` in `validation.js` and the
+// `computeEffectiveExcludes` guard in `services/backup.js` must share ONE rule,
+// and both modules already import this leaf — so declaring it here costs the
+// server suite no extra module instantiations (see lib/importScoping.test.js).
+// Anchoring happens at READ time, never by rewriting stored settings: the stored
+// value stays exactly what the user typed, so there is nothing to migrate.
+// Mirrored to `client/src/lib/backupExcludes.js` for the Backup settings tab.
+// ---------------------------------------------------------------------------
+
+/**
+ * Longest exclude pattern accepted, measured on the ANCHORED form — the string
+ * actually handed to rsync. Bounding the raw input instead would let a
+ * 256-character relative pattern pass validation and then anchor to 257, so the
+ * settings boundary would reject the very chip the UI had just shown as valid.
+ */
+export const EXCLUDE_PATTERN_MAX_LENGTH = 256;
+
+/**
+ * A pattern is left alone when it is already anchored (`/…`) or deliberately
+ * any-depth (`*…`, which covers rsync's `**` spelling). Everything else gets a
+ * leading `/`.
+ */
+const isAnchoredOrWildcardLed = (pattern) => pattern.startsWith('/') || pattern.startsWith('*');
+
+/**
+ * Normalize ONE user-entered pattern to the form rsync will be handed. This is
+ * the single declaration of what a legal pattern is — `isSafeExcludePattern`
+ * below is defined in terms of it, so the settings boundary can never accept
+ * something the read-time normalizer would then drop, or vice versa.
+ * @param {unknown} pattern
+ * @returns {string|null} the anchored pattern, or null when it is blank,
+ * non-string, or unsafe (caller drops it).
+ */
+export function anchorUserExclude(pattern) {
+ if (typeof pattern !== 'string') return null;
+ const trimmed = pattern.trim();
+ // A NUL would truncate the rsync argument; `..` in any segment (`../x`,
+ // `a/../../x`, the bare `..`) walks out of the data root.
+ if (!trimmed || trimmed.includes('\0')) return null;
+ if (trimmed.split('/').includes('..')) return null;
+ const anchored = isAnchoredOrWildcardLed(trimmed) ? trimmed : `/${trimmed}`;
+ return anchored.length <= EXCLUDE_PATTERN_MAX_LENGTH ? anchored : null;
+}
+
+/**
+ * Whether a stored/submitted pattern survives normalization. Shared with
+ * `lib/validation.js` so the settings boundary rejects exactly what
+ * `computeEffectiveExcludes` would have dropped.
+ * @param {unknown} pattern
+ * @returns {boolean}
+ */
+export const isSafeExcludePattern = (pattern) => anchorUserExclude(pattern) !== null;
+
+/**
+ * Normalize a whole user list, dropping blank/unsafe entries and duplicates
+ * that only differed by anchoring or whitespace.
+ * @param {unknown} patterns
+ * @returns {string[]}
+ */
+export function anchorUserExcludes(patterns) {
+ const list = Array.isArray(patterns) ? patterns : [];
+ return [...new Set(list.map(anchorUserExclude).filter(Boolean))];
+}
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 9ef99d5501..6183dc714a 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -11,6 +11,7 @@ import { QUEUEABLE_IMAGE_MODES, VIDEO_GEN_MODES } from './generationModes.js';
import { RENDER_TARGETS, RENDER_TARGET_BACKEND_AUTO } from './renderTargets.js';
import {
grokVideoDurationSchema, cloudModelIdString, recordRenderPinFields, isSafeSnapshotSource, isSafeSubdirFilter, csvIdsParam,
+ EXCLUDE_PATTERN_MAX_LENGTH, isSafeExcludePattern,
} from './sharedSchemas.js';
import { PR_COMPLETION_VALUES } from './prDisposition.js';
import { EFFORT_LEVELS } from './providerModels.js';
@@ -887,7 +888,18 @@ export const backupConfigSchema = z.object({
destPath: z.string().nullable().optional(),
cronExpression: z.string().optional().default(DEFAULT_BACKUP_CRON),
enabled: z.boolean().optional().default(true),
- excludePaths: z.array(z.string()).optional().default([]),
+ // rsync filter patterns, bounded and kept inside the data root. `..` (any
+ // segment) and NUL are rejected rather than sanitized, so a hand-edited
+ // settings.json can't hand rsync a pattern that walks upward or smuggles a
+ // separator. Anchoring itself happens at READ time in
+ // `computeEffectiveExcludes` — the stored value stays what the user typed —
+ // but the length bound is measured on the ANCHORED form, so this accepts
+ // exactly what that normalizer will keep. The outer .max() is a cheap ceiling
+ // on a pathological payload; isSafeExcludePattern owns the real rule.
+ excludePaths: z.array(
+ z.string().trim().min(1).max(EXCLUDE_PATTERN_MAX_LENGTH + 1)
+ .refine(isSafeExcludePattern, { message: `Exclude pattern must be at most ${EXCLUDE_PATTERN_MAX_LENGTH} characters once anchored, and may not contain ".." or a NUL byte` })
+ ).optional().default([]),
disabledDefaultExcludes: z.array(z.string()).optional().default([])
});
diff --git a/server/routes/backup.test.js b/server/routes/backup.test.js
index 9c123b389e..9bf1e286d7 100644
--- a/server/routes/backup.test.js
+++ b/server/routes/backup.test.js
@@ -82,7 +82,10 @@ describe('backup routes', () => {
it('runs the backup and forwards excludePaths', async () => {
getSettings.mockResolvedValue({
- backup: { destPath: '/dest', excludePaths: ['node_modules', '.git'] }
+ // Anchored is the canonical spelling; the second entry is deliberately
+ // not, to pin that the route forwards STORED settings verbatim — anchoring
+ // is a read-time concern inside computeEffectiveExcludes (#7241).
+ backup: { destPath: '/dest', excludePaths: ['/node_modules', '.git'] }
});
backup.runBackup.mockResolvedValue({ success: true, files: 100 });
const res = await request(buildApp()).post('/api/backup/run');
@@ -91,7 +94,7 @@ describe('backup routes', () => {
expect(backup.runBackup).toHaveBeenCalledWith(
'/dest',
undefined,
- { excludePaths: ['node_modules', '.git'], disabledDefaultExcludes: [] }
+ { excludePaths: ['/node_modules', '.git'], disabledDefaultExcludes: [] }
);
});
diff --git a/server/routes/settings.test.js b/server/routes/settings.test.js
index 9a24fdf0e3..0a048edf67 100644
--- a/server/routes/settings.test.js
+++ b/server/routes/settings.test.js
@@ -1281,3 +1281,36 @@ describe('Settings routes — backup schedule resolution (#6632)', () => {
expect(store.backup).toMatchObject({ enabled: true, cronExpression: '0 0 * * *', destPath: '/example-backups' });
});
});
+
+describe('Settings routes — backup excludePaths bounds (#7241)', () => {
+ beforeEach(() => {
+ store = {};
+ vi.clearAllMocks();
+ });
+
+ // These are rsync filter patterns handed straight to `--exclude`. A `..`
+ // segment walks out of the data root and a NUL truncates the argument, so the
+ // boundary rejects rather than sanitizes — a silently-trimmed pattern would
+ // exclude something other than what the user typed.
+ it.each([
+ ['a parent-directory escape', ['../../etc']],
+ ['a nested parent-directory escape', ['a/../../b']],
+ ['a NUL byte', [`repos${String.fromCharCode(0)}/etc`]],
+ ['a blank entry', ['']],
+ ['a pattern that overflows the cap once anchored', ['x'.repeat(256)]],
+ ['a pattern far past the cap', ['/'.padEnd(300, 'x')]],
+ ])('rejects %s', async (_label, excludePaths) => {
+ const res = await request(buildApp()).put('/api/settings').send({ backup: { excludePaths } });
+ expect(res.status).toBe(400);
+ expect(store.backup).toBeUndefined();
+ });
+
+ it('accepts anchored and wildcard-led patterns and stores them as typed', async () => {
+ const excludePaths = ['/repos/', '**/raw/', 'cache/'];
+ const res = await request(buildApp()).put('/api/settings').send({ backup: { excludePaths } });
+ expect(res.status).toBe(200);
+ // Stored verbatim — anchoring is a read-time concern in
+ // `computeEffectiveExcludes`, so nothing is rewritten under the user.
+ expect(store.backup.excludePaths).toEqual(excludePaths);
+ });
+});
diff --git a/server/services/backup.js b/server/services/backup.js
index 1a636e2396..c8a0961eb5 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -20,7 +20,7 @@ import { checkHealth, ensureSchema, getServerMajorVersion } from '../lib/db.js';
import { resolvePgDumpBinary } from '../lib/pgTools.js';
import { getBackendName } from './memoryBackend.js';
import { emitErrorEvent, ServerError } from '../lib/errorHandler.js';
-import { isSafeSnapshotSource, isSafeSubdirFilter } from '../lib/sharedSchemas.js';
+import { isSafeSnapshotSource, isSafeSubdirFilter, anchorUserExcludes } from '../lib/sharedSchemas.js';
import { getIo } from './socket.js';
import { reloadSettings } from './settings.js';
import { invalidateAllCaches as invalidateBrainCaches } from './brainStorage.js';
@@ -413,14 +413,19 @@ function runRsync(srcDir, destDir, flags = []) {
* - Array.isArray guards: settings can be hand-edited or sent by a stale
* client, so a non-array value here would otherwise throw inside .filter
* and abort the backup before the defensive allow-list has a chance to apply.
+ * - User patterns are ANCHORED here (`anchorUserExcludes`), not in storage: a
+ * bare `cache/` is rsync for "every cache/ at any depth", which silently drops
+ * the per-run caches nested under training runs too. Normalizing on read leaves
+ * the stored value exactly as typed, so there is no migration and nothing is
+ * rewritten under the user. A `*`/`**`-led pattern stays as-is — that is the
+ * deliberate way to ask for any-depth matching.
*/
export function computeEffectiveExcludes({ excludePaths, disabledDefaultExcludes } = {}) {
const overridablePaths = new Set(DEFAULT_EXCLUDES.filter(e => e.overridable).map(e => e.path));
const disabledList = Array.isArray(disabledDefaultExcludes) ? disabledDefaultExcludes : [];
- const userList = Array.isArray(excludePaths) ? excludePaths : [];
const disabledSet = new Set(disabledList.filter(p => overridablePaths.has(p)));
const activeDefaults = DEFAULT_EXCLUDES.filter(e => !disabledSet.has(e.path)).map(e => e.path);
- const userExcludes = userList.filter(Boolean);
+ const userExcludes = anchorUserExcludes(excludePaths);
return [...new Set([...activeDefaults, ...userExcludes])];
}
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index 0241d3e07f..5598abd20c 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -111,6 +111,7 @@ vi.mock('./brainStorage.js', async (importOriginal) => ({
import { reloadSettings } from './settings.js';
import { invalidateAllCaches as invalidateBrainCaches } from './brainStorage.js';
import { DEFAULT_EXCLUDES, computeEffectiveExcludes, listSnapshots, openSnapshotStream, restoreSnapshot, resolveRsyncBinary } from './backup.js';
+import { EXCLUDE_PATTERN_MAX_LENGTH, anchorUserExclude, anchorUserExcludes, isSafeExcludePattern } from '../lib/sharedSchemas.js';
// fs.access is mocked file-wide because backup.js probes the .in-progress marker
// with it. Restore the real implementation before EVERY test: vi.clearAllMocks()
@@ -204,13 +205,97 @@ describe('computeEffectiveExcludes', () => {
expect(result).toContain(target);
});
- it('merges user excludePaths on top of active defaults', () => {
+ it('merges user excludePaths on top of active defaults, anchored to the data root', () => {
const result = computeEffectiveExcludes({
excludePaths: ['my/custom/path', 'cache/'],
disabledDefaultExcludes: []
});
- expect(result).toContain('my/custom/path');
- expect(result).toContain('cache/');
+ // Anchored: a bare `cache/` is rsync for "every cache/ at any depth", which
+ // would also drop training-runs/*/cache/ and friends (#7241).
+ expect(result).toContain('/my/custom/path');
+ expect(result).toContain('/cache/');
+ expect(result).not.toContain('my/custom/path');
+ expect(result).not.toContain('cache/');
+ });
+
+ it('anchors every returned pattern unless it is deliberately wildcard-led', () => {
+ const result = computeEffectiveExcludes({
+ excludePaths: ['repos/', 'cache', '**/raw/', '/already/anchored'],
+ disabledDefaultExcludes: []
+ });
+ expect(result).toEqual(expect.arrayContaining(['/repos/', '/cache', '**/raw/', '/already/anchored']));
+ // The whole list — defaults included — is anchored or wildcard-led. This is
+ // the invariant, not the four spellings above: an unanchored entry anywhere
+ // in the list silently drops user data at any depth.
+ for (const pattern of result) {
+ expect(pattern.startsWith('/') || pattern.startsWith('*'), pattern).toBe(true);
+ }
+ });
+
+ it('passes a **-led user pattern through unchanged', () => {
+ // Any-depth matching stays available DELIBERATELY — it is just no longer
+ // what a user gets by accident from typing a bare directory name.
+ const result = computeEffectiveExcludes({
+ excludePaths: ['**/node_modules/', '*.tmp'],
+ disabledDefaultExcludes: []
+ });
+ expect(result).toContain('**/node_modules/');
+ expect(result).toContain('*.tmp');
+ });
+
+ it('dedupes user patterns that differ only by anchoring or whitespace', () => {
+ const result = computeEffectiveExcludes({
+ excludePaths: ['repos/', '/repos/', ' repos/ '],
+ disabledDefaultExcludes: []
+ });
+ expect(result.filter(p => p === '/repos/')).toHaveLength(1);
+ });
+
+ it('measures the length bound on the ANCHORED form, not the raw input', () => {
+ // A 255-char relative pattern anchors to exactly 256 and survives; 256 would
+ // anchor to 257. Bounding the RAW input instead would let the settings
+ // boundary accept a chip that this normalizer then silently dropped, so the
+ // snapshot would run without an exclude the UI had shown as saved.
+ const fits = 'a'.repeat(EXCLUDE_PATTERN_MAX_LENGTH - 1);
+ const overflows = 'a'.repeat(EXCLUDE_PATTERN_MAX_LENGTH);
+ const result = computeEffectiveExcludes({ excludePaths: [fits, overflows], disabledDefaultExcludes: [] });
+ expect(result).toContain(`/${fits}`);
+ expect(result).not.toContain(`/${overflows}`);
+ // An ALREADY-anchored pattern of exactly the max is untouched and kept.
+ const anchoredMax = `/${'b'.repeat(EXCLUDE_PATTERN_MAX_LENGTH - 1)}`;
+ expect(computeEffectiveExcludes({ excludePaths: [anchoredMax] })).toContain(anchoredMax);
+ // The settings boundary agrees with the normalizer in both directions.
+ expect(isSafeExcludePattern(fits)).toBe(true);
+ expect(isSafeExcludePattern(overflows)).toBe(false);
+ expect(isSafeExcludePattern(anchoredMax)).toBe(true);
+ });
+
+ // The Backup settings tab anchors a pattern as the user adds it, so the chip
+ // they see is the filter that runs. A one-sided edit to either copy would put
+ // the preview and the snapshot out of step silently — which is the whole
+ // failure mode #7241 is about. The mirror is a dependency-free leaf, so
+ // importing it here costs nothing.
+ it('the client mirror applies the identical rule', async () => {
+ const mirror = await import('../../client/src/lib/backupExcludes.js');
+ const cases = ['repos/', 'cache', '**/raw/', '*.tmp', '/anchored', ' spaced/ ', '', '../../etc', 'a/../../b',
+ 'x'.repeat(EXCLUDE_PATTERN_MAX_LENGTH - 1), 'x'.repeat(EXCLUDE_PATTERN_MAX_LENGTH), `/${'x'.repeat(EXCLUDE_PATTERN_MAX_LENGTH - 1)}`];
+ for (const input of cases) {
+ expect(mirror.anchorUserExclude(input), input).toBe(anchorUserExclude(input));
+ expect(mirror.isSafeExcludePattern(input), input).toBe(isSafeExcludePattern(input));
+ }
+ expect(mirror.anchorUserExcludes(cases)).toEqual(anchorUserExcludes(cases));
+ expect(mirror.EXCLUDE_PATTERN_MAX_LENGTH).toBe(EXCLUDE_PATTERN_MAX_LENGTH);
+ });
+
+ it('drops a user pattern that tries to escape the data root', () => {
+ // Defense in depth — the settings boundary rejects these, but a hand-edited
+ // settings.json is read straight through by the scheduler.
+ const result = computeEffectiveExcludes({
+ excludePaths: ['../../etc/', 'a/../../b', 'ok/path'],
+ disabledDefaultExcludes: []
+ });
+ expect(result).toContain('/ok/path');
+ expect(result.some(p => p.includes('..'))).toBe(false);
});
it('dedupes when a user exclude matches an active default', () => {
@@ -227,7 +312,7 @@ describe('computeEffectiveExcludes', () => {
excludePaths: ['', null, undefined, 'real/path'],
disabledDefaultExcludes: []
});
- expect(result).toContain('real/path');
+ expect(result).toContain('/real/path');
expect(result).not.toContain('');
expect(result).not.toContain(null);
});