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

fix: close two temp-path guard holes and stop the NODE_ENV guard passing vacuously (#4554)

[._.]/ Adam Eivyb79abd01b7c0
diff --git a/server/lib/README.md b/server/lib/README.md
index 5f4dcce45a..dd9522fb70 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -321,7 +321,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `renderSlot.js` | Render-slot helpers for `(proof\|final)Image` per stage. |
| `renderTargets.js` | Render-target alphabet (#3231): `RENDER_TARGET`/`RENDER_TARGETS` name every creative surface that enqueues renders (universe-bible, sprite-reference, music-video, …) — the keys into `settings.renderDefaults` — plus the `RENDER_TARGET_BACKEND_AUTO` fall-through sentinel. Dependency-free leaf; resolved per surface by `services/imageGen/cloudProviderConfig.js#resolveRenderTargetConfig`. |
| `telegramClient.js` | Telegram bot client. |
-| `tempPathGuard.js` | Throwaway-path guard for destructive test fixtures. `isTempPath(target)` — true only for an absolute path under `os.tmpdir()` (both the raw dir and its realpath count, so macOS `/var/folders/...` vs `/private/var/folders/...` both pass); `assertTempPath(target, operation)` throws otherwise and returns `target` so it can wrap an argument inline. Use it before any fixture `git init` / `git config` / `rm -rf`: `spawn` silently substitutes `process.cwd()` for a missing cwd, which is how a test run once set `core.bare = true` on a real checkout (#4554). |
+| `tempPathGuard.js` | Throwaway-path guard for destructive test fixtures. `isTempPath(target)` — true only for an absolute path that is a STRICT descendant of `os.tmpdir()` **after symlinks are resolved** (`os.tmpdir()` itself is refused, or `destroyGitSandbox(tmpdir())` would wipe every process's scratch; a `..` segment is refused rather than lexically collapsed; macOS `/var/folders/...` and `/private/var/folders/...` both pass). `assertTempPath(target, operation)` throws otherwise and returns `target` so it can wrap an argument inline. Use it before any fixture `git init` / `git config` / `rm -rf`: `spawn` silently substitutes `process.cwd()` for a missing cwd, which is how a test run once set `core.bare = true` on a real checkout (#4554). |
| `vaultCrypto.js` | Privacy Center PII Vault field-level encryption (issue #2140). AES-256-GCM `encryptValue`/`decryptValue` (`v1:<iv>:<tag>:<ct>` format, per-value 12-byte IV), `ensureVaultKey()` self-heal (generates `PRIVACY_VAULT_KEY` into the install root's `.env` on first write, replacing any invalid line; never logs the value), key resolution that falls back to reading `.env` so decrypt/status survive a server restart, `isVaultKeyConfigured()`, and the per-type `maskValue(type, plaintext)` display masking (last-4 / domain-visible / street-masked). Plaintext must never be logged by callers. |
## Model & config
diff --git a/server/lib/tempPathGuard.js b/server/lib/tempPathGuard.js
index d99ba1b7e6..29d90ce8a0 100644
--- a/server/lib/tempPathGuard.js
+++ b/server/lib/tempPathGuard.js
@@ -10,53 +10,71 @@
* live `.git/config` (`core.bare = true`, commits re-attributed to
* `test <test@test>`).
*
- * These helpers turn that silent fallback into a loud throw: resolve the target
- * and refuse anything that is not an absolute path under the OS temp dir.
- * Both the raw `os.tmpdir()` and its realpath count as roots, because macOS
- * reports `/var/folders/...` while `realpath` yields `/private/var/folders/...`.
+ * These helpers turn that silent fallback into a loud throw. Three properties
+ * carry the whole guarantee, and none of them is optional:
+ *
+ * - The target is judged by its CANONICAL path, not its spelling. A symlink
+ * sitting inside the temp dir and pointing at a real checkout is where the
+ * filesystem would actually operate, so that is what gets checked.
+ * - `..` is refused outright rather than modeled — `path.resolve` collapses it
+ * lexically, which is the wrong answer the moment a symlinked ancestor is
+ * involved.
+ * - The target must be a STRICT descendant of the temp dir. `os.tmpdir()`
+ * itself is not an acceptable target: `destroyGitSandbox(tmpdir())` would
+ * recursively delete the whole system temp directory.
*/
import { realpathSync } from 'fs';
import { tmpdir } from 'os';
-import { isAbsolute, resolve, sep } from 'path';
+import { basename, dirname, isAbsolute, join, resolve, sep } from 'path';
-const realpathOrSelf = (candidate) => {
- try {
- return realpathSync(candidate);
- } catch {
- // Not created yet (a fixture's `scratch/primary`) — the resolved path is
- // the best answer we have, and its temp-ness is decided by its ancestors.
- return candidate;
+/**
+ * The path the filesystem would really act on: realpath of the deepest existing
+ * ancestor, plus the not-yet-created tail (a fixture's `scratch/primary` does
+ * not exist yet, and a path component that does not exist cannot be a symlink).
+ */
+function canonicalize(resolved) {
+ const tail = [];
+ let existing = resolved;
+ for (;;) {
+ try {
+ return join(realpathSync(existing), ...tail);
+ } catch {
+ const parent = dirname(existing);
+ if (parent === existing) return resolved; // hit the root; nothing resolved
+ tail.unshift(basename(existing));
+ existing = parent;
+ }
}
-};
+}
function tempRoots() {
// Read `tmpdir()` on every call: TMPDIR is per-process env, and tests stub it.
const raw = resolve(tmpdir());
- const real = realpathOrSelf(raw);
- return real === raw ? [raw] : [raw, real];
+ return [...new Set([raw, canonicalize(raw)])];
}
// Windows paths compare case-insensitively, and a TEMP env var spelled with
// different casing than a resolved path would otherwise read as "not temp".
const comparable = (value) => (process.platform === 'win32' ? value.toLowerCase() : value);
-function isUnder(child, parent) {
+/** Strict descendant — deliberately NOT `child === parent`; see the header. */
+function isStrictlyUnder(child, parent) {
const c = comparable(child);
const p = comparable(parent);
- return c === p || c.startsWith(p.endsWith(sep) ? p : `${p}${sep}`);
+ return c.startsWith(p.endsWith(sep) ? p : `${p}${sep}`) && c.length > p.length;
}
/**
- * True when `target` is an absolute path inside the OS temp dir.
- * A non-string, empty, or relative `target` is always false — those are the
- * shapes that would otherwise be resolved against `process.cwd()`.
+ * True when `target` is an absolute path strictly inside the OS temp dir, after
+ * symlinks are resolved. A non-string, empty, relative, or `..`-bearing
+ * `target` is always false — those are the shapes that would otherwise be
+ * resolved against `process.cwd()` or climb out through a symlinked ancestor.
*/
export function isTempPath(target) {
if (typeof target !== 'string' || target.length === 0 || !isAbsolute(target)) return false;
- const resolved = resolve(target);
- const real = realpathOrSelf(resolved);
- const candidates = real === resolved ? [resolved] : [resolved, real];
- return tempRoots().some((root) => candidates.some((candidate) => isUnder(candidate, root)));
+ if (target.split(/[\\/]+/).includes('..')) return false;
+ const canonical = canonicalize(resolve(target));
+ return tempRoots().some((root) => isStrictlyUnder(canonical, root));
}
/**
@@ -71,7 +89,8 @@ export function assertTempPath(target, operation = 'this operation') {
if (isTempPath(target)) return target;
throw new Error(
`❌ refusing to run ${operation} outside ${tmpdir()} — got ${JSON.stringify(target)}. `
- + 'Test git fixtures must target a directory created under os.tmpdir(); '
- + 'a missing or relative path would fall back to process.cwd() and mutate the real checkout.',
+ + 'Test git fixtures must target a directory created UNDER os.tmpdir() (the temp dir '
+ + 'itself, a relative or `..`-bearing path, and a symlink out of the temp dir are all '
+ + 'refused); anything else would mutate the real checkout.',
);
}
diff --git a/server/lib/tempPathGuard.test.js b/server/lib/tempPathGuard.test.js
index 636f7151a3..523f43992a 100644
--- a/server/lib/tempPathGuard.test.js
+++ b/server/lib/tempPathGuard.test.js
@@ -15,10 +15,10 @@
* suite never writes outside the OS temp dir, and never near a real checkout.
*/
import { describe, it, expect, afterEach, vi } from 'vitest';
-import { mkdtemp, rm, writeFile, readFile, readdir } from 'fs/promises';
+import { mkdtemp, rm, writeFile, readFile, readdir, symlink } from 'fs/promises';
import { existsSync } from 'fs';
import { tmpdir } from 'os';
-import { join } from 'path';
+import { join, sep } from 'path';
import { isTempPath, assertTempPath } from './tempPathGuard.js';
import { execGit } from './execGit.js';
import {
@@ -79,6 +79,39 @@ describe('isTempPath', () => {
pretendTmpdirIs(await scratchDir());
expect(isTempPath(outside)).toBe(false);
});
+
+ it('rejects the temp dir ITSELF — an rm -rf there would wipe every process\u2019s scratch', async () => {
+ const root = await scratchDir();
+ pretendTmpdirIs(root);
+ // Bypass probe: a child of the same root is accepted, so the rejection
+ // below is the strict-descendant rule and not a broken root comparison.
+ expect(isTempPath(join(root, 'child'))).toBe(true);
+ expect(isTempPath(root)).toBe(false);
+ expect(isTempPath(tmpdir())).toBe(false);
+ });
+
+ it('judges a symlink by where it POINTS, not where it sits', async () => {
+ const outside = await scratchDir();
+ const root = await scratchDir();
+ const escape = join(root, 'escape');
+ await symlink(outside, escape, 'dir');
+ pretendTmpdirIs(root);
+
+ // Bypass probe: a real directory in exactly the same place is accepted, so
+ // the rejections below are the symlink target being followed.
+ expect(isTempPath(join(root, 'escape-but-real'))).toBe(true);
+ expect(isTempPath(escape)).toBe(false);
+ expect(isTempPath(join(escape, 'repo'))).toBe(false);
+ });
+
+ it('rejects a path that climbs out with ..', async () => {
+ const root = await scratchDir();
+ pretendTmpdirIs(root);
+ // Built by hand: path.join would collapse the '..' before the guard sees it,
+ // and a lexical collapse is exactly the wrong answer through a symlink.
+ expect(isTempPath(`${root}${sep}sub${sep}..${sep}sub`)).toBe(false);
+ expect(isTempPath(join(root, 'sub'))).toBe(true); // bypass probe
+ });
});
describe('assertTempPath', () => {
diff --git a/server/vitest.config.test.js b/server/vitest.config.test.js
index 5ba4b7bbea..5415ed0a9c 100644
--- a/server/vitest.config.test.js
+++ b/server/vitest.config.test.js
@@ -16,30 +16,40 @@
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
-const CONFIGS = ['./vitest.config.js', './vitest.config.db.js'];
-
beforeEach(() => {
vi.resetModules();
});
afterEach(() => {
+ vi.doUnmock('./vitest.config.db.js');
// Restores the pre-stub value even though the config under test reassigns
// process.env.NODE_ENV directly.
vi.unstubAllEnvs();
});
-describe.each(CONFIGS)('%s', (configPath) => {
- it('overrides an inherited non-test NODE_ENV when the config loads', async () => {
- vi.stubEnv('NODE_ENV', 'development');
- expect(process.env.NODE_ENV).toBe('development'); // bypass probe: really unset
+/** Assert the just-loaded config both forced the value and pinned it for workers. */
+async function expectForces(configPath) {
+ vi.stubEnv('NODE_ENV', 'development');
+ expect(process.env.NODE_ENV).toBe('development'); // bypass probe: the stub took
+
+ const config = (await import(configPath)).default;
- await import(configPath);
+ expect(process.env.NODE_ENV).toBe('test');
+ expect(config.test.env.NODE_ENV).toBe('test');
+}
- expect(process.env.NODE_ENV).toBe('test');
+describe('vitest.config.js', () => {
+ it('forces NODE_ENV=test on its own, not via the db config it imports', async () => {
+ // It pulls DB_TEST_INCLUDE from vitest.config.db.js, and THAT module forces
+ // NODE_ENV at its own top level — so without stubbing the import out, this
+ // case would still pass with vitest.config.js's assignment deleted.
+ vi.doMock('./vitest.config.db.js', () => ({ DB_TEST_INCLUDE: [] }));
+ await expectForces('./vitest.config.js');
});
+});
- it('pins NODE_ENV=test for the worker processes too', async () => {
- const config = (await import(configPath)).default;
- expect(config.test.env.NODE_ENV).toBe('test');
+describe('vitest.config.db.js', () => {
+ it('forces NODE_ENV=test when loaded directly by npm run test:db', async () => {
+ await expectForces('./vitest.config.db.js');
});
});