Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: share CORS middleware across app scaffolds (#7872)
[._.]/ Adam Eivyac41ba4ab423
diff --git a/server/lib/README.md b/server/lib/README.mdindex 130ef776e2..27472e2ea8 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -320,6 +320,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `dataRoot.js` | Data-root resolution + worktree-checkout detection (#1947). `resolveInstallRoot(fallbackRoot)` prefers the `PORTOS_DATA_ROOT` env var (pinned at real launch in `ecosystem.config.cjs`) over an `import.meta.url`-derived fallback, so a process booted from inside a CoS agent git worktree still resolves `data/`/`data.reference/` to the real install instead of the worktree's empty tree. `isWorktreeRoot(rootDir)` is the boot-migration backstop — true when `rootDir` lives under `data/cos/worktrees/` (keyed on the path segment only, so a fresh install's empty `data/` isn't a false positive). `resolveCodeRootForModule(moduleUrl)` is the single source of truth for the "two directories above this file" depth assumption — `paths.js`'s `CODE_ROOT` and `services/userActions.js`'s data-root guard both derive through it so they cannot silently drift apart. `DATA_ROOT_ENV` is the env-var name constant. Consumed by `fileUtils.js` (`PATHS`), `server/index.js`, and `scripts/run-migrations.js`. || `downloadPreflight.js` | Free-disk preflight + resumable weight download. `assessDownloadPreflight({ destPath, expectedBytes })` → `{ freeBytes, requiredBytes, headroomBytes, verdict: ok\|tight\|insufficient }`; `assertDownloadFits` throws typed `DISK_INSUFFICIENT` (507) when the volume cannot hold the payload. `streamResumableDownload` Range-resumes a `.partial` on transport failure, discards it on user cancel, and verifies a published sha256 before rename. `sweepOrphanedPartials(dirs, { maxAgeMs })` unlinks leftover `.partial` (+ `.partial.etag`) files older than 7 days (default) and skips recent/in-flight dests; missing dirs are a no-op. `probeRemoteSize` / `siblingDownloadMeta` / `verifyDownloadHash` are the size+digest helpers the four weight-download entry points share. `createDownloadSlot({ codePrefix, idleStallEnvVar, exclusive, keepPartialOnCancel })` is the one transfer-slot registry a weight download claims before its first await — in-flight map, abort controller carrying a cancel/stall reason, typed `<PREFIX>_DOWNLOAD_IN_FLIGHT`/`_STALLED`/`_CANCELLED` errors, a per-chunk progress throttle, and an `isInFlight(path)` predicate covering the dest, its `.partial`, and shards under a claimed directory. Call it at module scope only. `isAnyDownloadInFlight` answers for every registered slot at once, which is how the orphaned-partial GC protects live transfers. || `agentInstructionsFile.js` | The `AGENTS.md` + bridge `CLAUDE.md` pair a repo carries (#4852). `writeAgentInstructions(repoPath, content)` writes the body to `AGENTS.md` and the one-line `@AGENTS.md` import beside it — use it in scaffolders instead of a bare `writeFile(join(repoPath, 'CLAUDE.md'), …)`, since a generated repo carrying only one name is unreadable to half the CLIs PortOS can point at it. Constants: `AGENT_INSTRUCTIONS_FILENAME`, `CLAUDE_BRIDGE_FILENAME`, `AGENT_INSTRUCTIONS_IMPORT`. |+| `scaffoldSnippets.js` | Shared generated-project source snippets: `CORS_SNIPPET` provides dependency-free Express CORS middleware for the Express, PortOS, and Vite scaffold generators. || `failureLogging.js` | `logFailureWithStack(prefix, error, logger = console.error)` — logs `${prefix}: ${message}` plus `error.stack` as a second argument, so a fire-and-forget failure (boot init, a scheduled event handler) keeps its source location instead of collapsing to one message-only line (#6934, #7549). || `fileCore.js` | Cross-cutting filesystem primitives (`atomicWrite`, `writeFileGuarded`, `appendFileGuarded`, `copyFileGuarded`, `rmGuarded`, `unlinkGuarded`, `createWriteStreamGuarded`, directory helpers, `parseFilesystemStats(stats)` → canonical/byte-alias metrics or `null`, bounded tail reads/watchers), time/format helpers, directory sizing, and SHA-256 helpers. || `familySettingsMap.js` | The merge rule every per-provider-family map in `data/settings.json` shares (plan prices, plan tiers) — `normalizeFamilyMap(raw, normalizeValue)` and `mergeFamilyMap(stored, patch, normalizeValue)`, which hold the absent-vs-present-but-empty contract in ONE place: an omitted family keeps its stored value, one sent empty is an intentional clear and is deleted. Each store supplies only its value normalizer. Pure. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 3dfa2300d3..1cc1a65870 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -283,6 +283,7 @@ export * from './createNewestWinsGuard.js';export * from './dataRoot.js';export * from './downloadPreflight.js';export * from './agentInstructionsFile.js';+export * from './scaffoldSnippets.js';export * from './failureLogging.js';export * from './fileCore.js';export * as fileUtils from './fileUtils.js';diff --git a/server/lib/scaffoldSnippets.js b/server/lib/scaffoldSnippets.jsnew file mode 100644index 0000000000..83496dd390--- /dev/null+++ b/server/lib/scaffoldSnippets.js@@ -0,0 +1,8 @@+// Inline CORS middleware snippet for generated projects (no cors package dependency)+export const CORS_SNIPPET = `app.use((req, res, next) => {+ res.set('Access-Control-Allow-Origin', '*');+ res.set('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');+ res.set('Access-Control-Allow-Headers', 'Content-Type,Authorization');+ if (req.method === 'OPTIONS') return res.sendStatus(204);+ next();+});`;diff --git a/server/routes/scaffoldExpress.js b/server/routes/scaffoldExpress.jsindex a0728cc179..16a35a2f4f 100644--- a/server/routes/scaffoldExpress.js+++ b/server/routes/scaffoldExpress.js@@ -1,15 +1,7 @@import { writeFile } from 'fs/promises';import { join } from 'path';import { atomicWrite } from '../lib/fileUtils.js';--// Inline CORS middleware snippet for generated projects (no cors package dependency)-const CORS_SNIPPET = `app.use((req, res, next) => {- res.set('Access-Control-Allow-Origin', '*');- res.set('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');- res.set('Access-Control-Allow-Headers', 'Content-Type,Authorization');- if (req.method === 'OPTIONS') return res.sendStatus(204);- next();-});`;+import { CORS_SNIPPET } from '../lib/scaffoldSnippets.js';export async function scaffoldExpress(repoPath, dirName, apiPort, addStep) {const pkg = {diff --git a/server/routes/scaffoldPortOS.js b/server/routes/scaffoldPortOS.jsindex 3aa3eef794..6ba29ad8e5 100644--- a/server/routes/scaffoldPortOS.js+++ b/server/routes/scaffoldPortOS.js@@ -2,15 +2,7 @@ import { writeFile } from 'fs/promises';import { join } from 'path';import { atomicWrite, ensureDir, ensureDirs } from '../lib/fileUtils.js';import { writeAgentInstructions } from '../lib/agentInstructionsFile.js';--// Inline CORS middleware snippet for generated projects (no cors package dependency)-const CORS_SNIPPET = `app.use((req, res, next) => {- res.set('Access-Control-Allow-Origin', '*');- res.set('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');- res.set('Access-Control-Allow-Headers', 'Content-Type,Authorization');- if (req.method === 'OPTIONS') return res.sendStatus(204);- next();-});`;+import { CORS_SNIPPET } from '../lib/scaffoldSnippets.js';export async function scaffoldPortOS({ repoPath, name, dirName, uiPort, apiPort, addStep }) {const clientDir = join(repoPath, 'client');diff --git a/server/routes/scaffoldVite.js b/server/routes/scaffoldVite.jsindex 62e2b81f64..bfcde1c673 100644--- a/server/routes/scaffoldVite.js+++ b/server/routes/scaffoldVite.js@@ -4,15 +4,7 @@ import { join } from 'path';import { spawn } from '../lib/childProcess.js';import { atomicWrite, ensureDir } from '../lib/fileUtils.js';import { safeJSONParse } from '../lib/fileUtils.js';--// Inline CORS middleware snippet for generated projects (no cors package dependency)-const CORS_SNIPPET = `app.use((req, res, next) => {- res.set('Access-Control-Allow-Origin', '*');- res.set('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');- res.set('Access-Control-Allow-Headers', 'Content-Type,Authorization');- if (req.method === 'OPTIONS') return res.sendStatus(204);- next();-});`;+import { CORS_SNIPPET } from '../lib/scaffoldSnippets.js';export async function scaffoldVite({ repoPath, dirName, parentDir, template, uiPort, apiPort, addStep }) {// Create using npm create vite