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

address review (codex): canonicalize document paths and harden the save path

Adam Eivy3b8089135031
diff --git a/client/src/components/apps/tabs/DocumentsTab.jsx b/client/src/components/apps/tabs/DocumentsTab.jsx
index b5de5a7f31..148f6fbdec 100644
--- a/client/src/components/apps/tabs/DocumentsTab.jsx
+++ b/client/src/components/apps/tabs/DocumentsTab.jsx
@@ -1,5 +1,6 @@
import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
-import { RefreshCw, FileText, Pencil, Save, X, Plus } from 'lucide-react';
+import { useSearchParams } from 'react-router';
+import { RefreshCw, FileText, Pencil, Save, X, Plus, AlertTriangle } from 'lucide-react';
import toast from '../../ui/Toast';
import BrailleSpinner from '../../BrailleSpinner';
import MarkdownOutput from '../../cos/MarkdownOutput';
@@ -16,41 +17,81 @@ export default function DocumentsTab({ appId, repoPath }) {
const [docs, setDocs] = useState([]);
const [hasPlanning, setHasPlanning] = useState(false);
const [loading, setLoading] = useState(true);
- const [selectedDoc, setSelectedDoc] = useState(null);
+ // The listing request FAILED — distinct from a listing that succeeded and is
+ // legitimately empty, which renders the "no documents found" state instead.
+ const [listFailed, setListFailed] = useState(false);
+
+ // The open document lives in the URL so it is shareable, bookmarkable and
+ // reload-safe (client/src/AGENTS.md). A search param rather than a route
+ // segment because a document path is itself multi-segment (`docs/a/b.md`).
+ const [searchParams, setSearchParams] = useSearchParams();
+ const selectedDoc = searchParams.get('doc');
const selectedDocRef = useRef(selectedDoc);
selectedDocRef.current = selectedDoc;
+
+ // `null` = failed to load (or nothing selected); `''` is a real, empty file.
const [docContent, setDocContent] = useState(null);
const [loadingDoc, setLoadingDoc] = useState(false);
+ // The document being created — never in the URL, since it doesn't exist yet.
+ const [creating, setCreating] = useState(null);
const [editing, setEditing] = useState(false);
const [editContent, setEditContent] = useState('');
const [saving, setSaving] = useState(false);
// dir → explicit open/closed, overriding the default-open rule below
const [groupOverrides, setGroupOverrides] = useState({});
- const loadDocument = useCallback(async (filename) => {
- setSelectedDoc(filename);
+ const activeDoc = creating || selectedDoc;
+
+ const selectDoc = useCallback((filename) => {
+ setCreating(null);
setEditing(false);
+ setSearchParams(prev => {
+ const next = new URLSearchParams(prev);
+ next.set('doc', filename);
+ return next;
+ }, { replace: true });
+ }, [setSearchParams]);
+
+ // Load whatever the URL points at, so a deep link, a sidebar click, and the
+ // browser Back button all take the same path.
+ useEffect(() => {
+ if (!selectedDoc) {
+ setDocContent(null);
+ return undefined;
+ }
+ let cancelled = false;
setLoadingDoc(true);
- const data = await api.getAppDocument(appId, filename, { silent: true }).catch(() => null);
- setDocContent(data?.content || null);
- setLoadingDoc(false);
- }, [appId]);
+ api.getAppDocument(appId, selectedDoc, { silent: true })
+ .catch(() => null)
+ .then(data => {
+ if (cancelled) return;
+ setDocContent(typeof data?.content === 'string' ? data.content : null);
+ setLoadingDoc(false);
+ });
+ return () => { cancelled = true; };
+ }, [appId, selectedDoc]);
const fetchDocuments = useCallback(async () => {
setLoading(true);
- const data = await api.getAppDocuments(appId, { silent: true })
- .catch(() => ({ documents: [], docs: [], hasPlanning: false }));
+ const data = await api.getAppDocuments(appId, { silent: true }).catch(() => null);
+ setLoading(false);
+
+ // A failed refresh keeps the list already on screen rather than blanking it.
+ if (!data) {
+ setListFailed(true);
+ return;
+ }
+ setListFailed(false);
setDocuments(data.documents || []);
setDocs(data.docs || []);
setHasPlanning(data.hasPlanning || false);
- setLoading(false);
// Auto-select the first root document, falling back to the docs/ tree
const firstExisting = (data.documents || []).find(d => d.exists)?.filename || (data.docs || [])[0];
if (firstExisting && !selectedDocRef.current) {
- loadDocument(firstExisting);
+ selectDoc(firstExisting);
}
- }, [appId, loadDocument]);
+ }, [appId, selectDoc]);
const enterEditMode = () => {
setEditContent(docContent || '');
@@ -58,7 +99,7 @@ export default function DocumentsTab({ appId, repoPath }) {
};
const enterCreateMode = (filename) => {
- setSelectedDoc(filename);
+ setCreating(filename);
setDocContent(null);
setEditContent('');
setEditing(true);
@@ -66,12 +107,15 @@ export default function DocumentsTab({ appId, repoPath }) {
const cancelEdit = () => {
setEditing(false);
+ setCreating(null);
setEditContent('');
};
const handleSave = async () => {
+ const saved = activeDoc;
setSaving(true);
- const result = await api.saveAppDocument(appId, selectedDoc, editContent, undefined, { silent: true })
+ const result = await api
+ .saveAppDocument(appId, saved, editContent, undefined, { silent: true })
.catch(() => null);
setSaving(false);
@@ -86,9 +130,11 @@ export default function DocumentsTab({ appId, repoPath }) {
return;
}
- toast.success(`Committed ${result.created ? 'new' : 'updated'} ${selectedDoc} (${result.hash})`);
- setDocContent(editContent);
+ toast.success(`Committed ${result.created ? 'new' : 'updated'} ${saved} (${result.hash})`);
setEditing(false);
+ setDocContent(editContent);
+ // A newly created document now exists — hand it to the URL-driven path.
+ if (creating) selectDoc(saved);
fetchDocuments();
};
@@ -108,15 +154,16 @@ export default function DocumentsTab({ appId, repoPath }) {
return [...groups.entries()];
}, [docs]);
- if (loading) {
+ if (loading && documents.length === 0 && !listFailed) {
return <BrailleSpinner text="Loading documents" />;
}
const existingDocs = documents.filter(d => d.exists);
const missingDocs = documents.filter(d => !d.exists);
+ const nothingToShow = existingDocs.length === 0 && docs.length === 0;
const docButtonClass = (filename) => `px-3 py-2 rounded-lg text-sm text-left transition-colors ${
- selectedDoc === filename
+ activeDoc === filename
? 'bg-port-accent/20 text-port-accent border border-port-accent/30'
: 'bg-port-card border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50'
}`;
@@ -140,27 +187,44 @@ export default function DocumentsTab({ appId, repoPath }) {
</button>
</div>
- {existingDocs.length === 0 && docs.length === 0 && !editing ? (
- <div className="bg-port-card border border-port-border rounded-lg p-8 text-center">
- <FileText size={32} className="text-gray-600 mx-auto mb-3" />
- <p className="text-gray-400 mb-2">No documents found</p>
- <p className="text-xs text-gray-500 mb-4">
- No markdown in the repo root or a docs/ directory
- </p>
- {missingDocs.length > 0 && (
- <div className="flex gap-2 justify-center flex-wrap">
- {missingDocs.map(doc => (
- <button
- key={doc.filename}
- onClick={() => enterCreateMode(doc.filename)}
- className="px-3 py-1.5 bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded-lg text-xs flex items-center gap-1"
- >
- <Plus size={14} /> Create {doc.filename}
- </button>
- ))}
- </div>
- )}
+ {listFailed && (
+ <div className="bg-port-card border border-port-error/40 rounded-lg p-3 flex items-center gap-2 text-sm text-port-error">
+ <AlertTriangle size={16} />
+ <span>
+ Could not load the document list{documents.length > 0 ? ' — showing the last known list' : ''}.
+ </span>
+ <button
+ onClick={fetchDocuments}
+ className="ml-auto px-2 py-1 bg-port-border hover:bg-port-border/80 text-white rounded text-xs"
+ >
+ Retry
+ </button>
</div>
+ )}
+
+ {nothingToShow && !editing ? (
+ !listFailed && (
+ <div className="bg-port-card border border-port-border rounded-lg p-8 text-center">
+ <FileText size={32} className="text-gray-600 mx-auto mb-3" />
+ <p className="text-gray-400 mb-2">No documents found</p>
+ <p className="text-xs text-gray-500 mb-4">
+ No markdown in the repo root or a docs/ directory
+ </p>
+ {missingDocs.length > 0 && (
+ <div className="flex gap-2 justify-center flex-wrap">
+ {missingDocs.map(doc => (
+ <button
+ key={doc.filename}
+ onClick={() => enterCreateMode(doc.filename)}
+ className="px-3 py-1.5 bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded-lg text-xs flex items-center gap-1"
+ >
+ <Plus size={14} /> Create {doc.filename}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ )
) : (
<div className="flex flex-col sm:flex-row gap-4">
{/* Document selector */}
@@ -168,7 +232,7 @@ export default function DocumentsTab({ appId, repoPath }) {
{existingDocs.map(doc => (
<button
key={doc.filename}
- onClick={() => loadDocument(doc.filename)}
+ onClick={() => selectDoc(doc.filename)}
className={docButtonClass(doc.filename)}
>
<FileText size={14} className="inline mr-2" />
@@ -194,7 +258,7 @@ export default function DocumentsTab({ appId, repoPath }) {
{paths.map(path => (
<button
key={path}
- onClick={() => loadDocument(path)}
+ onClick={() => selectDoc(path)}
title={path}
className={`w-full truncate ${docButtonClass(path)}`}
>
@@ -229,7 +293,7 @@ export default function DocumentsTab({ appId, repoPath }) {
) : editing ? (
<div className="space-y-3">
<div className="flex items-center justify-between">
- <span className="text-sm text-gray-400">Editing {selectedDoc}</span>
+ <span className="text-sm text-gray-400">Editing {activeDoc}</span>
<div className="flex gap-2">
<button
onClick={cancelEdit}
@@ -256,7 +320,7 @@ export default function DocumentsTab({ appId, repoPath }) {
spellCheck={false}
/>
</div>
- ) : docContent ? (
+ ) : docContent !== null ? (
<div>
<div className="flex items-center justify-between mb-2 gap-2">
<span className="text-xs text-gray-500 truncate">{selectedDoc}</span>
@@ -267,7 +331,9 @@ export default function DocumentsTab({ appId, repoPath }) {
<Pencil size={14} /> Edit
</button>
</div>
- <MarkdownOutput content={docContent} />
+ {docContent
+ ? <MarkdownOutput content={docContent} />
+ : <p className="text-gray-500 text-sm italic">This document is empty.</p>}
</div>
) : selectedDoc ? (
<p className="text-gray-500 text-sm">Failed to load document</p>
diff --git a/client/src/components/apps/tabs/DocumentsTab.test.jsx b/client/src/components/apps/tabs/DocumentsTab.test.jsx
index c808d971f6..4c1bf3f79e 100644
--- a/client/src/components/apps/tabs/DocumentsTab.test.jsx
+++ b/client/src/components/apps/tabs/DocumentsTab.test.jsx
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
import DocumentsTab from './DocumentsTab';
vi.mock('../../../services/api', () => ({
@@ -24,6 +25,13 @@ const listing = {
hasPlanning: false
};
+const renderTab = (initialPath = '/apps/app-1/documents') =>
+ render(
+ <MemoryRouter initialEntries={[initialPath]}>
+ <DocumentsTab appId="app-1" repoPath="/repo/example" />
+ </MemoryRouter>
+ );
+
describe('DocumentsTab', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -33,7 +41,7 @@ describe('DocumentsTab', () => {
});
it('lists every root markdown file, not just the conventional four', async () => {
- render(<DocumentsTab appId="app-1" repoPath="/repo/example" />);
+ renderTab();
expect(await screen.findByRole('button', { name: /ARCHITECTURE\.md/ })).toBeInTheDocument();
expect(screen.getByRole('button', { name: /README\.md/ })).toBeInTheDocument();
@@ -42,7 +50,7 @@ describe('DocumentsTab', () => {
});
it('groups the docs/ tree by directory and opens a nested file by its full path', async () => {
- render(<DocumentsTab appId="app-1" repoPath="/repo/example" />);
+ renderTab();
expect(await screen.findByText('docs/')).toBeInTheDocument();
expect(screen.getByText('docs/decisions/')).toBeInTheDocument();
@@ -52,8 +60,23 @@ describe('DocumentsTab', () => {
await waitFor(() => expect(requestedPaths()).toContain('docs/decisions/2026-01-01-choice.md'));
});
+ it('opens the document named by the URL instead of auto-selecting', async () => {
+ renderTab('/apps/app-1/documents?doc=docs%2FAPI.md');
+
+ await waitFor(() => expect(requestedPaths()).toEqual(['docs/API.md']));
+ });
+
+ it('renders an empty document as empty, not as a load failure', async () => {
+ api.getAppDocument.mockResolvedValue({ filename: 'ARCHITECTURE.md', content: '' });
+
+ renderTab();
+
+ expect(await screen.findByText('This document is empty.')).toBeInTheDocument();
+ expect(screen.queryByText('Failed to load document')).not.toBeInTheDocument();
+ });
+
it('still offers to create a conventional document the repo is missing', async () => {
- render(<DocumentsTab appId="app-1" repoPath="/repo/example" />);
+ renderTab();
expect(await screen.findByRole('button', { name: /AGENTS\.md/ })).toBeInTheDocument();
});
@@ -61,9 +84,19 @@ describe('DocumentsTab', () => {
it('shows the empty state only when the root and docs/ are both empty', async () => {
api.getAppDocuments.mockResolvedValue({ documents: [], docs: [], hasPlanning: false });
- render(<DocumentsTab appId="app-1" repoPath="/repo/example" />);
+ renderTab();
expect(await screen.findByText('No documents found')).toBeInTheDocument();
expect(api.getAppDocument).not.toHaveBeenCalled();
});
+
+ it('reports a failed listing instead of claiming the repo has no documents', async () => {
+ api.getAppDocuments.mockRejectedValue(new Error('boom'));
+
+ renderTab();
+
+ expect(await screen.findByText(/Could not load the document list/)).toBeInTheDocument();
+ expect(screen.queryByText('No documents found')).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument();
+ });
});
diff --git a/server/lib/README.md b/server/lib/README.md
index eb6aa78951..8be133e9f2 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -275,7 +275,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). Includes `probeFrameCount(videoPath)` (metadata `nb_frames`, falling back to a real `-count_frames` pass — expensive, so call it once per file) and `trimVideoFromFrame(videoPath, outPath, {startFrame, fps})` — a frame-EXACT head cut via the `trim` filter (an `-ss` seek can drift a frame, which reads as a stutter at a stitch seam), keeping audio in sync with `atrim` when the clip has a soundtrack and taking `-an` when it doesn't. Re-encodes by necessity, so a later concat must re-encode too; `outPath` may equal the input (temp-file + rename install). Used by the chained-render context window — see `videoContinuity.js`. `buildTrimConcatArgs({inputs, outPath, width, height, fps, withAudio})` builds the argv for the other half of that job: a concat that drops leading frames from some of its inputs inside a `filter_complex` graph, so the cuts ride along with the timeline encode instead of costing one pre-encode per clip (pass `withAudio` only when EVERY input has an audio stream — check with `hasAudioStream`). `H264_ENCODE_ARGS` / `AAC_ENCODE_ARGS` are the shared encode profile: clips produced by different paths here get concatenated together, so a mismatch shows up as one segment graded differently from its neighbours — spread these rather than re-typing the flags. Every re-encode here also pins BT.709: `BT709_CONTAINER_ARGS` (the `colr` atom, always emitted) plus `bt709TagFilter()` → the `BT709_TAG_FILTER` `setparams=…` string, or `null` on an ffmpeg without that filter (`supportsSetparamsFilter()` probes `-filters` once per process; `null` = not probed, and a probe that couldn't run stays uncached). Both halves are required — from ffmpeg 8 the encoder reads color properties off the FRAMES, silently overriding the container flags, so a flags-only output decodes washed-out. `buildTrimConcatArgs` takes the filter as its `colorTagFilter` option rather than probing, to stay pure. |
| `frameQuality.js` | Scores decoded video frames so a chained render can CHOOSE its continuation anchor instead of taking whatever an end-seek lands on. `scoreFrame({width,height,data},{recency})` combines three terms over a raw single-channel buffer: log-compressed `gradientVariance` (focus), distance of `meanLuma` from mid-grey (exposure penalty, which rejects a fade-to-black or a blown highlight), and a small linear recency bonus that keeps the anchor near the cut when candidates are comparably clean. Usability and ranking are deliberately separate: `usable` gates on raw gradient variance against `MIN_SIGNAL_VARIANCE` alone, so only a mathematically degenerate frame is rejected and a legitimately dark low-key tail still qualifies — the same contract `imageFrameStats.js` keeps. Gating on the composite score instead would reject every night scene on the exposure term. `TAIL_WINDOW_SECONDS` is capped at the reach of the single `-sseof -1.0` seek this replaces: focus is systematically highest at the OLDEST candidate, so a wider window would widen the backward jump at each chain seam rather than tightening it. `pickBestFrame(paths)` decodes each candidate through `sharp` and returns the winner (or `null` when nothing decodes or every candidate is degenerate, so the caller degrades rather than failing a render); its `index` is the position in the array AS PASSED, because the caller turns that into the anchor's time offset. `MAX_CANDIDATES` is derived from the window, never set independently — the ffmpeg-side `-frames:v` cap truncates from the NEWEST end, exactly the frames recency prefers. `TAIL_WINDOW_SECONDS` / `CANDIDATE_FPS` / `MAX_CANDIDATES` define the window the caller decodes from. Consumer: `services/videoGen/local.js#extractLastFrame`. |
| `ffmpegRenderGuard.js` | `attachFfmpegRenderGuard(proc, {label, onSpawnError, onProcessError, onClose})` — shared spawn-state tracking + exactly-once `terminal` guard + pre-vs-post-spawn dispatch for the SSE ffmpeg render runners (musicVideo/render + videoTimeline/local). Owns the 'spawn'/'error'/'close' wiring (only the pre-spawn 'error' or 'close' finalizes; a post-spawn 'error' records only) and takes the service-specific finalize bodies as callbacks so each renderer keeps its own project-status/history behavior. |
-| `gitArgs.js` | `PROTECTED_BRANCHES`, `validateFilePaths(files)` — pure command-arg builders/validators for `git.js` (reject injection/traversal in staged paths). |
+| `gitArgs.js` | `PROTECTED_BRANCHES`, `validateFilePaths(files)`, `isGitStageableFilePath(file)` — pure command-arg builders/validators for `git.js` (reject injection/traversal in staged paths). `isGitStageableFilePath` is `validateFilePaths`' non-throwing twin, for callers that must refuse an unstageable path BEFORE writing the file rather than 500 on the commit. |
| `gitCommitProbe.js` | `commitsSince(workspacePath, sinceMs)` / `committedDuringRun(workspacePath, sinceMs)` — the run-window commit probe: how many commits landed with a COMMITTER date inside a run's window (so a rebase/commit by the agent counts, a merely-pulled remote commit does not). The single machine-checkable "did this run commit anything?" primitive shared by finalize's success-criteria evaluation, run completion, runner completion, and orphan recovery — it replaced the unsatisfiable task-id commit-marker grep (#3637). Non-throwing: a non-repo, empty repo, or git timeout is 0. |
| `gitForge.js` | `parseGitRemote`, `parseGitHubOwnerFromRemote`, `pickGhAccountForOwner`, `detectForgeCli`, `parsePullRequestUrl` — pure GitHub/GitLab remote + PR/MR URL parsers and forge/account selectors used by `git.js`. |
| `gitOutputParsers.js` | `parseStatus`, `parseDiffStat`, `parseBranchVerboseLine`, `parseSubmoduleStatusLine`/`SUBMODULE_STATUS_RE`, `extractAgentSummary` — pure parsers turning git command output into structured data for `git.js`. `extractAgentSummary` anchors on `agentOutputMarkers`' completion marker so a TUI agent's PR body carries its sentinel summary, not the lifecycle telemetry above it. `isBenignConcurrentFetchRefRace(stderr)` reads a non-zero `git fetch` as a SUCCESS when its only failure is a lost compare-and-swap whose refs already hold the fetched commits — the routine outcome when the Git tab, `getRemoteBranches`, and CoS agent worktrees fetch one `.git` at once. |
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index d83e3d79a3..1efd992838 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -1290,7 +1290,7 @@
"sources": [
{
"source": "server/routes/apps/documents.js",
- "line": 109
+ "line": 129
}
]
},
@@ -1301,7 +1301,7 @@
"sources": [
{
"source": "server/routes/apps/documents.js",
- "line": 143
+ "line": 163
}
]
},
@@ -1312,7 +1312,7 @@
"sources": [
{
"source": "server/routes/apps/documents.js",
- "line": 158
+ "line": 178
}
]
},
diff --git a/server/lib/gitArgs.js b/server/lib/gitArgs.js
index 6b28f48e05..a7c3f6c1ce 100644
--- a/server/lib/gitArgs.js
+++ b/server/lib/gitArgs.js
@@ -9,6 +9,31 @@
// would break the published site, so it is protected everywhere the others are.
export const PROTECTED_BRANCHES = ['main', 'master', 'dev', 'develop', 'release', 'gh-pages'];
+// Null bytes and shell command separators. Shared by the predicate and the
+// thrower below so the two can never disagree about what is unsafe.
+const GIT_UNSAFE_CHARS = /[\0;|&`$]/;
+
+/**
+ * `validateFilePaths`'s non-throwing twin: true when `file` is a repo-relative
+ * path git can be asked to stage. For callers that must REPORT an unstageable
+ * path as data rather than throw — e.g. a route that would otherwise write the
+ * file to disk and only then discover the commit can't reference it, leaving a
+ * mutated tree behind a 500. `validateFilePaths` is layered on this, so the
+ * gate and the predicate always admit the same set.
+ *
+ * Note `..` is rejected as a SUBSTRING, not just as a path component, which is
+ * stricter than `pathSafety.isTopLevelEntryName` — `notes..md` is a perfectly
+ * good filename that git staging still refuses here.
+ *
+ * @param {string} file - Repo-relative file path
+ * @returns {boolean}
+ */
+export function isGitStageableFilePath(file) {
+ if (!file || typeof file !== 'string') return false;
+ if (GIT_UNSAFE_CHARS.test(file)) return false;
+ return !file.startsWith('/') && !file.includes('..');
+}
+
/**
* Validate file paths to prevent command injection and path traversal.
* Throws on null bytes / shell metacharacters, absolute paths, or `..` traversal.
@@ -26,11 +51,11 @@ export function validateFilePaths(files) {
const fileList = Array.isArray(files) ? files : [files];
return fileList.map(f => {
// Reject paths with null bytes or command separators
- if (/[\0;|&`$]/.test(f)) {
+ if (GIT_UNSAFE_CHARS.test(f)) {
throw new Error(`Invalid character in file path: ${f}`);
}
// Reject absolute paths or parent directory traversal
- if (f.startsWith('/') || f.includes('..')) {
+ if (!isGitStageableFilePath(f)) {
throw new Error(`Invalid file path: ${f}`);
}
return f;
diff --git a/server/routes/apps/documents.js b/server/routes/apps/documents.js
index 52246deb0c..d15c773ff7 100644
--- a/server/routes/apps/documents.js
+++ b/server/routes/apps/documents.js
@@ -13,9 +13,10 @@
*/
import { Router } from 'express';
-import { readdir, readFile } from 'fs/promises';
-import { join } from 'path';
+import { readdir, readFile, realpath } from 'fs/promises';
+import { dirname, join } from 'path';
import { atomicWrite, listDirectoryByExtension } from '../../lib/fileUtils.js';
+import { isGitStageableFilePath } from '../../lib/gitArgs.js';
import { isPathInsideDir, isSafeFilename, isTopLevelEntryName } from '../../lib/pathSafety.js';
import { documentUpdateSchema } from '../../lib/validation.js';
import { asyncHandler, ServerError } from '../../lib/errorHandler.js';
@@ -82,8 +83,15 @@ function isAllowedDocumentPath(rel) {
/**
* Validate `*docPath` and resolve it inside the app's repo. Throws the same
* 400s the single-file allowlist used to, so client error handling is unchanged.
+ *
+ * The containment check runs TWICE, and the second pass is what makes it real:
+ * `isPathInsideDir` is lexical, so a symlinked directory component inside the
+ * repo (`docs/shared -> /outside`) passes the string comparison while `readFile`
+ * and `atomicWrite` happily follow the link. Canonicalizing closes that escape.
+ * The old six-name allowlist had no directory component to subvert; the wildcard
+ * route does, so the canonical check arrived with it.
*/
-function resolveDocumentPath(app, docPath) {
+async function resolveDocumentPath(app, docPath) {
const filename = Array.isArray(docPath) ? docPath.join('/') : String(docPath || '');
if (!isAllowedDocumentPath(filename)) {
@@ -91,9 +99,21 @@ function resolveDocumentPath(app, docPath) {
}
const resolved = join(app.repoPath, filename);
- if (!isPathInsideDir(app.repoPath, resolved)) {
- throw new ServerError('Invalid document path', { status: 400, code: 'PATH_TRAVERSAL' });
+ const traversal = () =>
+ new ServerError('Invalid document path', { status: 400, code: 'PATH_TRAVERSAL' });
+
+ if (!isPathInsideDir(app.repoPath, resolved)) throw traversal();
+
+ // The PARENT must canonically live in the repo (so a not-yet-created file
+ // still validates), and so must the file itself when it already exists — the
+ // leaf can be a symlink even when every directory above it is real.
+ const realRoot = await realpath(app.repoPath);
+ const realParent = await realpath(dirname(resolved)).catch(() => null);
+ if (!realParent || (realParent !== realRoot && !isPathInsideDir(realRoot, realParent))) {
+ throw traversal();
}
+ const realFile = await realpath(resolved).catch(() => null);
+ if (realFile && !isPathInsideDir(realRoot, realFile)) throw traversal();
return { filename, resolved };
}
@@ -144,7 +164,7 @@ router.get('/:id/documents/*docPath', loadApp, asyncHandler(async (req, res) =>
const app = req.loadedApp;
await requireRepoPath(app);
- const { filename, resolved } = resolveDocumentPath(app, req.params.docPath);
+ const { filename, resolved } = await resolveDocumentPath(app, req.params.docPath);
if (!await pathExists(resolved)) {
throw new ServerError('Document not found', { status: 404, code: 'NOT_FOUND' });
@@ -159,7 +179,16 @@ router.put('/:id/documents/*docPath', loadApp, asyncHandler(async (req, res) =>
const app = req.loadedApp;
await requireRepoPath(app);
- const { filename, resolved } = resolveDocumentPath(app, req.params.docPath);
+ const { filename, resolved } = await resolveDocumentPath(app, req.params.docPath);
+
+ // Git staging rejects a substring `..` and shell metacharacters, which
+ // `isSafeFilename` allows (`docs/notes..md` is a legal filename). Refuse the
+ // write up front rather than mutating the file and then 500-ing on the commit.
+ if (!isGitStageableFilePath(filename)) {
+ throw new ServerError('Document name cannot be committed by git', {
+ status: 400, code: 'INVALID_DOCUMENT'
+ });
+ }
const { content, commitMessage } = documentUpdateSchema.parse(req.body);
const created = !await pathExists(resolved);
diff --git a/server/routes/apps/documents.test.js b/server/routes/apps/documents.test.js
index 3c3e3a7980..9b2eaaa078 100644
--- a/server/routes/apps/documents.test.js
+++ b/server/routes/apps/documents.test.js
@@ -8,10 +8,11 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import express from 'express';
-import { mkdtemp, mkdir, writeFile, rm, readFile } from 'fs/promises';
+import { mkdtemp, mkdir, writeFile, rm, readFile, symlink } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
import { request } from '../../lib/testHelper.js';
+import { pathExists } from './shared.js';
vi.mock('../../services/apps.js', () => ({ getAppById: vi.fn() }));
vi.mock('../../services/git.js', () => ({
@@ -131,4 +132,51 @@ describe('Apps Document Routes', () => {
expect(res.status).toBe(400);
expect(git.stageFiles).not.toHaveBeenCalled();
});
+
+ it('refuses to read or write through a symlinked directory that escapes the repo', async () => {
+ // The lexical containment check passes for `docs/escape/...` — only
+ // canonicalizing the path catches that the directory points outside.
+ const outside = await mkdtemp(join(tmpdir(), 'portos-outside-'));
+ await writeFile(join(outside, 'secret.md'), '# Secret');
+ await symlink(outside, join(repoPath, 'docs', 'escape'), 'dir');
+
+ const read = await request(app).get('/api/apps/app-1/documents/docs/escape/secret.md');
+ expect(read.status).toBe(400);
+ expect(read.body.code).toBe('PATH_TRAVERSAL');
+
+ const write = await request(app)
+ .put('/api/apps/app-1/documents/docs/escape/secret.md')
+ .send({ content: 'pwned' });
+ expect(write.status).toBe(400);
+ expect(await readFile(join(outside, 'secret.md'), 'utf-8')).toBe('# Secret');
+
+ await rm(outside, { recursive: true, force: true });
+ });
+
+ it('refuses to read a symlinked FILE that escapes the repo', async () => {
+ const outside = await mkdtemp(join(tmpdir(), 'portos-outside-'));
+ await writeFile(join(outside, 'secret.md'), '# Secret');
+ await symlink(join(outside, 'secret.md'), join(repoPath, 'docs', 'leak.md'));
+
+ const res = await request(app).get('/api/apps/app-1/documents/docs/leak.md');
+
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('PATH_TRAVERSAL');
+
+ await rm(outside, { recursive: true, force: true });
+ });
+
+ it('refuses a write git could never stage, before touching the file', async () => {
+ // `notes..md` is a legal filename that `isSafeFilename` accepts, but git
+ // staging rejects a substring `..` — writing first would leave a mutated
+ // tree behind a 500 from stageFiles.
+ const res = await request(app)
+ .put('/api/apps/app-1/documents/docs/notes..md')
+ .send({ content: '# Notes' });
+
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('INVALID_DOCUMENT');
+ expect(git.stageFiles).not.toHaveBeenCalled();
+ expect(await pathExists(join(repoPath, 'docs', 'notes..md'))).toBe(false);
+ });
});