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
fix: bound PM2 brace patterns before stack exhaustion (#9906)
Adam Eivy65d2e06fc9b2
diff --git a/docs/DEPS.md b/docs/DEPS.mdindex 5abd4937a0..ad76069d84 100644--- a/docs/DEPS.md+++ b/docs/DEPS.md@@ -193,6 +193,20 @@ Packages that legitimately need an install script are named explicitly in the alDate semantics: LIST carries no timezone, so values are read as UTC (the zone MDTM and MLSD use). `Mon d yyyy`, `d Mon yyyy` → midnight UTC (day resolution); `Mon d hh:mm`, `d Mon hh:mm` → the latest year not more than a day ahead of now; `yyyy-mm-dd hh:mm` (`-` or `/`) → as written. Anything else (non-English months, Japanese forms, impossible dates, ambiguous numeric forms) throws `EFTPLISTDATE` rather than inventing a timestamp. Cache validation compares exact instants, so a listing that switches from the time form to the year form simply redownloads. The security-patched `basic-ftp` override is unchanged.+### PM2 brace recursion mitigation (#9906)++As of 2026-10-03, the upstream [braces advisory GHSA-vfj7-8cjw-p6xm](https://github.com/advisories/GHSA-vfj7-8cjw-p6xm) has no first patched release, and npm still publishes braces 3.0.3 / PM2 7.0.4. Both root and server lockfiles resolve PM2 → chokidar 3.6.0 → the hoisted braces 3.0.3. They intentionally keep those supported versions; changing the server's separate chokidar 5 dependency does not change PM2's watcher.++`scripts/lib/bracesDepthPatch.js` applies a local mitigation during the existing trusted-rebuild step. It verifies the installed version and complete upstream file hashes before editing, then bounds parser nesting and recursive compile, expand, stringify, append and flatten calls to 64 levels. Excessive patterns or externally supplied ASTs throw `EBRACESDEPTH` instead of exhausting the process stack. Quoted, escaped and bracketed literals preserve their parser semantics. A missing braces install is a no-op; unfamiliar releases, modified walkers and failed writes stop startup/install so an unguarded tree cannot be marked repaired. The patch is idempotent and repairs a partly written patch on the next attempt. Re-verify the patch when bumping braces; the dependency parity test pins both its version and hoisted location.++All managed setup/update paths already run trusted rebuilds. `scripts/ensure-deps.js` additionally reapplies patches to existing workspace trees before `npm start` launches PM2, covering code-only upgrades with unchanged manifests and lockfiles. The trusted-rebuild cache stamp includes this patch's fingerprint.++Input authority: PortOS's own ecosystem processes disable watching, and command-launched apps set `watch: false`; the spawn helper strips inherited `watch`. Managed-app lifecycle requests can also load that app's existing ecosystem file (`server/routes/apps/lifecycle.js` → `server/services/pm2.js`). PM2's `Watcher.js` passes ecosystem `watch`, `ignore_watch`, and `watch_options` to chokidar. Those patterns therefore come from locally admitted app configuration or an operator's PM2 CLI use, rather than an anonymous API watch-pattern field. Host-control route gates remain required; this tracing is not a claim that every reachable peer is trusted or that arbitrary app configuration is safe. The mitigation guards the dependency regardless of pattern origin.++Regression tests copy the actual PM2 braces consumer into disposable trees, exercise deeply nested patterns below the existing character limit and externally supplied ASTs, verify normal globs/literals, and reject unfamiliar walkers before writing. Validation also used a disposable PM2 daemon with its own `PM2_HOME` and synthetic app: start, explicit restart, brace-glob file-watch restart, stop, and daemon cleanup all passed. No live managed processes were used.++Dependabot alerts 58 (`package-lock.json`) and 59 (`server/package-lock.json`) are version-based and cannot detect this install-time patch. Reconcile each only after the mitigation PR is merged, recording the merged commit, this patch and regression evidence in the dismissal comment. The `tolerable_risk` reason records the local mitigation while the upstream version remains flagged; it is not an upstream fix or a claim of non-reachability. Future upstream fixes should replace the patch and restore version-based resolution.+## Inline Audit Policy`audit=false` is pinned in the same five `.npmrc` files, enforced by the same discovered-workspace test. This turns off only the advisory lookup `npm install` performs *after* it has already resolved and written `node_modules` — it does not change what gets installed.diff --git a/scripts/ensure-deps.js b/scripts/ensure-deps.jsindex 9085767605..b3a651b35d 100644--- a/scripts/ensure-deps.js+++ b/scripts/ensure-deps.js@@ -8,7 +8,7 @@ import { execFileSync } from 'child_process';import { createHash } from 'crypto';import { join, dirname } from 'path';import { fileURLToPath } from 'url';-import { rebuildTrusted } from './trusted-rebuilds.js';+import { rebuildTrusted, patchInstalledDependencies } from './trusted-rebuilds.js';import { isDirectlyInvoked } from './lib/directInvocation.js';// Node refuses to spawn npm's `.cmd` shim under `shell:false` (CVE-2024-27980),// so every npm spawn goes through this wrap. Safe to import before `npm install`@@ -205,6 +205,10 @@ function main() {}}+ // A code-only upgrade can change an install-time patch without changing any+ // manifest or lockfile. Repair warm trees too, before PM2 is ever started.+ for (const { dir } of WORKSPACES) patchInstalledDependencies(dir);+if (hashesDirty) saveHashes(storedHashes);if (needed) console.log('✅ Dependencies verified');diff --git a/scripts/ensure-deps.test.js b/scripts/ensure-deps.test.jsindex ab70eb8e9a..c12c01f3cf 100644--- a/scripts/ensure-deps.test.js+++ b/scripts/ensure-deps.test.js@@ -97,7 +97,12 @@ describe('startup dependency reconciliation', () => {writeFileSync(join(root, 'package.json'), '{"type":"module"}');copyFileSync(join(REPO_ROOT, 'scripts', 'ensure-deps.js'), join(root, 'scripts', 'ensure-deps.js'));copyFileSync(join(REPO_ROOT, 'scripts', 'lib', 'directInvocation.js'), join(root, 'scripts', 'lib', 'directInvocation.js'));- writeFileSync(join(root, 'scripts', 'trusted-rebuilds.js'), 'export const rebuildTrusted = () => true;');+ writeFileSync(join(root, 'scripts', 'trusted-rebuilds.js'), `+ import { writeFileSync } from 'fs';+ import { join } from 'path';+ export const rebuildTrusted = () => true;+ export const patchInstalledDependencies = dir => writeFileSync(join(dir, 'node_modules', 'patch-applied'), 'patched');+ `);writeFileSync(join(root, 'server', 'lib', 'bufferedSpawn.js'), `import { fileURLToPath } from 'url';export const prepareCliSpawn = (command, args) => ({@@ -143,8 +148,10 @@ describe('startup dependency reconciliation', () => {expect(readFileSync(join(f.client, 'package-lock.json'), 'utf8')).toBe(updated);expect(readFileSync(join(f.client, 'package.json'), 'utf8')).toBe('{}');writeFileSync(join(f.client, 'node_modules', 'keep'), 'unchanged tree');+ rmSync(join(f.client, 'node_modules', 'patch-applied'));expect(f.run()).not.toContain('reinstall');expect(existsSync(join(f.client, 'node_modules', 'keep'))).toBe(true);+ expect(readFileSync(join(f.client, 'node_modules', 'patch-applied'), 'utf8')).toBe('patched');} finally {rmSync(f.root, { recursive: true, force: true });}diff --git a/scripts/lib/bracesDepthPatch.js b/scripts/lib/bracesDepthPatch.jsnew file mode 100644index 0000000000..142aaa8b2b--- /dev/null+++ b/scripts/lib/bracesDepthPatch.js@@ -0,0 +1,87 @@+/** Install-time mitigation for GHSA-vfj7-8cjw-p6xm (#9906).+ * PM2 still requires chokidar 3.6.0 / braces 3.0.3. Keep that API and refuse+ * excessive parser/AST recursion instead. Never edit an unfamiliar release.+ */+import { createHash } from 'crypto';+import { existsSync, readFileSync, writeFileSync } from 'fs';+import { join } from 'path';++export const BRACES_PATCH_TARGET_VERSION = '3.0.3';+export const BRACES_MAX_DEPTH = 64;+const MARKER = '// portos #9906 depth guard';+const guard = `${MARKER}\n if (depth > ${BRACES_MAX_DEPTH}) throw Object.assign(new RangeError('Brace nesting exceeds safe depth'), { code: 'EBRACESDEPTH' });`;+const digest = source => createHash('sha256').update(source).digest('hex');++// Verify complete upstream files, not merely an anchor that another release+// could retain while changing the recursion around it.+const FILES = {+ 'parse.js': {+ hash: 'e572166565f15fa6ad9865ae49d678218e32aabfd1b3720f6d0d43d39800d310',+ changes: [[' stack.push(block);', ` ${MARKER}\n if (stack.length > ${BRACES_MAX_DEPTH}) throw Object.assign(new RangeError('Brace nesting exceeds safe depth'), { code: 'EBRACESDEPTH' });\n stack.push(block);`]],+ },+ 'compile.js': {+ hash: 'dc98f22eee3d511785d92a00758d5f0d48efed5f5813bdecc2de430c529b5c9f',+ changes: [+ ['const walk = (node, parent = {}) => {', `const walk = (node, parent = {}, depth = 0) => {\n ${guard}`],+ ['walk(child, node)', 'walk(child, node, depth + 1)'],+ ],+ },+ 'expand.js': {+ hash: '41ccc196ebfa7b7781a634e721eb744e4e7bcb54cba427a7e3d6806a1b9e58f7',+ changes: [+ ['const walk = (node, parent = {}) => {', `const walk = (node, parent = {}, depth = 0) => {\n ${guard}`],+ ['walk(child, node)', 'walk(child, node, depth + 1)'],+ ["const append = (queue = '', stash = '', enclose = false) => {", `const append = (queue = '', stash = '', enclose = false, depth = 0) => {\n ${guard}`],+ ['append(value, stash, enclose)', 'append(value, stash, enclose, depth + 1)'],+ ['append(item, ele, enclose)', 'append(item, ele, enclose, depth + 1)'],+ ],+ },+ 'stringify.js': {+ hash: '379f22d77bfa1478341ccd49c5e4267464aabcbba03558bab332aac23fc6f23a',+ changes: [+ ['const stringify = (node, parent = {}) => {', `const stringify = (node, parent = {}, depth = 0) => {\n ${guard}`],+ ['stringify(child)', 'stringify(child, {}, depth + 1)'],+ ],+ },+ 'utils.js': {+ hash: 'b5a7596aa67730412b3c029ef09e84e6b67b8e445cffd35d1d295549c89066c7',+ changes: [+ ['const flat = arr => {', `const flat = (arr, depth = 0) => {\n ${guard}`],+ ['flat(ele)', 'flat(ele, depth + 1)'],+ ],+ },+};++export const bracesPatchFingerprint = () => digest(JSON.stringify({+ version: BRACES_PATCH_TARGET_VERSION, files: FILES,+})).slice(0, 16);++/** Patch the lockfile's hoisted braces install. Throws on unexpected code or+ * I/O failure: unlike the FTP compatibility patch, this is a security guard.+ * Both shipped PM2 lockfiles pin this location and version in the parity test.+ * All files are validated before any write. A partial write is repairable on+ * the next attempt because each file accepts pristine OR exact patched bytes.+ */+export function applyBracesDepthPatch(nodeModulesDir) {+ const dir = join(nodeModulesDir, 'braces');+ if (!existsSync(dir)) return 'absent';+ const manifest = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));+ if (manifest.version !== BRACES_PATCH_TARGET_VERSION) {+ throw new Error(`Unrecognized braces release for depth patch: ${manifest.version}`);+ }+ const files = Object.entries(FILES).map(([name, { hash, changes }]) => {+ const path = join(dir, 'lib', name);+ const installed = readFileSync(path, 'utf8');+ const original = changes.reduce((source, [before, after]) => source.replaceAll(after, before), installed);+ if (digest(original) !== hash) throw new Error(`Unrecognized braces ${name} for depth patch`);+ const patched = changes.reduce((source, [before, after]) => source.replaceAll(before, after), original);+ return { path, installed, patched };+ });+ let changed = false;+ for (const { path, installed, patched } of files) {+ if (installed === patched) continue;+ writeFileSync(path, patched);+ changed = true;+ }+ return changed ? 'patched' : 'already-patched';+}diff --git a/scripts/lib/bracesDepthPatch.test.js b/scripts/lib/bracesDepthPatch.test.jsnew file mode 100644index 0000000000..f0b818e553--- /dev/null+++ b/scripts/lib/bracesDepthPatch.test.js@@ -0,0 +1,89 @@+import { afterEach, describe, expect, it } from 'vitest';+import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';+import { createRequire } from 'module';+import { tmpdir } from 'os';+import { dirname, join } from 'path';+import { fileURLToPath } from 'url';+import { applyBracesDepthPatch, BRACES_MAX_DEPTH } from './bracesDepthPatch.js';+import { patchInstalledDependencies, rebuildTrusted, runCli } from '../trusted-rebuilds.js';++const require = createRequire(import.meta.url);+// CI installs the server tree only. Follow PM2's actual chokidar consumer,+// rather than assuming a root install or the server's unrelated chokidar 5.+const pm2Require = createRequire(require.resolve('pm2/package.json', { paths: [fileURLToPath(new URL('../../server/', import.meta.url))] }));+const watcherRequire = createRequire(pm2Require.resolve('chokidar'));+const bracesRequire = createRequire(watcherRequire.resolve('braces/package.json'));+const dirs = [];+afterEach(() => dirs.splice(0).forEach(dir => rmSync(dir, { recursive: true, force: true })));++const install = () => {+ const dir = mkdtempSync(join(tmpdir(), 'braces-depth-patch-'));+ dirs.push(dir);+ const modules = join(dir, 'node_modules');+ mkdirSync(modules);+ for (const name of ['braces', 'fill-range', 'to-regex-range', 'is-number']) {+ cpSync(dirname(bracesRequire.resolve(`${name}/package.json`)), join(modules, name), { recursive: true });+ }+ return { dir, modules, braces: () => require(join(modules, 'braces')) };+};++describe('PM2 braces depth mitigation (#9906)', () => {+ it('refuses deep brace, parenthesis and malformed patterns with a bounded error, then remains usable', () => {+ const f = install();+ patchInstalledDependencies(f.dir);+ const braces = f.braces();+ const deep = '{'.repeat(4000) + 'a,b' + '}'.repeat(4000);+ for (const input of [deep, '('.repeat(4000) + 'x' + ')'.repeat(4000), '{'.repeat(4000)]) {+ for (const method of ['parse', 'compile', 'expand', 'stringify']) {+ expect(() => braces[method](input)).toThrowError(expect.objectContaining({ code: 'EBRACESDEPTH' }));+ }+ }+ expect(braces.expand('src/{client,server}/{a..c}.js')).toEqual([+ 'src/client/a.js', 'src/client/b.js', 'src/client/c.js',+ 'src/server/a.js', 'src/server/b.js', 'src/server/c.js',+ ]);+ expect(braces.compile('src/{client,server}/*.js')).toBe('src/(client|server)/*.js');+ // Quoted, escaped and bracketed literals must not spend nesting depth.+ const literal = '{'.repeat(100);+ expect(braces.stringify(`"${literal}"`)).toBe(literal);+ expect(braces.stringify('\\{'.repeat(100))).toBe(literal);+ expect(braces.stringify(`[${literal}]`)).toBe(`[${literal}]`);+ expect(braces.stringify('{a')).toBe('{a');+ });++ it('guards externally supplied ASTs as well as parser input', () => {+ const f = install();+ applyBracesDepthPatch(f.modules);+ const braces = f.braces();+ const ast = () => {+ let node = { type: 'text', value: 'x' };+ for (let i = 0; i < BRACES_MAX_DEPTH + 2; i++) node = { type: 'root', nodes: [node] };+ return node;+ };+ for (const method of ['compile', 'expand', 'stringify']) {+ expect(() => braces[method](ast())).toThrowError(expect.objectContaining({ code: 'EBRACESDEPTH' }));+ }+ });++ it('patches idempotently through both managed rebuild and rebuild-free CLI paths', () => {+ const f = install();+ expect(rebuildTrusted(f.dir, 'client')).toBe(true);+ const file = join(f.modules, 'braces', 'lib', 'compile.js');+ const once = readFileSync(file, 'utf8');+ expect(runCli(['browser', f.dir])).toBe(0);+ expect(applyBracesDepthPatch(f.modules)).toBe('already-patched');+ expect(readFileSync(file, 'utf8')).toBe(once);+ });++ it('fails the install before writing when any upstream walker is unfamiliar', () => {+ const f = install();+ const compile = join(f.modules, 'braces', 'lib', 'compile.js');+ const parse = join(f.modules, 'braces', 'lib', 'parse.js');+ const original = readFileSync(parse, 'utf8');+ writeFileSync(compile, 'module.exports = () => "foreign";');+ expect(() => runCli(['browser', f.dir])).toThrow('Unrecognized braces compile.js');+ expect(readFileSync(parse, 'utf8')).toBe(original);+ writeFileSync(join(f.modules, 'braces', 'package.json'), '{"version":"4.0.0"}');+ expect(() => applyBracesDepthPatch(f.modules)).toThrow('Unrecognized braces release');+ });+});diff --git a/scripts/trusted-rebuild-stamp.js b/scripts/trusted-rebuild-stamp.jsindex 011b50cb63..b222896de8 100644--- a/scripts/trusted-rebuild-stamp.js+++ b/scripts/trusted-rebuild-stamp.js@@ -34,6 +34,7 @@ import { existsSync, readFileSync, writeFileSync } from 'fs';import { join } from 'path';import { isDirectlyInvoked } from './lib/directInvocation.js';+import { bracesPatchFingerprint } from './lib/bracesDepthPatch.js';import { patchFingerprint } from './lib/getUriFtpPatch.js';import { TRUSTED_REBUILDS, discoverWorkspaces, workspaceDir } from './trusted-rebuilds.js';@@ -53,7 +54,7 @@ export function expectedStamp(label, { platform = process.platform, arch = proceallowlist: createHash('sha256').update(JSON.stringify(TRUSTED_REBUILDS[label] ?? null)).digest('hex').slice(0, 16),// Install-time dependency patches are applied by the same step that writes// this mark, so a cached tree from before a patch changed must read as stale.- patches: patchFingerprint(),+ patches: `${patchFingerprint()}:${bracesPatchFingerprint()}`,platform,arch,modules: String(modules),diff --git a/scripts/trusted-rebuilds.js b/scripts/trusted-rebuilds.jsindex 71154bb54d..9d75a39346 100644--- a/scripts/trusted-rebuilds.js+++ b/scripts/trusted-rebuilds.js@@ -24,6 +24,7 @@ import { fileURLToPath } from 'url';import { prepareCliSpawn } from '../server/lib/bufferedSpawn.js';import { isDirectlyInvoked } from './lib/directInvocation.js';import { applyGetUriFtpPatch } from './lib/getUriFtpPatch.js';+import { applyBracesDepthPatch } from './lib/bracesDepthPatch.js';const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');@@ -85,10 +86,12 @@ export const TRUSTED_REBUILDS = {* tree (get-uri's FTP adapter, #9462 — see scripts/lib/getUriFtpPatch.js). Rides* on this module because every managed install path already calls it after* `npm install` and `ignore-scripts=true` rules out a postinstall hook. Never- * fatal: the FTP fallback is a compatibility fix, not a boot requirement, and a- * get-uri release this patch does not recognize is reported rather than edited.+ * fatal for the FTP compatibility fallback. The braces recursion guard is+ * mandatory: unrecognized code or failed patch writes must stop the install.*/export function patchInstalledDependencies(dir) {+ const bracesStatus = applyBracesDepthPatch(join(dir, 'node_modules'));+ if (bracesStatus === 'patched') console.log(`🩹 Patched braces recursion depth in ${dir}`);try {const status = applyGetUriFtpPatch(join(dir, 'node_modules'));if (status === 'patched') console.log(`🩹 Patched get-uri FTP LIST date fallback in ${dir}`);diff --git a/server/dependency-overrides.test.js b/server/dependency-overrides.test.jsindex f04578fab7..3092a1a3a8 100644--- a/server/dependency-overrides.test.js+++ b/server/dependency-overrides.test.js@@ -4,6 +4,7 @@ import { readFileSync } from 'fs';import { fileURLToPath } from 'url';import { dirname, join } from 'path';import { discoverWorkspaces } from '../scripts/trusted-rebuilds.js';+import { BRACES_PATCH_TARGET_VERSION } from '../scripts/lib/bracesDepthPatch.js';import { GET_URI_PATCH_TARGET_VERSION } from '../scripts/lib/getUriFtpPatch.js';const __dirname = dirname(fileURLToPath(import.meta.url));@@ -198,6 +199,14 @@ describe('dependency override parity across manifests (#2848)', () => {);});+ it.each(['package.json', 'server/package.json'])('%s pins the braces install the depth patch guards (#9906)', rel => {+ const resolved = Object.entries(readLockPackages(lockfileFor(rel)))+ .filter(([path]) => packageNameFromLockPath(path) === 'braces');+ expect(resolved.map(([path, metadata]) => [path, metadata.version])).toEqual([+ ['node_modules/braces', BRACES_PATCH_TARGET_VERSION],+ ]);+ });+it('governs every workspace manifest that ships its own lockfile', () => {const tracked = trackedLockfiles();const ungoverned = discoverWorkspaces()