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: gate Brain Notes vault add/repoint and enforce .md-only note CRUD (#9007)

[._.]/ Adam Eivy76db79fcb161
diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.js
index b7660d17e6..65ce317fa7 100644
--- a/server/lib/hostControlRoutes.js
+++ b/server/lib/hostControlRoutes.js
@@ -38,6 +38,8 @@
* or self-improvement on it queues CoS agents. Every other pipeline route
* generates text or media through an already-configured provider, the
* same as any AI feature; the caller never chooses what runs.
+ * - notes (#9007): vault add/repoint gated (chooses the host directory
+ * note CRUD reads/writes); note CRUD itself stays open.
* - browser: navigate uses the configured browser with its URL/IP guards;
* downloads DELETE removes data. Harness models/refresh re-reads the
* configured harness catalog; neither selects or installs an executable.
@@ -162,6 +164,12 @@ export const HOST_CONTROL_ROUTES = Object.freeze([
// runs repository-configured programs (hooks, fsmonitor) even for `status`.
'POST /api/git/*rest',
+ // Notes vaults: add/repoint chooses which host directory the note CRUD
+ // routes read from and write into (#9007). Note CRUD itself stays open —
+ // it is only safe once the root is operator-chosen.
+ 'POST /api/notes/vaults',
+ 'PUT /api/notes/vaults/:id',
+
// Restores replace records and machine-local execution policy; previews
// require the same operator authority as execution (#8772).
'POST /api/backup/restore',
diff --git a/server/lib/notesValidation.js b/server/lib/notesValidation.js
index 5920bb2bd7..b53147950b 100644
--- a/server/lib/notesValidation.js
+++ b/server/lib/notesValidation.js
@@ -5,6 +5,11 @@ import { isAbsolute } from 'path';
// Rejects:
// - any path segment equal to `..` or `.` (traversal) while still allowing
// filenames like `notes..md` or `v1..v2.md`
+// - any segment that STARTS with `.` (dot-directories/dotfiles such as
+// `.ssh`, `.claude`, `.git`, `.obsidian` — vault notes never live there,
+// and every note operation resolves relative to a caller-chosen vault
+// root, so this is the only thing standing between a registered vault and
+// the host's dotfiles) (#9007)
// - leading `/` (posix absolute)
// - Windows drive letters (e.g. `C:\foo`) and UNC paths (e.g. `\\host\share`)
// - backslashes anywhere (only forward slashes are valid separators)
@@ -16,10 +21,11 @@ const safeRelativePath = z.string().min(1).max(1000).refine(
if (/^[A-Za-z]:/.test(p)) return false; // blocks drive-letter prefixes
if (isAbsolute(p)) return false;
const segments = p.split('/');
- if (segments.some(seg => seg === '..' || seg === '.')) return false;
+ // `.startsWith('.')` alone already covers `.` and `..` traversal segments.
+ if (segments.some(seg => seg.startsWith('.'))) return false;
return true;
},
- { message: 'Path must be relative, forward-slash separated, and cannot contain .. segments' }
+ { message: 'Path must be relative, forward-slash separated, and cannot contain .. or dot-prefixed segments' }
);
export const vaultInputSchema = z.object({
diff --git a/server/lib/notesValidation.test.js b/server/lib/notesValidation.test.js
index c4f5d6fb65..b781d13a40 100644
--- a/server/lib/notesValidation.test.js
+++ b/server/lib/notesValidation.test.js
@@ -37,6 +37,14 @@ describe('notesValidation', () => {
expect(notePathSchema.safeParse({ path: 'folder/./file.md' }).success).toBe(false);
});
+ it('rejects dot-prefixed segments, including dot-directories (#9007)', () => {
+ expect(notePathSchema.safeParse({ path: '.ssh/id_ed25519' }).success).toBe(false);
+ expect(notePathSchema.safeParse({ path: '.ssh/authorized_keys' }).success).toBe(false);
+ expect(notePathSchema.safeParse({ path: '.claude/CLAUDE.md' }).success).toBe(false);
+ expect(notePathSchema.safeParse({ path: '.env' }).success).toBe(false);
+ expect(notePathSchema.safeParse({ path: 'folder/.git/config' }).success).toBe(false);
+ });
+
it('rejects posix absolute paths', () => {
expect(notePathSchema.safeParse({ path: '/etc/passwd' }).success).toBe(false);
});
diff --git a/server/routes/notesHostControl.test.js b/server/routes/notesHostControl.test.js
new file mode 100644
index 0000000000..4d23804bdf
--- /dev/null
+++ b/server/routes/notesHostControl.test.js
@@ -0,0 +1,94 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { request } from '../lib/testHelper.js';
+import { DEV_PROXY_CLIENT_ADDRESS_HEADER } from '../../lib/portosAuthCore.js';
+
+// The real authGate + hostControlRouteGate, pinned to a password-free install
+// so the developer's own settings cannot change what these cases observe.
+vi.mock('../services/auth.js', async (importOriginal) => ({
+ ...await importOriginal(),
+ isAuthEnabled: vi.fn().mockResolvedValue(false),
+}));
+
+const obsidian = vi.hoisted(() => ({
+ addVault: vi.fn(),
+ updateVault: vi.fn(),
+ getVaults: vi.fn(),
+ detectVaults: vi.fn(),
+}));
+vi.mock('../services/obsidian.js', () => obsidian);
+
+import { authGate, hostControlRouteGate } from '../services/authGate.js';
+import notesRoutes from './notes.js';
+
+// Mirrors the mount order server/index.js uses for this family.
+const buildGatedApp = (remoteAddress) => {
+ const app = express();
+ app.use((req, _res, next) => {
+ Object.defineProperty(req.socket, 'remoteAddress', { value: remoteAddress });
+ next();
+ });
+ app.use(authGate);
+ app.use(hostControlRouteGate);
+ app.use(express.json());
+ app.use('/api/notes', notesRoutes);
+ app.use(errorMiddleware);
+ return app;
+};
+
+const remote = () => buildGatedApp('192.0.2.10');
+const local = () => buildGatedApp('127.0.0.1');
+
+const call = (app, [method, path, body = {}], proxyClient) => {
+ const pending = request(app)[method](path);
+ if (proxyClient) pending.set(DEV_PROXY_CLIENT_ADDRESS_HEADER, proxyClient);
+ return pending.send(body);
+};
+
+const expectRefused = (response) => {
+ expect(response.status).toBe(403);
+ expect(response.body.code).toBe('HOST_CONTROL_FORBIDDEN');
+};
+
+describe('host-control gate on notes vault add/repoint (#9007)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ obsidian.addVault.mockResolvedValue({ id: 'v1', name: 'x', path: '/tmp/example-vault' });
+ obsidian.updateVault.mockResolvedValue({ id: 'v1', name: 'x', path: '/tmp/example-vault' });
+ });
+
+ it('refuses a remote password-free caller registering or repointing a vault, direct or proxied, with no vault persisted', async () => {
+ const writes = [
+ ['post', '/api/notes/vaults', { path: '/tmp/example-vault' }],
+ ['put', '/api/notes/vaults/v1', { path: '/tmp/other-vault' }],
+ ];
+ for (const write of writes) {
+ expectRefused(await call(remote(), write));
+ expectRefused(await call(local(), write, '192.0.2.10'));
+ }
+ expect(obsidian.addVault).not.toHaveBeenCalled();
+ expect(obsidian.updateVault).not.toHaveBeenCalled();
+ });
+
+ it('keeps a local caller, direct or through the dev proxy, able to add and repoint vaults', async () => {
+ for (const proxyClient of [undefined, '::ffff:127.0.0.1']) {
+ const app = local();
+ const add = await call(app, ['post', '/api/notes/vaults', { path: '/tmp/example-vault' }], proxyClient);
+ const update = await call(app, ['put', '/api/notes/vaults/v1', { path: '/tmp/other-vault' }], proxyClient);
+ expect(add.status).toBe(201);
+ expect(update.status).toBe(200);
+ }
+ expect(obsidian.addVault).toHaveBeenCalledTimes(2);
+ expect(obsidian.updateVault).toHaveBeenCalledTimes(2);
+ });
+
+ it('leaves read-only vault listing and detection open to a remote caller', async () => {
+ obsidian.getVaults.mockResolvedValue([]);
+ obsidian.detectVaults.mockResolvedValue([]);
+ const list = await request(remote()).get('/api/notes/vaults');
+ const detect = await request(remote()).get('/api/notes/detect');
+ expect(list.status).toBe(200);
+ expect(detect.status).toBe(200);
+ });
+});
diff --git a/server/services/obsidian.js b/server/services/obsidian.js
index 07e1d1944b..6be320c665 100644
--- a/server/services/obsidian.js
+++ b/server/services/obsidian.js
@@ -119,6 +119,17 @@ function resolveVaultPath(vault, notePath) {
return null;
}
+// A lexical-only containment check (`resolve`/`relative`, no `realpathSync`),
+// so a plainly out-of-vault path can be rejected BEFORE any directory is
+// created for it. `resolveVaultPath` above still runs afterward for the
+// symlink-aware check once the parent is known to exist.
+function isWithinVaultLexically(vault, notePath) {
+ const rootResolved = resolve(vault.path);
+ const fullPath = resolve(join(vault.path, notePath));
+ const rel = relative(rootResolved, fullPath);
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
+}
+
export async function getVaultById(id) {
const vaults = await getVaults();
return vaults.find(v => v.id === id) || null;
@@ -242,6 +253,9 @@ export async function getNote(vaultId, notePath, { includeBacklinks = true } = {
if (!fullPath) {
return { error: 'INVALID_PATH', message: 'Path traversal not allowed' };
}
+ if (extname(fullPath) !== '.md') {
+ return { error: 'INVALID_PATH', message: 'Only .md notes can be read' };
+ }
if (!existsSync(fullPath)) return { error: 'NOTE_NOT_FOUND' };
const content = await readNoteContent(fullPath);
@@ -289,6 +303,7 @@ export async function updateNote(vaultId, notePath, content, { force = false } =
const fullPath = resolveVaultPath(vault, notePath);
if (!fullPath) return { error: 'INVALID_PATH' };
+ if (extname(fullPath) !== '.md') return { error: 'INVALID_PATH' };
if (!existsSync(fullPath)) return { error: 'NOTE_NOT_FOUND' };
// Overwriting an EVICTED note would block exactly like reading one — measured,
@@ -375,6 +390,10 @@ export async function createNote(vaultId, notePath, content = '') {
if (!notePath.endsWith('.md')) notePath += '.md';
+ // Reject an out-of-vault path lexically BEFORE creating any directories —
+ // a rejected path must never leave directories behind on disk (#9007).
+ if (!isWithinVaultLexically(vault, notePath)) return { error: 'INVALID_PATH' };
+
// For a new file the target doesn't exist yet — resolveVaultPath realpaths
// the parent directory (which must exist) to still catch symlink escapes.
await ensureDir(dirname(join(vault.path, notePath)));
@@ -450,6 +469,7 @@ export async function deleteNote(vaultId, notePath) {
const fullPath = resolveVaultPath(vault, notePath);
if (!fullPath) return { error: 'INVALID_PATH' };
+ if (extname(fullPath) !== '.md') return { error: 'INVALID_PATH' };
if (!existsSync(fullPath)) return { error: 'NOTE_NOT_FOUND' };
// No dataless screen here, deliberately (#3713): `unlink` does NOT materialize
diff --git a/server/services/obsidian.test.js b/server/services/obsidian.test.js
index 1a9284d7df..aa5b511069 100644
--- a/server/services/obsidian.test.js
+++ b/server/services/obsidian.test.js
@@ -23,7 +23,7 @@ vi.mock('../lib/fileUtils.js', async () => {
return makePathsProxy(actual, { dataRoot: tempRoot });
});
-const { addVault, upsertNote, getNote } = await import('./obsidian.js');
+const { addVault, upsertNote, getNote, createNote, updateNote, deleteNote } = await import('./obsidian.js');
const VAULT_DIR = join(tempRoot, 'vault');
let vaultId;
@@ -75,3 +75,31 @@ describe('obsidian.upsertNote', () => {
expect(readFileSync(join(VAULT_DIR, 'keep.md'), 'utf-8')).toBe('original');
});
});
+
+// #9007: a remote caller that had already registered an existing host
+// directory as a vault (e.g. the home directory) must not be able to use note
+// CRUD to read/overwrite/delete anything outside the `.md` notes the scanner
+// itself recognizes.
+describe('obsidian note CRUD extension enforcement (#9007)', () => {
+ it('createNote rejects a fully out-of-vault path and creates no directories', async () => {
+ const result = await createNote(vaultId, '../newdir/escaped.md', 'x');
+ expect(result).toMatchObject({ error: 'INVALID_PATH' });
+ expect(existsSync(join(tempRoot, 'newdir'))).toBe(false);
+ });
+
+ it('getNote/updateNote/deleteNote refuse a non-.md path even when the file exists', async () => {
+ writeFileSync(join(VAULT_DIR, 'secret.env'), 'API_KEY=x');
+
+ expect(await getNote(vaultId, 'secret.env')).toMatchObject({ error: 'INVALID_PATH' });
+ expect(await updateNote(vaultId, 'secret.env', 'y')).toMatchObject({ error: 'INVALID_PATH' });
+ expect(await deleteNote(vaultId, 'secret.env')).toMatchObject({ error: 'INVALID_PATH' });
+
+ // Untouched: neither the read nor the write/delete attempt changed it.
+ expect(readFileSync(join(VAULT_DIR, 'secret.env'), 'utf-8')).toBe('API_KEY=x');
+ });
+
+ it('still serves ordinary .md notes after the extension check is added', async () => {
+ writeFileSync(join(VAULT_DIR, 'ok.md'), 'hello');
+ expect(await getNote(vaultId, 'ok.md')).toMatchObject({ content: 'hello' });
+ });
+});