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

refactor: consolidate filename/MIME/formatter helpers and adopt atomic doc writes

[._.]/ Adam Eivybef21c86c83c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 2a0a462259..7c4c4dfcc4 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -20,6 +20,7 @@
- **Workspace-root validation on git/scaffold routes** — git operations and app scaffolding refuse paths outside allowed workspace roots; file staging uses literal pathspecs (no git glob expansion); `env` removed from the shell command allowlist so process secrets can't land in persisted job output.
- **Route validation + linkable tabs** — jira, loops, CoS, digital-twin, automation-schedule, and history inputs are now Zod-validated; Prompt Manager and Messages triage tabs live in the URL (deep-linkable); previously-swallowed client errors are logged.
+- **Helper consolidation** — filename sanitization and MIME maps unified in fileUtils (was 3 copies); GSD/app document saves use atomic writes; client components use the canonical formatters and shared command API instead of local re-implementations.
- **A watched TUI run no longer false-times-out after finishing its work** — companion fix to *Live TUI runs are now viewable AND drivable in the Shell page* (above). One-shot AI runs that drive a terminal UI (Claude Code, Codex, etc.) write their completed answer to a response file and then return to an interactive prompt **without exiting**. The runner only auto-completed such a run via output-idle — which is paused while you watch it in the Shell page (so it isn't snapped shut mid-read). With the process never exiting and idle paused, a watched run had no terminus but the 10-minute hard timeout — at which point it was marked **failed**, its already-written result was **discarded**, and a useless fallback retry ran in its place. The runner now watches for the response file as the model's authoritative "done" signal and completes the run the moment it's written — even while you're watching — since once the file exists the task is genuinely finished. A second safety net salvages the file on hard timeout: if the result was written but completion stalled for any other reason, the run finishes as **success** with that result instead of throwing it away and falling back. So a long editorial pass you keep open in the Shell tab now lands its findings when the model finishes, instead of silently dying at 10 minutes. (`server/lib/tuiPromptRunner.js`)
diff --git a/client/src/components/BackupWidget.jsx b/client/src/components/BackupWidget.jsx
index 7a3b438b8c..1e139557d0 100644
--- a/client/src/components/BackupWidget.jsx
+++ b/client/src/components/BackupWidget.jsx
@@ -16,6 +16,7 @@ import * as api from '../services/api';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
import { useTimeTick } from '../hooks/useTimeTick';
import { equalByKeys, equalListByKeys } from '../lib/compareHelpers';
+import { timeAgo, timeUntil } from '../utils/formatters';
// ---------------------------------------------------------------------------
// Pure helpers
@@ -34,25 +35,6 @@ function computeHealth(status) {
return 'critical';
}
-function relativeTime(isoString) {
- if (!isoString) return null;
- const diffMs = Date.now() - new Date(isoString).getTime();
- const future = diffMs < 0;
- const abs = Math.abs(diffMs);
- const minutes = Math.floor(abs / 60000);
- const hours = Math.floor(minutes / 60);
- const days = Math.floor(hours / 24);
-
- let label;
- if (minutes < 2) label = 'just now';
- else if (minutes < 60) label = `${minutes} min`;
- else if (hours < 24) label = `${hours} hour${hours !== 1 ? 's' : ''}`;
- else label = `${days} day${days !== 1 ? 's' : ''}`;
-
- if (label === 'just now') return label;
- return future ? `in ${label}` : `${label} ago`;
-}
-
const HEALTH_STYLES = {
healthy: {
dot: 'bg-port-success',
@@ -351,7 +333,7 @@ const BackupWidget = memo(function BackupWidget() {
<span className="text-xs text-gray-500">Last backup</span>
</div>
<div className="text-sm font-semibold text-white truncate">
- {status?.lastRun ? relativeTime(status.lastRun) : '—'}
+ {status?.lastRun ? timeAgo(status.lastRun) : '—'}
</div>
{status?.filesChanged != null && (
<div className="text-xs text-gray-600">{status.filesChanged} files changed</div>
@@ -363,7 +345,7 @@ const BackupWidget = memo(function BackupWidget() {
<span className="text-xs text-gray-500">Next backup</span>
</div>
<div className="text-sm font-semibold text-white truncate">
- {status?.nextRun ? relativeTime(status.nextRun) : '—'}
+ {status?.nextRun ? timeUntil(status.nextRun) : '—'}
</div>
{status?.destPath && (
<div className="text-xs text-gray-600 truncate" title={status.destPath}>
diff --git a/client/src/components/CosDashboardWidget.jsx b/client/src/components/CosDashboardWidget.jsx
index cd07fb12b8..fe374fd29d 100644
--- a/client/src/components/CosDashboardWidget.jsx
+++ b/client/src/components/CosDashboardWidget.jsx
@@ -17,7 +17,7 @@ import {
import * as api from '../services/api';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
import { useTimeTick } from '../hooks/useTimeTick';
-import { timeAgo } from '../utils/formatters';
+import { timeAgo, formatDateWeekday } from '../utils/formatters';
/**
* CosDashboardWidget - Compact CoS status widget for the main Dashboard
@@ -394,11 +394,6 @@ function ActivityCalendar({ data }) {
}
};
- const formatDate = (dateStr) => {
- const date = new Date(dateStr + 'T12:00:00');
- return date.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' });
- };
-
return (
<div className="mt-4 pt-4 border-t border-port-border">
<div className="flex items-center justify-between mb-2">
@@ -436,7 +431,7 @@ function ActivityCalendar({ data }) {
${day.isToday ? 'ring-1 ring-port-accent' : ''}
${day.isFuture ? 'opacity-30' : ''}
`}
- title={day.isFuture ? '' : `${formatDate(day.date)}: ${day.tasks} task${day.tasks !== 1 ? 's' : ''} (${day.successRate}% success)`}
+ title={day.isFuture ? '' : `${formatDateWeekday(day.date)}: ${day.tasks} task${day.tasks !== 1 ? 's' : ''} (${day.successRate}% success)`}
/>
))}
</div>
diff --git a/client/src/components/apps/tabs/ProcessesTab.jsx b/client/src/components/apps/tabs/ProcessesTab.jsx
index ec72c8193a..db8e995d79 100644
--- a/client/src/components/apps/tabs/ProcessesTab.jsx
+++ b/client/src/components/apps/tabs/ProcessesTab.jsx
@@ -1,6 +1,7 @@
import { useState, useEffect, useRef, Fragment } from 'react';
import { Maximize2, X } from 'lucide-react';
import * as api from '../../../services/api';
+import { executeCommand } from '../../../services/api';
import socket from '../../../services/socket';
import BrailleSpinner from '../../BrailleSpinner';
import { useAutoRefetch } from '../../../hooks/useAutoRefetch';
@@ -95,39 +96,9 @@ export default function ProcessesTab({ pm2ProcessNames, filterFn }) {
};
}, [expandedProcess, tailLines]);
- const handleRestart = async (name) => {
+ const pm2Action = async (action, name) => {
setRestarting(prev => ({ ...prev, [name]: true }));
- await fetch('/api/commands/execute', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ command: `pm2 restart ${name}` })
- }).catch(() => null);
- setTimeout(() => {
- setRestarting(prev => ({ ...prev, [name]: false }));
- refetch();
- }, 2000);
- };
-
- const handleStop = async (name) => {
- setRestarting(prev => ({ ...prev, [name]: true }));
- await fetch('/api/commands/execute', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ command: `pm2 stop ${name}` })
- }).catch(() => null);
- setTimeout(() => {
- setRestarting(prev => ({ ...prev, [name]: false }));
- refetch();
- }, 2000);
- };
-
- const handleStart = async (name) => {
- setRestarting(prev => ({ ...prev, [name]: true }));
- await fetch('/api/commands/execute', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ command: `pm2 start ${name}` })
- }).catch(() => null);
+ await executeCommand(`pm2 ${action} ${name}`, undefined).catch(() => null);
setTimeout(() => {
setRestarting(prev => ({ ...prev, [name]: false }));
refetch();
@@ -210,14 +181,14 @@ export default function ProcessesTab({ pm2ProcessNames, filterFn }) {
{proc.status === 'online' ? (
<>
<button
- onClick={() => handleRestart(proc.name)}
+ onClick={() => pm2Action('restart', proc.name)}
disabled={restarting[proc.name]}
className="px-2 py-1 text-xs bg-port-warning/20 text-port-warning hover:bg-port-warning/30 rounded disabled:opacity-50"
>
{restarting[proc.name] ? '...' : 'Restart'}
</button>
<button
- onClick={() => handleStop(proc.name)}
+ onClick={() => pm2Action('stop', proc.name)}
disabled={restarting[proc.name]}
className="px-2 py-1 text-xs bg-port-error/20 text-port-error hover:bg-port-error/30 rounded disabled:opacity-50"
>
@@ -226,7 +197,7 @@ export default function ProcessesTab({ pm2ProcessNames, filterFn }) {
</>
) : (
<button
- onClick={() => handleStart(proc.name)}
+ onClick={() => pm2Action('start', proc.name)}
disabled={restarting[proc.name]}
className="px-2 py-1 text-xs bg-port-success/20 text-port-success hover:bg-port-success/30 rounded disabled:opacity-50"
>
diff --git a/client/src/components/brain/tabs/ImportTab.jsx b/client/src/components/brain/tabs/ImportTab.jsx
index 31927c3abc..816ea94950 100644
--- a/client/src/components/brain/tabs/ImportTab.jsx
+++ b/client/src/components/brain/tabs/ImportTab.jsx
@@ -15,6 +15,7 @@ import toast from '../../ui/Toast';
import Banner from '../../ui/Banner';
import BrailleSpinner from '../../BrailleSpinner';
import { formatBytes, formatDateShort } from '../../../utils/formatters';
+import { ATTACHMENT_MAX_FILE_SIZE } from '../../../utils/fileUpload';
// Sources we plan to support. Only `available` ones are clickable.
const SOURCES = [
@@ -146,7 +147,7 @@ function ChatGPTWizard({ onExit, navigate }) {
setError('Please select the conversations.json file from your ChatGPT export.');
return;
}
- if (file.size > 50 * 1024 * 1024) {
+ if (file.size > ATTACHMENT_MAX_FILE_SIZE) {
setError(`File is ${formatBytes(file.size)}, larger than the 50 MB upload limit. See instructions for splitting the file.`);
return;
}
diff --git a/client/src/components/cos/tabs/LearningTab.jsx b/client/src/components/cos/tabs/LearningTab.jsx
index d645e01f03..15cc9c3f6c 100644
--- a/client/src/components/cos/tabs/LearningTab.jsx
+++ b/client/src/components/cos/tabs/LearningTab.jsx
@@ -28,6 +28,7 @@ import {
import toast from '../../ui/Toast';
import * as api from '../../../services/api';
import BrailleSpinner from '../../BrailleSpinner';
+import { formatDurationMin } from '../../../utils/formatters';
export default function LearningTab() {
const [learning, setLearning] = useState(null);
@@ -146,15 +147,6 @@ export default function LearningTab() {
return 'bg-port-error';
}, []);
- const formatDuration = useCallback((ms) => {
- if (!ms) return '—';
- const minutes = Math.round(ms / 60000);
- if (minutes < 60) return `${minutes}m`;
- const hours = Math.floor(minutes / 60);
- const mins = minutes % 60;
- return `${hours}h ${mins}m`;
- }, []);
-
// Memoize sorted durations to avoid re-sorting on each render
const sortedDurations = useMemo(() => {
if (!durations) return [];
@@ -613,10 +605,10 @@ export default function LearningTab() {
<tr key={idx} className="border-t border-port-border">
<td className="p-3 text-gray-300 truncate max-w-[200px]">{taskType}</td>
<td className="p-3 text-right text-gray-500 font-mono">
- {formatDuration(data.avgDurationMs)}
+ {data.avgDurationMs ? formatDurationMin(Math.round(data.avgDurationMs / 60000)) || '—' : '—'}
</td>
<td className="p-3 text-right text-cyan-400 font-mono" title="P80 estimate used for progress bars and ETAs">
- {formatDuration(data.p80DurationMs || data.avgDurationMs)}
+ {(data.p80DurationMs || data.avgDurationMs) ? formatDurationMin(Math.round((data.p80DurationMs || data.avgDurationMs) / 60000)) || '—' : '—'}
</td>
<td className="p-3 text-right text-gray-500 hidden sm:table-cell">
{data.completed}
diff --git a/client/src/components/meatspace/tabs/GenomeTab.jsx b/client/src/components/meatspace/tabs/GenomeTab.jsx
index 7b865eaff3..717a6435f8 100644
--- a/client/src/components/meatspace/tabs/GenomeTab.jsx
+++ b/client/src/components/meatspace/tabs/GenomeTab.jsx
@@ -55,6 +55,7 @@ async function parseZipText(arrayBuffer, ext = '.txt') {
throw new Error(`No ${ext} file found inside the zip`);
}
import * as api from '../../../services/api';
+import { ATTACHMENT_MAX_FILE_SIZE } from '../../../utils/fileUpload';
import GenomeCategoryCard from '../GenomeCategoryCard';
import EpigeneticTracker from '../EpigeneticTracker';
import ProvenanceChip from '../../ui/ProvenanceChip';
@@ -191,7 +192,7 @@ export default function GenomeTab() {
const handleFileUpload = useCallback(async (file) => {
if (!file) return;
- if (file.size > 50 * 1024 * 1024) {
+ if (file.size > ATTACHMENT_MAX_FILE_SIZE) {
toast.error('File too large (max 50MB)');
return;
}
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index 0424345b60..035e53155d 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -21,7 +21,7 @@ import {
import PeerAppsList from '../components/instances/PeerAppsList';
import PeerAgentsSection from '../components/instances/PeerAgentsSection';
import { SchemaGapBadge } from '../components/instances/SchemaGapBadge';
-import { timeAgo } from '../utils/formatters';
+import { timeAgo, timeUntil } from '../utils/formatters';
import { useLocalStorageBool } from '../hooks/useLocalStorageBool';
import { directionalCounts, describeDirectional } from '../lib/syncCounts';
@@ -37,19 +37,6 @@ const STATUS_ICONS = {
unknown: CircleDot
};
-function timeUntil(iso) {
- if (!iso) return null;
- const diff = new Date(iso).getTime() - Date.now();
- if (diff <= 0) return 'now';
- const secs = Math.floor(diff / 1000);
- if (secs < 60) return `in ${secs}s`;
- const mins = Math.floor(secs / 60);
- if (mins < 60) return `in ${mins}m`;
- const hrs = Math.floor(mins / 60);
- if (hrs < 24) return `in ${hrs}h`;
- return `in ${Math.floor(hrs / 24)}d`;
-}
-
function HealthSummary({ health, version }) {
if (!health) return <span className="text-gray-500 text-xs">No data</span>;
return (
diff --git a/client/src/pages/ProcessesPage.jsx b/client/src/pages/ProcessesPage.jsx
index a74d9ac4d9..00ad918b9c 100644
--- a/client/src/pages/ProcessesPage.jsx
+++ b/client/src/pages/ProcessesPage.jsx
@@ -3,6 +3,7 @@ import { Save } from 'lucide-react';
import ProcessesTab from '../components/apps/tabs/ProcessesTab';
import toast from '../components/ui/Toast';
import * as api from '../services/api';
+import { executeCommand } from '../services/api';
export function ProcessesPage() {
const [managedProcessNames, setManagedProcessNames] = useState(new Set());
@@ -27,16 +28,12 @@ export function ProcessesPage() {
const handlePm2Save = async () => {
setSaving(true);
- // /api/commands/execute returns 202 { commandId, status: 'started' } and
- // runs asynchronously — treat a returned commandId as a successful queue.
- const res = await fetch('/api/commands/execute', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ command: 'pm2 save' })
- }).catch(() => null);
- const body = res ? await res.json().catch(() => null) : null;
+ // executeCommand returns { commandId, status: 'started' } on success.
+ // silent: true — this handler owns the error UI (toast.error below);
+ // without it the request() helper would also toast, double-toasting.
+ const result = await executeCommand('pm2 save', undefined, { silent: true }).catch(() => null);
setSaving(false);
- if (res?.ok && body?.commandId) {
+ if (result?.commandId) {
toast.success('PM2 save queued');
} else {
toast.error('Failed to save PM2 process list');
diff --git a/client/src/pages/RunsHistoryPage.jsx b/client/src/pages/RunsHistoryPage.jsx
index abbd479c15..b4050e1f12 100644
--- a/client/src/pages/RunsHistoryPage.jsx
+++ b/client/src/pages/RunsHistoryPage.jsx
@@ -2,7 +2,7 @@ import { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { Trash2, RotateCcw, MessageSquarePlus } from 'lucide-react';
import * as api from '../services/api';
-import { formatTime, formatRuntime } from '../utils/formatters';
+import { formatTime, formatRuntime, formatBytes } from '../utils/formatters';
import BrailleSpinner from '../components/BrailleSpinner';
import Banner from '../components/ui/Banner';
import { writeClipboardSilently } from '../lib/clipboard';
@@ -347,7 +347,7 @@ export function RunsHistoryPage() {
{run.outputSize && (
<div>
<div className="text-xs text-gray-500 uppercase tracking-wide mb-1">Output Size</div>
- <div className="text-gray-300 font-mono">{(run.outputSize / 1024).toFixed(1)} KB</div>
+ <div className="text-gray-300 font-mono">{formatBytes(run.outputSize)}</div>
</div>
)}
</div>
diff --git a/client/src/services/apiCommands.js b/client/src/services/apiCommands.js
index 65b8bfb4ff..9af408318e 100644
--- a/client/src/services/apiCommands.js
+++ b/client/src/services/apiCommands.js
@@ -1,9 +1,10 @@
import { request } from './apiCore.js';
// Commands
-export const executeCommand = (command, workspacePath) => request('/commands/execute', {
+export const executeCommand = (command, workspacePath, options = {}) => request('/commands/execute', {
method: 'POST',
- body: JSON.stringify({ command, workspacePath })
+ body: JSON.stringify({ command, workspacePath }),
+ ...options
});
export const stopCommand = (id) => request(`/commands/${id}/stop`, { method: 'POST' });
export const getAllowedCommands = () => request('/commands/allowed');
diff --git a/client/src/utils/fileUpload.js b/client/src/utils/fileUpload.js
index 766d20f9ac..bda5aaf2c8 100644
--- a/client/src/utils/fileUpload.js
+++ b/client/src/utils/fileUpload.js
@@ -129,7 +129,7 @@ export async function uploadScreenshotFile(file, options = {}) {
}
// Max file size for attachments: 50MB
-const ATTACHMENT_MAX_FILE_SIZE = 50 * 1024 * 1024;
+export const ATTACHMENT_MAX_FILE_SIZE = 50 * 1024 * 1024;
/**
* Check if a file extension is allowed for attachments
diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.js
index 0ee66b417b..d14d3e9e8b 100644
--- a/client/src/utils/formatters.js
+++ b/client/src/utils/formatters.js
@@ -95,6 +95,32 @@ export function timeAgo(dateStr, fallback = 'never') {
return `${Math.floor(days / 365)}y ago`;
}
+/**
+ * Format a future timestamp as a relative "in X" string, mirroring timeAgo's
+ * bucket thresholds. Returns `fallback` for null/missing or past dates (use
+ * timeAgo for past-relative display). Example outputs: "in 5s", "in 3m",
+ * "in 2h", "in 4d".
+ * @param {string|Date|null} dateStr - ISO timestamp or Date object
+ * @param {string} fallback - Text to show for null/missing/past dates (default: 'now')
+ * @returns {string} Future-relative time string
+ */
+export function timeUntil(dateStr, fallback = 'now') {
+ if (!dateStr) return fallback;
+ const time = new Date(dateStr).getTime();
+ if (!Number.isFinite(time)) return fallback;
+ const seconds = Math.floor((time - Date.now()) / 1000);
+ if (seconds <= 0) return fallback;
+ if (seconds < 60) return `in ${seconds}s`;
+ const mins = Math.floor(seconds / 60);
+ if (mins < 60) return `in ${mins}m`;
+ const hrs = Math.floor(mins / 60);
+ if (hrs < 24) return `in ${hrs}h`;
+ const days = Math.floor(hrs / 24);
+ if (days < 30) return `in ${days}d`;
+ if (days < 365) return `in ${Math.floor(days / 30)}mo`;
+ return `in ${Math.floor(days / 365)}y`;
+}
+
/**
* Format bytes as a human-readable string
* @param {number} bytes - Size in bytes
@@ -313,6 +339,21 @@ export function formatEventDateTime(dateStr, options = {}) {
return date.toLocaleString([], { weekday: 'short', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
}
+/**
+ * Format a date string as a short weekday + month + day string
+ * (e.g., "Sat, Mar 5"). Used for activity-heatmap tooltips where compact
+ * output with a leading weekday abbreviation is important.
+ * The input is treated as a calendar date (anchored at local noon to avoid
+ * day-boundary drift), not as a precise timestamp.
+ * @param {string} dateStr - Date-only string ("YYYY-MM-DD"); a full ISO
+ * timestamp is NOT supported (the noon-anchor suffix would make it invalid)
+ * @returns {string} Formatted date (e.g., "Sat, Mar 5")
+ */
+export function formatDateWeekday(dateStr) {
+ const date = new Date(dateStr + 'T12:00:00');
+ return date.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' });
+}
+
/**
* Get app name from app ID by looking up in apps array
* @param {string|null} appId - The app ID to look up
diff --git a/server/lib/aiToolkit/internal/atomicWrite.js b/server/lib/aiToolkit/internal/atomicWrite.js
index 5e45b59bbc..f461742ce7 100644
--- a/server/lib/aiToolkit/internal/atomicWrite.js
+++ b/server/lib/aiToolkit/internal/atomicWrite.js
@@ -1,11 +1,19 @@
/**
* Atomic file write helper for the aiToolkit.
*
- * Duplicated from server/lib/fileUtils.js so the toolkit stays self-contained
- * (no imports out to sibling PortOS modules). Keep in sync with upstream.
+ * Vendored copy of server/lib/fileUtils.js#atomicWrite so the toolkit stays
+ * self-contained (no imports out to sibling PortOS modules — see CLAUDE.md
+ * "AI Toolkit" section). Keep in sync with the upstream implementation:
+ *
+ * PARITY REQUIREMENT: every change to server/lib/fileUtils.js#atomicWrite
+ * must be mirrored here and vice-versa. The critical invariant is the
+ * payload-coercion line: Buffer must pass through unchanged (JSON.stringify
+ * on a Buffer produces `{"type":"Buffer","data":[...]}`, corrupting binary
+ * writes). String and Buffer both bypass stringify; everything else is
+ * serialised with 2-space indentation.
*
* Writes data to a temp file, then renames atomically so readers never see
- * a partial write. Accepts a string or any JSON-serializable value.
+ * a partial write. Accepts a string, a Buffer, or any JSON-serializable value.
*/
import { mkdir, writeFile, rename, unlink } from 'fs/promises';
@@ -17,7 +25,9 @@ export async function ensureDir(dir) {
}
export async function atomicWrite(filePath, data) {
- const payload = typeof data === 'string' ? data : JSON.stringify(data, null, 2);
+ // Buffer must pass through unchanged — JSON.stringify on a Buffer produces
+ // `{"type":"Buffer","data":[...]}` which corrupts binary writes (PNG, etc.).
+ const payload = typeof data === 'string' || Buffer.isBuffer(data) ? data : JSON.stringify(data, null, 2);
await ensureDir(dirname(filePath));
const tmp = `${filePath}.${process.pid}.${Date.now()}.${randomUUID()}.tmp`;
await writeFile(tmp, payload);
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index 242c990b30..7f0a91017a 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -665,6 +665,132 @@ export function formatBytes(bytes) {
return (bytes / Math.pow(1024, i)).toFixed(i > 1 ? 1 : 0) + ' ' + units[i];
}
+// =============================================================================
+// FILENAME / MIME HELPERS (shared by uploads, attachments, screenshots routes)
+// =============================================================================
+
+/**
+ * Full extension→MIME map covering documents, images, audio, video, code, and
+ * archives accepted by the generic uploads route. The attachments route uses a
+ * strict subset — see ATTACHMENT_ALLOWED_EXTENSIONS below.
+ *
+ * Exported so routes can serve the correct Content-Type header without keeping
+ * their own copy. Unknown extensions fall back to 'application/octet-stream'.
+ */
+export const EXTENSION_MIME_MAP = {
+ // Documents
+ '.txt': 'text/plain',
+ '.md': 'text/markdown',
+ '.json': 'application/json',
+ '.csv': 'text/csv',
+ '.xml': 'application/xml',
+ '.yaml': 'application/x-yaml',
+ '.yml': 'application/x-yaml',
+ '.pdf': 'application/pdf',
+ // Images
+ '.png': 'image/png',
+ '.jpg': 'image/jpeg',
+ '.jpeg': 'image/jpeg',
+ '.gif': 'image/gif',
+ '.webp': 'image/webp',
+ '.svg': 'image/svg+xml',
+ '.ico': 'image/x-icon',
+ '.bmp': 'image/bmp',
+ // Audio
+ '.mp3': 'audio/mpeg',
+ '.wav': 'audio/wav',
+ '.ogg': 'audio/ogg',
+ '.m4a': 'audio/mp4',
+ // Video
+ '.mp4': 'video/mp4',
+ '.webm': 'video/webm',
+ '.mov': 'video/quicktime',
+ // Code
+ '.js': 'text/javascript',
+ '.ts': 'text/typescript',
+ '.jsx': 'text/javascript',
+ '.tsx': 'text/typescript',
+ '.py': 'text/x-python',
+ '.sh': 'text/x-shellscript',
+ '.sql': 'text/x-sql',
+ '.html': 'text/html',
+ '.css': 'text/css',
+ '.go': 'text/x-go',
+ '.rs': 'text/x-rust',
+ '.java': 'text/x-java',
+ '.c': 'text/x-c',
+ '.cpp': 'text/x-c++',
+ '.h': 'text/x-c',
+ // Archives
+ '.zip': 'application/zip',
+ '.tar': 'application/x-tar',
+ '.gz': 'application/gzip',
+ '.7z': 'application/x-7z-compressed',
+ '.rar': 'application/vnd.rar',
+ // Other
+ '.log': 'text/plain',
+ '.env': 'text/plain',
+ '.conf': 'text/plain',
+ '.cfg': 'text/plain',
+ '.ini': 'text/plain',
+};
+
+/**
+ * Strict allowlist for file attachments (task attachments, CoS context files).
+ * A subset of EXTENSION_MIME_MAP — excludes audio, video, ICO, BMP, and
+ * miscellaneous text/config types that are not meaningful attachment types.
+ * The attachments route validates against this set; uploads uses the full map.
+ */
+export const ATTACHMENT_ALLOWED_EXTENSIONS = new Set([
+ '.txt', '.md', '.json', '.csv', '.xml', '.yaml', '.yml',
+ '.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg', '.pdf',
+ '.js', '.ts', '.jsx', '.tsx', '.py', '.sh', '.sql', '.html', '.css',
+ '.zip', '.tar', '.gz',
+]);
+
+/**
+ * Look up the MIME type for a file extension (including the leading dot, e.g.
+ * ".png"). Returns 'application/octet-stream' for unknown extensions.
+ *
+ * @param {string} ext - Lowercased extension with leading dot (e.g. '.png')
+ * @returns {string} MIME type string
+ */
+export function getMimeType(ext) {
+ return EXTENSION_MIME_MAP[ext] || 'application/octet-stream';
+}
+
+/**
+ * Get a file's extension, normalised to lowercase with a leading dot.
+ * Returns null when the filename has no extension.
+ *
+ * @param {string} filename
+ * @returns {string|null}
+ */
+export function getFileExtension(filename) {
+ return extname(filename).toLowerCase() || null;
+}
+
+/**
+ * Sanitize a user-supplied filename to prevent path traversal and filesystem
+ * surprises. Strips any directory component, replaces characters that are not
+ * alphanumeric / dot / hyphen / underscore with `_`, and ensures the name
+ * does not start with a dot (hidden-file prevention).
+ *
+ * Identical logic was copy-pasted across uploads.js, attachments.js, and
+ * screenshots.js — consolidated here so fixes propagate to all callers.
+ *
+ * @param {string} filename - User-provided filename (possibly with path components)
+ * @returns {string} Safe basename
+ */
+export function sanitizeFilename(filename) {
+ const base = basename(filename);
+ const sanitized = base.replace(/[^a-zA-Z0-9._-]/g, '_');
+ if (sanitized.startsWith('.')) {
+ return '_' + sanitized.slice(1);
+ }
+ return sanitized;
+}
+
/**
* Validate a user-supplied filename is a safe basename with one of the
* allowed extensions — refuses path-traversal, null bytes, separators, and
diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.js
index 226cab90bc..cc74ecd384 100644
--- a/server/lib/fileUtils.test.js
+++ b/server/lib/fileUtils.test.js
@@ -30,6 +30,11 @@ import {
sha256File,
resolveImageInputPath,
PATHS,
+ sanitizeFilename,
+ getFileExtension,
+ getMimeType,
+ EXTENSION_MIME_MAP,
+ ATTACHMENT_ALLOWED_EXTENSIONS,
} from './fileUtils.js';
import { copyFileSync, existsSync, mkdirSync } from 'fs';
import { dirname } from 'path';
@@ -786,3 +791,105 @@ describe('fileUtils', () => {
});
});
});
+
+// =============================================================================
+// sanitizeFilename / getFileExtension / getMimeType / allowlists (#1140)
+// =============================================================================
+
+describe('sanitizeFilename', () => {
+ it('returns a safe basename for a normal filename', () => {
+ expect(sanitizeFilename('hello.txt')).toBe('hello.txt');
+ });
+
+ it('strips directory components', () => {
+ expect(sanitizeFilename('/etc/passwd')).toBe('passwd');
+ expect(sanitizeFilename('../../etc/passwd')).toBe('passwd');
+ });
+
+ it('replaces special characters with underscores', () => {
+ expect(sanitizeFilename('hello world!.txt')).toBe('hello_world_.txt');
+ expect(sanitizeFilename('file with spaces.js')).toBe('file_with_spaces.js');
+ expect(sanitizeFilename('résumé.pdf')).toBe('r_sum_.pdf');
+ });
+
+ it('prevents hidden files by replacing a leading dot', () => {
+ expect(sanitizeFilename('.bashrc')).toBe('_bashrc');
+ expect(sanitizeFilename('.hidden.txt')).toBe('_hidden.txt');
+ });
+
+ it('leaves dots in the middle alone (extension dots)', () => {
+ expect(sanitizeFilename('my.file.name.txt')).toBe('my.file.name.txt');
+ });
+
+ it('handles an empty string gracefully', () => {
+ expect(sanitizeFilename('')).toBe('');
+ });
+});
+
+describe('getFileExtension', () => {
+ it('returns the lowercased extension with leading dot', () => {
+ expect(getFileExtension('photo.PNG')).toBe('.png');
+ expect(getFileExtension('archive.tar.gz')).toBe('.gz');
+ });
+
+ it('returns null for a filename without an extension', () => {
+ expect(getFileExtension('Makefile')).toBeNull();
+ expect(getFileExtension('no-ext')).toBeNull();
+ });
+
+ it('normalises uppercase extensions', () => {
+ expect(getFileExtension('IMAGE.JPEG')).toBe('.jpeg');
+ });
+});
+
+describe('getMimeType', () => {
+ it('returns the correct MIME type for known extensions', () => {
+ expect(getMimeType('.png')).toBe('image/png');
+ expect(getMimeType('.pdf')).toBe('application/pdf');
+ expect(getMimeType('.mp3')).toBe('audio/mpeg');
+ expect(getMimeType('.zip')).toBe('application/zip');
+ expect(getMimeType('.json')).toBe('application/json');
+ });
+
+ it('falls back to application/octet-stream for unknown extensions', () => {
+ expect(getMimeType('.xyz')).toBe('application/octet-stream');
+ expect(getMimeType('.unknown')).toBe('application/octet-stream');
+ expect(getMimeType(null)).toBe('application/octet-stream');
+ });
+
+ it('all entries in EXTENSION_MIME_MAP are reachable through getMimeType', () => {
+ for (const [ext, mime] of Object.entries(EXTENSION_MIME_MAP)) {
+ expect(getMimeType(ext)).toBe(mime);
+ }
+ });
+});
+
+describe('ATTACHMENT_ALLOWED_EXTENSIONS', () => {
+ it('is a Set', () => {
+ expect(ATTACHMENT_ALLOWED_EXTENSIONS).toBeInstanceOf(Set);
+ });
+
+ it('allows common document types', () => {
+ expect(ATTACHMENT_ALLOWED_EXTENSIONS.has('.pdf')).toBe(true);
+ expect(ATTACHMENT_ALLOWED_EXTENSIONS.has('.md')).toBe(true);
+ expect(ATTACHMENT_ALLOWED_EXTENSIONS.has('.json')).toBe(true);
+ });
+
+ it('allows image types', () => {
+ expect(ATTACHMENT_ALLOWED_EXTENSIONS.has('.png')).toBe(true);
+ expect(ATTACHMENT_ALLOWED_EXTENSIONS.has('.jpg')).toBe(true);
+ });
+
+ it('does NOT allow audio/video types (strict attachment subset)', () => {
+ expect(ATTACHMENT_ALLOWED_EXTENSIONS.has('.mp3')).toBe(false);
+ expect(ATTACHMENT_ALLOWED_EXTENSIONS.has('.mp4')).toBe(false);
+ expect(ATTACHMENT_ALLOWED_EXTENSIONS.has('.ico')).toBe(false);
+ expect(ATTACHMENT_ALLOWED_EXTENSIONS.has('.bmp')).toBe(false);
+ });
+
+ it('all extensions in the set are also present in EXTENSION_MIME_MAP', () => {
+ for (const ext of ATTACHMENT_ALLOWED_EXTENSIONS) {
+ expect(EXTENSION_MIME_MAP).toHaveProperty(ext);
+ }
+ });
+});
diff --git a/server/lib/validation.js b/server/lib/validation.js
index fd5b45a88d..63ec67bf73 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -2088,3 +2088,17 @@ export const llmSchema = z.object({
provider: z.string().trim().max(80).nullable().optional(),
model: z.string().trim().max(200).nullable().optional(),
}).optional();
+
+// =============================================================================
+// DOCUMENT EDITING SCHEMAS (shared by apps.js and gsd.js document routes)
+// =============================================================================
+
+/**
+ * Body schema for PUT /api/apps/:id/documents/:filename and
+ * PUT /api/cos/gsd/projects/:appId/documents/:docName.
+ * Both routes accept a content string plus an optional commit message.
+ */
+export const documentUpdateSchema = z.object({
+ content: z.string().max(500000),
+ commitMessage: z.string().max(200).optional()
+});
diff --git a/server/routes/apps.js b/server/routes/apps.js
index c386c25c31..617a46225d 100644
--- a/server/routes/apps.js
+++ b/server/routes/apps.js
@@ -2,7 +2,7 @@ import { Router } from 'express';
import { spawn } from 'child_process';
import { readFile, writeFile, stat, access, mkdir } from 'fs/promises';
import { join, resolve, extname } from 'path';
-import { PATHS, tryReadFile, readJSONFile, safeJSONParse } from '../lib/fileUtils.js';
+import { PATHS, tryReadFile, readJSONFile, safeJSONParse, atomicWrite } from '../lib/fileUtils.js';
import * as appsService from '../services/apps.js';
import { notifyAppsChanged, PORTOS_APP_ID } from '../services/apps.js';
import * as pm2Service from '../services/pm2.js';
@@ -11,7 +11,7 @@ import * as appBuilder from '../services/appBuilder.js';
import * as cos from '../services/cos.js';
import { logAction } from '../services/history.js';
import { z } from 'zod';
-import { validateRequest, appSchema, appUpdateSchema, sanitizeTaskMetadata } from '../lib/validation.js';
+import { validateRequest, appSchema, appUpdateSchema, sanitizeTaskMetadata, documentUpdateSchema } from '../lib/validation.js';
import * as git from '../services/git.js';
import { parseCronToNextRun } from '../services/eventScheduler.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
@@ -274,11 +274,8 @@ router.post('/:id/upgrade-tls', loadApp, asyncHandler(async (req, res) => {
);
}
- const [helperSource] = await Promise.all([
- readFile(sourcePath, 'utf-8'),
- mkdir(targetDir, { recursive: true })
- ]);
- await writeFile(targetPath, helperSource);
+ const helperSource = await readFile(sourcePath, 'utf-8');
+ await atomicWrite(targetPath, helperSource);
await appsService.updateApp(app.id, { tlsPort });
@@ -967,11 +964,6 @@ router.post('/:id/refresh-config', loadApp, asyncHandler(async (req, res) => {
const ALLOWED_DOCUMENTS = ['PLAN.md', 'CLAUDE.md', 'GOALS.md', 'REVIEW.md', 'REJECTED.md'];
-const documentUpdateSchema = z.object({
- content: z.string().max(500000),
- commitMessage: z.string().max(200).optional()
-});
-
// GET /api/apps/:id/documents - List which documents exist
router.get('/:id/documents', loadApp, asyncHandler(async (req, res) => {
const app = req.loadedApp;
@@ -1052,7 +1044,7 @@ router.put('/:id/documents/:filename', loadApp, asyncHandler(async (req, res) =>
const { content, commitMessage } = documentUpdateSchema.parse(req.body);
const created = !await pathExists(resolved);
- await writeFile(resolved, content, 'utf-8');
+ await atomicWrite(resolved, content);
await git.stageFiles(app.repoPath, [filename]);
const status = await git.getStatus(app.repoPath);
diff --git a/server/routes/attachments.js b/server/routes/attachments.js
index ca61b2a54c..4adaeb9647 100644
--- a/server/routes/attachments.js
+++ b/server/routes/attachments.js
@@ -6,10 +6,13 @@
import { Router } from 'express';
import { writeFile, unlink, readdir, stat } from 'fs/promises';
import { existsSync } from 'fs';
-import { join, basename, extname, resolve } from 'path';
+import { join, resolve } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
-import { ensureDir, PATHS, RISKY_MIME_TYPES } from '../lib/fileUtils.js';
+import {
+ ensureDir, PATHS, RISKY_MIME_TYPES,
+ sanitizeFilename, getFileExtension, getMimeType, ATTACHMENT_ALLOWED_EXTENSIONS,
+} from '../lib/fileUtils.js';
const ATTACHMENTS_DIR = PATHS.cosAttachments;
@@ -18,71 +21,13 @@ const router = Router();
// Max file size: 50MB (larger than screenshots to accommodate documents)
const MAX_FILE_SIZE = 50 * 1024 * 1024;
-// Allowed file extensions and their MIME types
-const ALLOWED_EXTENSIONS = {
- // Documents
- '.txt': 'text/plain',
- '.md': 'text/markdown',
- '.json': 'application/json',
- '.csv': 'text/csv',
- '.xml': 'application/xml',
- '.yaml': 'application/x-yaml',
- '.yml': 'application/x-yaml',
- // Images
- '.png': 'image/png',
- '.jpg': 'image/jpeg',
- '.jpeg': 'image/jpeg',
- '.gif': 'image/gif',
- '.webp': 'image/webp',
- '.svg': 'image/svg+xml',
- // Documents
- '.pdf': 'application/pdf',
- // Code
- '.js': 'text/javascript',
- '.ts': 'text/typescript',
- '.jsx': 'text/javascript',
- '.tsx': 'text/typescript',
- '.py': 'text/x-python',
- '.sh': 'text/x-shellscript',
- '.sql': 'text/x-sql',
- '.html': 'text/html',
- '.css': 'text/css',
- // Archives (useful for providing multiple files)
- '.zip': 'application/zip',
- '.tar': 'application/x-tar',
- '.gz': 'application/gzip'
-};
-
-/**
- * Validate and sanitize filename to prevent path traversal
- * @param {string} filename - User-provided filename
- * @returns {string} - Safe filename
- */
-function sanitizeFilename(filename) {
- const base = basename(filename);
- // Replace problematic characters but keep extension dots
- const sanitized = base.replace(/[^a-zA-Z0-9._-]/g, '_');
- // Ensure it doesn't start with a dot (hidden files)
- if (sanitized.startsWith('.')) {
- return '_' + sanitized.slice(1);
- }
- return sanitized;
-}
-
-/**
- * Get file extension, normalized to lowercase with leading dot
- */
-function getExtension(filename) {
- const ext = extname(filename).toLowerCase();
- return ext || null;
-}
-
/**
- * Validate file extension is allowed
+ * Validate file extension is allowed for attachments.
+ * Uses the strict ATTACHMENT_ALLOWED_EXTENSIONS allowlist from fileUtils.
*/
function isAllowedExtension(filename) {
- const ext = getExtension(filename);
- return ext && ALLOWED_EXTENSIONS[ext];
+ const ext = getFileExtension(filename);
+ return ext && ATTACHMENT_ALLOWED_EXTENSIONS.has(ext);
}
// POST /api/attachments - Upload a file attachment (base64)
@@ -99,7 +44,7 @@ router.post('/', asyncHandler(async (req, res) => {
// Validate extension
if (!isAllowedExtension(filename)) {
- const allowedList = Object.keys(ALLOWED_EXTENSIONS).join(', ');
+ const allowedList = [...ATTACHMENT_ALLOWED_EXTENSIONS].join(', ');
throw new ServerError(`File type not allowed. Supported: ${allowedList}`, { status: 400, code: 'INVALID_FILE_TYPE' });
}
@@ -116,7 +61,7 @@ router.post('/', asyncHandler(async (req, res) => {
const id = uuidv4();
const safeName = sanitizeFilename(filename);
- const ext = getExtension(safeName);
+ const ext = getFileExtension(safeName);
// Create unique filename with UUID prefix to avoid collisions
const fname = `${id.slice(0, 8)}-${safeName}`;
const filepath = join(ATTACHMENTS_DIR, fname);
@@ -129,7 +74,7 @@ router.post('/', asyncHandler(async (req, res) => {
await writeFile(filepath, buffer);
- const mimeType = ALLOWED_EXTENSIONS[ext] || 'application/octet-stream';
+ const mimeType = getMimeType(ext);
console.log(`📎 Attachment saved: ${fname} (${buffer.length} bytes, ${mimeType})`);
@@ -159,8 +104,8 @@ router.get('/:filename', asyncHandler(async (req, res) => {
throw new ServerError('Attachment not found', { status: 404, code: 'NOT_FOUND' });
}
- const ext = getExtension(safeFilename);
- const mimeType = ALLOWED_EXTENSIONS[ext] || 'application/octet-stream';
+ const ext = getFileExtension(safeFilename);
+ const mimeType = getMimeType(ext);
res.set('X-Content-Type-Options', 'nosniff');
if (RISKY_MIME_TYPES.has(mimeType)) {
@@ -202,12 +147,12 @@ router.get('/', asyncHandler(async (req, res) => {
const attachments = await Promise.all(files.map(async filename => {
const filepath = join(ATTACHMENTS_DIR, filename);
const stats = await stat(filepath);
- const ext = getExtension(filename);
+ const ext = getFileExtension(filename);
return {
filename,
path: filepath,
size: stats.size,
- mimeType: ALLOWED_EXTENSIONS[ext] || 'application/octet-stream',
+ mimeType: getMimeType(ext),
createdAt: stats.birthtime
};
}));
diff --git a/server/routes/gsd.js b/server/routes/gsd.js
index 0ee3a47a31..eb40f2cc4e 100644
--- a/server/routes/gsd.js
+++ b/server/routes/gsd.js
@@ -8,9 +8,11 @@
import { Router } from 'express'
import { z } from 'zod'
import { existsSync } from 'fs'
-import { readFile, writeFile } from 'fs/promises'
+import { readFile } from 'fs/promises'
import { join, resolve } from 'path'
import { asyncHandler, ServerError } from '../lib/errorHandler.js'
+import { atomicWrite } from '../lib/fileUtils.js'
+import { documentUpdateSchema } from '../lib/validation.js'
import * as gsdService from '../services/gsdService.js'
import { addTask } from '../services/cos.js'
import { getActiveApps } from '../services/apps.js'
@@ -30,11 +32,6 @@ const phaseActionSchema = z.object({
action: z.enum(['plan', 'execute', 'verify'])
})
-const documentUpdateSchema = z.object({
- content: z.string().max(500000),
- commitMessage: z.string().max(200).optional()
-})
-
const GSD_ALLOWED_DOCUMENTS = ['PROJECT.md', 'ROADMAP.md', 'STATE.md', 'CONCERNS.md', 'RETROSPECTIVE.md', 'MILESTONES.md']
const GSD_ACTION_DESCRIPTIONS = {
@@ -200,7 +197,7 @@ router.put('/projects/:appId/documents/:docName', asyncHandler(async (req, res)
const { content, commitMessage } = documentUpdateSchema.parse(req.body)
const created = !existsSync(resolved)
- await writeFile(resolved, content, 'utf-8')
+ await atomicWrite(resolved, content)
const relPath = `.planning/${docName}`
await git.stageFiles(ctx.app.repoPath, [relPath])
diff --git a/server/routes/screenshots.js b/server/routes/screenshots.js
index a20518c780..901423d79d 100644
--- a/server/routes/screenshots.js
+++ b/server/routes/screenshots.js
@@ -1,32 +1,15 @@
import { Router } from 'express';
import { writeFile } from 'fs/promises';
import { existsSync } from 'fs';
-import { join, basename, resolve } from 'path';
+import { join, resolve } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
-import { ensureDir, PATHS } from '../lib/fileUtils.js';
+import { ensureDir, PATHS, sanitizeFilename } from '../lib/fileUtils.js';
const SCREENSHOTS_DIR = PATHS.screenshots;
const router = Router();
-/**
- * Validate and sanitize filename to prevent path traversal
- * @param {string} filename - User-provided filename
- * @returns {string} - Safe filename
- */
-function sanitizeFilename(filename) {
- // Get just the base filename, removing any path components
- const base = basename(filename);
- // Remove any remaining path traversal attempts or special characters
- const sanitized = base.replace(/[^a-zA-Z0-9._-]/g, '_');
- // Ensure it doesn't start with a dot (hidden files)
- if (sanitized.startsWith('.')) {
- return '_' + sanitized.slice(1);
- }
- return sanitized;
-}
-
// Max file size: 10MB
const MAX_FILE_SIZE = 10 * 1024 * 1024;
diff --git a/server/routes/uploads.js b/server/routes/uploads.js
index 28cc04ab75..be644e5179 100644
--- a/server/routes/uploads.js
+++ b/server/routes/uploads.js
@@ -6,10 +6,10 @@
import { Router } from 'express';
import { writeFile, unlink, readdir, stat } from 'fs/promises';
import { existsSync } from 'fs';
-import { join, basename, extname, resolve } from 'path';
+import { join, resolve } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
-import { ensureDir, PATHS, RISKY_MIME_TYPES } from '../lib/fileUtils.js';
+import { ensureDir, PATHS, RISKY_MIME_TYPES, sanitizeFilename, getFileExtension, getMimeType } from '../lib/fileUtils.js';
const UPLOADS_DIR = PATHS.uploads;
@@ -18,89 +18,6 @@ const router = Router();
// Max file size: 100MB for general uploads
const MAX_FILE_SIZE = 100 * 1024 * 1024;
-/**
- * Validate and sanitize filename to prevent path traversal
- */
-function sanitizeFilename(filename) {
- const base = basename(filename);
- const sanitized = base.replace(/[^a-zA-Z0-9._-]/g, '_');
- if (sanitized.startsWith('.')) {
- return '_' + sanitized.slice(1);
- }
- return sanitized;
-}
-
-/**
- * Get file extension, normalized to lowercase with leading dot
- */
-function getExtension(filename) {
- return extname(filename).toLowerCase() || null;
-}
-
-/**
- * Get MIME type from extension
- */
-function getMimeType(ext) {
- const mimeTypes = {
- // Documents
- '.txt': 'text/plain',
- '.md': 'text/markdown',
- '.json': 'application/json',
- '.csv': 'text/csv',
- '.xml': 'application/xml',
- '.yaml': 'application/x-yaml',
- '.yml': 'application/x-yaml',
- '.pdf': 'application/pdf',
- // Images
- '.png': 'image/png',
- '.jpg': 'image/jpeg',
- '.jpeg': 'image/jpeg',
- '.gif': 'image/gif',
- '.webp': 'image/webp',
- '.svg': 'image/svg+xml',
- '.ico': 'image/x-icon',
- '.bmp': 'image/bmp',
- // Audio
- '.mp3': 'audio/mpeg',
- '.wav': 'audio/wav',
- '.ogg': 'audio/ogg',
- '.m4a': 'audio/mp4',
- // Video
- '.mp4': 'video/mp4',
- '.webm': 'video/webm',
- '.mov': 'video/quicktime',
- // Code
- '.js': 'text/javascript',
- '.ts': 'text/typescript',
- '.jsx': 'text/javascript',
- '.tsx': 'text/typescript',
- '.py': 'text/x-python',
- '.sh': 'text/x-shellscript',
- '.sql': 'text/x-sql',
- '.html': 'text/html',
- '.css': 'text/css',
- '.go': 'text/x-go',
- '.rs': 'text/x-rust',
- '.java': 'text/x-java',
- '.c': 'text/x-c',
- '.cpp': 'text/x-c++',
- '.h': 'text/x-c',
- // Archives
- '.zip': 'application/zip',
- '.tar': 'application/x-tar',
- '.gz': 'application/gzip',
- '.7z': 'application/x-7z-compressed',
- '.rar': 'application/vnd.rar',
- // Other
- '.log': 'text/plain',
- '.env': 'text/plain',
- '.conf': 'text/plain',
- '.cfg': 'text/plain',
- '.ini': 'text/plain'
- };
- return mimeTypes[ext] || 'application/octet-stream';
-}
-
/**
* Format file size for display
*/
@@ -136,7 +53,7 @@ router.post('/', asyncHandler(async (req, res) => {
const id = uuidv4();
const safeName = sanitizeFilename(filename);
- const ext = getExtension(safeName);
+ const ext = getFileExtension(safeName);
// Create unique filename with UUID prefix to avoid collisions
const fname = `${id.slice(0, 8)}-${safeName}`;
const filepath = join(UPLOADS_DIR, fname);
@@ -177,7 +94,7 @@ router.get('/', asyncHandler(async (req, res) => {
const uploads = await Promise.all(files.map(async (filename) => {
const filepath = join(UPLOADS_DIR, filename);
const stats = await stat(filepath);
- const ext = getExtension(filename);
+ const ext = getFileExtension(filename);
totalSize += stats.size;
return {
@@ -216,7 +133,7 @@ router.get('/:filename', asyncHandler(async (req, res) => {
throw new ServerError('File not found', { status: 404, code: 'NOT_FOUND' });
}
- const ext = getExtension(safeFilename);
+ const ext = getFileExtension(safeFilename);
const mimeType = getMimeType(ext);
res.set('X-Content-Type-Options', 'nosniff');
diff --git a/server/services/catalogIngestSources.js b/server/services/catalogIngestSources.js
index 9d21f075f8..ae417b975a 100644
--- a/server/services/catalogIngestSources.js
+++ b/server/services/catalogIngestSources.js
@@ -30,7 +30,7 @@ import {
evaluateOnPage,
} from './browserService.js';
import { lookup } from 'dns/promises';
-import { PATHS, ensureDir, sleep } from '../lib/fileUtils.js';
+import { PATHS, ensureDir, sleep, safeJSONParse } from '../lib/fileUtils.js';
import { isSafeIngestUrl, isBlockedIngestHost } from '../lib/catalogValidation.js';
// Cap fetched/transcribed bodies at the scrap column boundary (the Zod
@@ -130,8 +130,7 @@ export async function fetchUrlMainText(url, { settleMs = PAGE_SETTLE_MS } = {})
return JSON.stringify({ title, text });
})()`;
const raw = await evaluateOnPage(page, expression);
- let parsed = null;
- try { parsed = raw ? JSON.parse(raw) : null; } catch { parsed = null; }
+ const parsed = raw ? safeJSONParse(raw, null) : null;
const text = clampText(parsed?.text || '');
if (!text.trim()) throw new Error('no readable text extracted from page');
return { text, title: parsed?.title || page.title || '', finalUrl: page.url || url };
diff --git a/server/services/catalogIngestSources.test.js b/server/services/catalogIngestSources.test.js
index 1c62e54708..a756a51623 100644
--- a/server/services/catalogIngestSources.test.js
+++ b/server/services/catalogIngestSources.test.js
@@ -39,6 +39,13 @@ vi.mock('../lib/fileUtils.js', () => ({
PATHS: { audio: '/tmp/data/audio' },
ensureDir: vi.fn(),
sleep: vi.fn(() => Promise.resolve()),
+ safeJSONParse: vi.fn((raw, fallback) => {
+ try {
+ return JSON.parse(raw);
+ } catch {
+ return fallback;
+ }
+ }),
}));
const catalogDB = await import('./catalogDB.js');
diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.js
index 498483a22d..f05e59b1bb 100644
--- a/server/services/ollamaManager.js
+++ b/server/services/ollamaManager.js
@@ -21,7 +21,7 @@ import { execFile, spawn } from 'child_process'
import { promisify } from 'util'
import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'
import { readResponseJson } from '../lib/readResponseJson.js'
-import { readJSONFile, sha256File } from '../lib/fileUtils.js'
+import { readJSONFile, sha256File, safeJSONParse } from '../lib/fileUtils.js'
import {
parseOllamaManifest, parseOllamaModelRef, ollamaManifestRelPath, digestToBlobFilename, buildModelfile
} from '../lib/localLlmDisk.js'
@@ -756,9 +756,8 @@ async function streamNdjson(response, onFrame) {
return lastError
}
-function safeParse(line) {
- try { return JSON.parse(line) } catch { return null }
-}
+// safeJSONParse imported from fileUtils provides identical null-on-failure semantics.
+const safeParse = (line) => safeJSONParse(line, null);
/**
* Delete an installed model (DELETE /api/delete).
diff --git a/server/services/prWatcher.js b/server/services/prWatcher.js
index d9767dca74..8802262aca 100644
--- a/server/services/prWatcher.js
+++ b/server/services/prWatcher.js
@@ -28,6 +28,7 @@ import { execGh } from './github.js';
import { getAppById, updateApp } from './apps.js';
import { getOriginInfo } from '../lib/gitRemote.js';
import { PR_AUTHOR_FILTERS } from '../lib/validation.js';
+import { safeJSONParse } from '../lib/fileUtils.js';
// Bound the gh query. The high-water mark (computePrCheck) advances to the max
// open PR number it saw, so it can only correctly drain a backlog it received
@@ -92,8 +93,8 @@ async function listOpenPullRequests(repoFullName, baseBranch) {
// otherwise throw a SyntaxError, breaking this module's "never throws"
// contract and aborting the scheduler tick (the generator calls
// checkPullRequests with no try/catch). Degrade to the pr-list-failed path.
- let parsed;
- try { parsed = JSON.parse(raw); } catch { return null; }
+ const parsed = safeJSONParse(raw, null);
+ if (parsed === null) return null;
if (!Array.isArray(parsed)) return [];
return parsed.map((pr) => ({
number: pr.number,