Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): refuse symlinked folder frontmatter.yml leaf (PRD-8469) (#4037)
omar-inkeep58df7e9236bc
diff --git a/.changeset/sec-folder-frontmatter-symlink-leaf.md b/.changeset/sec-folder-frontmatter-symlink-leaf.mdnew file mode 100644index 000000000..020670e6e--- /dev/null+++ b/.changeset/sec-folder-frontmatter-symlink-leaf.md@@ -0,0 +1,19 @@+---+'@inkeep/open-knowledge': patch+'@inkeep/open-knowledge-core': patch+'@inkeep/open-knowledge-server': patch+'@inkeep/open-knowledge-app': patch+'@inkeep/open-knowledge-desktop': patch+---++The folder-config, template, and folder Activity (`/api/history`) endpoints now refuse to read or write through symbolic links planted in a folder's `.ok/` directory. Previously, a maliciously committed symlink at `<folder>/.ok/frontmatter.yml` (arriving via `git clone`/pull of an untrusted branch) let `GET /api/folder-config` disclose any YAML file the server process could read (for example `~/.config/gh/hosts.yml` or `~/.kube/config`) as folder frontmatter, and one `PUT /api/folder-config` folded the link target's keys into the merge and replaced the link with a real, git-trackable file containing that foreign content. A symlink at `<folder>/.ok/templates/<name>.md` — or a symlinked `.ok` / `.ok/templates` directory reached by requesting a descendant folder — similarly let `GET /api/template` return the link target's raw bytes verbatim, and a symlinked `<folder>/.ok` directory aliased both endpoints into another directory. The seed/`ok init` path could also create a file outside the project by writing through a committed dangling symlink at a scaffolded leaf.++The server now:++- rejects a symlinked `<folder>/.ok` on the requested folder on every folder-config, template, and folder-history arm, and — on the template arms, reads AND writes — a symlinked `<folder>/.ok/templates` directory, a symlinked template leaf (`GET` refuses to read through it; `PUT`/import refuse to write through it), and a symlinked ancestor `.ok`/`.ok/templates` on the fetch-by-name walk, all with `urn:ok:error:symlink-refused`. The folder-config arms degrade instead of rejecting for the template menu: a symlinked `.ok/templates` on the requested folder (wherever it points, dangling included), or a symlinked `.ok`/`.ok/templates` on any ancestor it inherits from, is skipped by the menu and reported by `GET /api/folder-config` via `warnings` + `warningCodes` (`templates-symlink-refused`, or `templates-unverifiable` when its `lstat` fails with anything but `ENOTDIR`; a non-directory `.ok` or `.ok/templates`, on this folder or an ancestor, provably holds no templates and produces no `templates-*` code);+- reports a symlinked, malformed, or uninspectable `frontmatter.yml` in `GET /api/folder-config` via `warnings` + `warningCodes` (`symlink-refused` / `malformed-yaml` / `unverifiable`, with `frontmatter_local: null`) while the rest of the folder payload keeps working, and treats such a leaf — or a symlinked containing `.ok` — as absent in folder-metadata enrichment and template-menu enumeration;+- writes scaffolded files with `O_EXCL`, so a committed dangling symlink at a seeded leaf fails rather than writing through;+- degrades instead of erroring on the folder-config and folder Activity arms for three shapes the path gate used to reject: a folder's own `.ok/templates` link that resolves outside the content root (was 400 `path-escape`), a regular file named `.ok`, and a `.ok` directory the server cannot search (both were 500). All three now answer 200 on `GET /api/folder-config` and on `GET /api/history?folder=`. `GET /api/folder-config` names what it dropped in `warnings` + `warningCodes` — `templates-symlink-refused` for the first, `unverifiable` for the second, `templates-unverifiable` + `unverifiable` for the third; `GET /api/history?folder=` has no `warnings` field, so it simply answers. `PUT /api/folder-config` still fails a folder whose `.ok` is a regular file or is unsearchable, now from the write itself rather than path validation; it no longer rejects a folder whose own `.ok/templates` resolves outside the content root, since the write never reads or writes that path. Those arms no longer run the `.ok/templates` containment check: the unconditional check on `<folder>/.ok` already covers every escape through an ancestor or `.ok` itself, and a symlinked `.ok/templates` is refused by identity in `collectFromFolder` before anything under it is enumerated. The template arms keep both checks;+- returns 500 (carrying the errno) from `POST /api/template` (move) when an ancestor `.ok`/`.ok/templates` on the source folder's walk cannot be inspected, matching `GET /api/template`, where it previously fell through to a misleading 404 `template-not-found`.++This is a blanket refusal of symlinks at `.ok` artifact paths on the HTTP plane, broader than the earlier escaping-symlink fixes: an *in-root* `.ok` symlink is refused too, because the folder-config write merges and rewrites the leaf in place. If a folder's properties, its template picker, or its Activity feed stop resolving after upgrading, replace the symlink under that folder's `.ok/` (the `frontmatter.yml` leaf, the `.ok` or `templates` directory, or a template file) with a regular file.diff --git a/docs/content/advanced/folders-and-templates.mdx b/docs/content/advanced/folders-and-templates.mdxindex c2e8d446b..a352641fb 100644--- a/docs/content/advanced/folders-and-templates.mdx+++ b/docs/content/advanced/folders-and-templates.mdx@@ -138,7 +138,20 @@ You never have to edit these files by hand (the folder overview page is the fron- A folder's own properties live in `<folder>/.ok/frontmatter.yml` (open-shape: any keys; `title` / `description` / `tags` are the conventional ones).- Templates live in `<folder>/.ok/templates/<name>.md`.-A folder only gets a `.ok/` directory once you give it a description or its first template; folders with nothing special stay plain. See the [Configuration reference](/docs/reference/configuration#folder-properties) for the file formats, and the [MCP reference](/docs/reference/mcp) for the `write` and `edit` tools (with `folder` and `template` targets) that set the same things from an AI agent.+A folder only gets a `.ok/` directory once you give it a description or its first template; folders with nothing special stay plain. `<folder>/.ok` and `<folder>/.ok/templates` must be real directories, and `frontmatter.yml` and each template real files.++Only one malformation stops the page from loading: a symlink at the folder's own `.ok`. Everything else still loads and shows less — though editing properties can still fail where the table says so:++| What is wrong | What the folder loses |+|---|---|+| A symlink at `.ok/templates` — on this folder or on an ancestor it inherits from, wherever it points and whether or not its target exists — or at an ancestor's `.ok` | That directory's templates, for this folder and every folder inheriting from it. Properties keep working, and the response warnings name the directory. |+| A symlink at `frontmatter.yml` | Only this folder's properties; the warnings name it. Saving a property edit also fails until you replace it. |+| `frontmatter.yml` is a real file but is not valid YAML | Only this folder's properties; the warnings name it. Saving a property edit also fails until you fix the syntax. |+| A symlink at a single template | Only that template. |+| `.ok` is a plain file, or a directory the server cannot read — on this folder or on an ancestor it inherits from | If it is this folder's, its properties and its own templates, and saving a property edit here fails until you fix it; if an ancestor's, that ancestor's templates for every folder inheriting from it, while this folder's own properties keep saving. Templates from unaffected ancestors still resolve. |+| `.ok/templates` is a plain file, or a directory the server cannot read — on this folder or on an ancestor it inherits from | That directory's templates, for this folder or for every folder inheriting from the affected ancestor. |++Those last two rows may drop templates with nothing in the warnings, so a folder that quietly loses templates — its own or an inherited set — is the signal to check `.ok` and `.ok/templates` on that folder and on every ancestor above it. To restore what broke: replace a symlink or a plain file with a real directory or file, copying in whatever the link pointed at if you want that content back; if the directory is already there, restore read access for the OpenKnowledge process rather than replacing it. See the [Configuration reference](/docs/reference/configuration#folder-properties) for the file formats, and the [MCP reference](/docs/reference/mcp) for the `write` and `edit` tools (with `folder` and `template` targets) that set the same things from an AI agent.## See alsodiff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdxindex 785ffed19..22cb220df 100644--- a/docs/content/features/editor.mdx+++ b/docs/content/features/editor.mdx@@ -170,7 +170,7 @@ Right-click anywhere in the sidebar to get a context-aware menu. Three shapes shItems that depend on the desktop app (revealing in your file manager, Delete via the OS trash) are hidden in the web build. Asset rows (images, PDFs, other non-markdown files) suppress Open with AI, Share, Duplicate, and Hide; they keep Reveal, Copy Path, Rename, and Delete.-Expand all and Collapse all only appear when they have work to do: Expand all is hidden when no folder is collapsed; Collapse all is hidden when no folder is expanded. New from template appears only when templates are available for the target folder, and Share only when the project has a GitHub remote.+Expand all and Collapse all only appear when they have work to do: Expand all is hidden when no folder is collapsed; Collapse all is hidden when no folder is expanded. New from template appears when templates are available for the target folder, and also whenever its folder config has not loaded — if the load failed, the item opens to a disabled "Couldn't load templates" row. A symlink, a plain file, or an unreadable directory under `.ok/` can drop a folder's templates (hiding the item); a symlink at the folder's own `.ok` fails its config load (the disabled row) — see [where templates are stored](../advanced/folders-and-templates.mdx#where-its-stored). Share appears only when the project has a GitHub remote.### Creating files and foldersdiff --git a/packages/app/src/hooks/use-folder-config.ts b/packages/app/src/hooks/use-folder-config.tsindex 8f38bf3f2..2eb16cf5a 100644--- a/packages/app/src/hooks/use-folder-config.ts+++ b/packages/app/src/hooks/use-folder-config.ts@@ -1,4 +1,8 @@-import { type TemplatesListEntry, TemplatesListSuccessSchema } from '@inkeep/open-knowledge-core';+import {+ type FolderConfigWarningCode,+ type TemplatesListEntry,+ TemplatesListSuccessSchema,+} from '@inkeep/open-knowledge-core';import { t } from '@lingui/core/macro';import { useEffect, useState } from 'react';import { subscribeToTemplatesChanged } from '@/lib/documents-events';@@ -21,6 +25,8 @@ interface FolderConfig {export interface FolderConfigSnapshot {folder: FolderConfig;frontmatterLocal: Record<string, unknown> | null;+ warningCodes: FolderConfigWarningCode[];+ warnings: string[];}export interface TemplateMenuEntry {@@ -72,6 +78,8 @@ export function useFolderConfig(folderPath: string | null): FolderConfigHandle {return r.json() as Promise<{folder: FolderConfig;frontmatter_local?: Record<string, unknown> | null;+ warnings?: string[];+ warningCodes?: FolderConfigWarningCode[];}>;}).then((payload) => {@@ -85,6 +93,8 @@ export function useFolderConfig(folderPath: string | null): FolderConfigHandle {data: {folder: payload.folder,frontmatterLocal: payload.frontmatter_local ?? null,+ warnings: payload.warnings ?? [],+ warningCodes: payload.warningCodes ?? [],},});})diff --git a/packages/core/src/handoff/urn-ipc-registry.ts b/packages/core/src/handoff/urn-ipc-registry.tsindex 66191c1c5..f8a2dcfa3 100644--- a/packages/core/src/handoff/urn-ipc-registry.ts+++ b/packages/core/src/handoff/urn-ipc-registry.ts@@ -36,6 +36,7 @@ export const URN_HTTP_ONLY: ReadonlySet<ProblemType> = new Set<ProblemType>(['urn:ok:error:payload-too-large','urn:ok:error:request-timeout','urn:ok:error:internal-server-error',+ 'urn:ok:error:symlink-refused','urn:ok:error:derived-index-unavailable','urn:ok:error:loopback-required','urn:ok:error:invalid-origin',diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex dd7735a81..36fe0949e 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -1207,12 +1207,14 @@ export {type EmbedProbeEntryWire,type EmptyRequest,EmptyRequestSchema,+ FOLDER_CONFIG_WARNING_CODES,type FolderConfigGetSuccess,FolderConfigGetSuccessSchema,type FolderConfigPutRequest,FolderConfigPutRequestSchema,type FolderConfigPutSuccess,FolderConfigPutSuccessSchema,+ type FolderConfigWarningCode,type ForwardLinkDocEntry,ForwardLinkDocEntrySchema,type ForwardLinkEntry,diff --git a/packages/core/src/schemas/api/_envelope.ts b/packages/core/src/schemas/api/_envelope.tsindex 104427d34..5f8b17373 100644--- a/packages/core/src/schemas/api/_envelope.ts+++ b/packages/core/src/schemas/api/_envelope.ts@@ -54,6 +54,7 @@ export const ProblemTypeSchema = z.enum(['urn:ok:error:storage-error','urn:ok:error:no-file-received','urn:ok:error:path-escape',+ 'urn:ok:error:symlink-refused','urn:ok:error:method-not-allowed','urn:ok:error:invalid-request','urn:ok:error:payload-too-large',diff --git a/packages/core/src/schemas/api/tags-search.ts b/packages/core/src/schemas/api/tags-search.tsindex 55ba604f7..07ae85434 100644--- a/packages/core/src/schemas/api/tags-search.ts+++ b/packages/core/src/schemas/api/tags-search.ts@@ -42,10 +42,27 @@ export const TagsForNameSuccessSchema = z.loose() satisfies StandardSchemaV1;export type TagsForNameSuccess = z.infer<typeof TagsForNameSuccessSchema>;+export const FOLDER_CONFIG_WARNING_CODES = [+ 'symlink-refused',+ 'malformed-yaml',+ 'unverifiable',+ 'templates-symlink-refused',+ 'templates-unverifiable',+] as const;+export type FolderConfigWarningCode = (typeof FOLDER_CONFIG_WARNING_CODES)[number];+export const FolderConfigGetSuccessSchema = z.object({folder: z.unknown(),frontmatter_local: z.record(z.string(), z.unknown()).nullable(),+ warnings: z.array(z.string()).optional().meta({+ description:+ 'Non-fatal degradations of this response, one per entry; the field each affects is absent, null, or incomplete — the aligned `warningCodes` entry names which field and how.',+ }),+ warningCodes: z.array(z.enum(FOLDER_CONFIG_WARNING_CODES)).optional().meta({+ description:+ "Machine-readable codes aligned 1:1 with `warnings`; switch on these, never on the English. `symlink-refused` / `malformed-yaml` / `unverifiable`: this folder's own `.ok/frontmatter.yml` (a symlink, malformed YAML, or an lstat failure) — `frontmatter_local` is null. `templates-symlink-refused` / `templates-unverifiable`: the `.ok/templates` directory on this folder, or a `.ok` or `.ok/templates` directory on an ancestor it inherits from — a symlink (wherever it points, dangling included), or a non-ENOTDIR `lstat` failure — `folder.templates_available` omits that directory's templates and may still list others. A non-directory `.ok` / `.ok/templates` (ENOTDIR) is treated as empty and yields no `templates-*` code. This folder's own symlinked `.ok` is a 400, never a warning.",+ }),}).loose() satisfies StandardSchemaV1;export type FolderConfigGetSuccess = z.infer<typeof FolderConfigGetSuccessSchema>;diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 70112b288..3c68c3c74 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -158,6 +158,7 @@ import {} from './frontmatter-malformed-error.ts';import {assertNoSymlinkEscape,+ checkSymlinkLeaf,isContainmentRejection,PathContainmentError,} from './fs-safety.ts';@@ -5566,8 +5567,9 @@ export function createApiExtension(function validateFolderRel(raw: string,res: ServerResponse,- label: 'path' | 'folder' = 'path',- handler = 'folder-config',+ label: 'path' | 'folder',+ handler: string,+ components: 'ok' | 'ok-and-templates',): { folderRel: string; resolvedContentDir: string } | null {const folderRel = raw.replace(/^\.\//, '').replace(/^\/+/, '').replace(/\/+$/, '');if (folderRel.split('/').some((seg) => seg === '..') || raw.startsWith('/')) {@@ -5592,10 +5594,57 @@ export function createApiExtension(});return null;}+ /* STOP: the escape asserts below admit an IN-ROOT symlinked+ `<folder>/.ok` OR `<folder>/.ok/templates` (their realpaths stay+ inside the content root), which would alias every folder-config and+ template arm — including the WRITE arms (`applyTemplateWrite`'s+ rename lands wherever `templates` points; `applyTemplateDelete`+ unlinks through it) — into another directory. Refuse by identity —+ same posture as `initContent`'s `assertNotSymlink` on the root `.ok/`+ and the templates resolver's gates. The `templates` component is+ checked only for the template arms (`components: 'ok-and-templates'`).+ The folder-config arms DO reach `.ok/templates` — through+ `collectFromFolder` (content/templates-resolver.ts), which gates it by+ identity and degrades, skipping a symlinked templates dir (and+ reporting it via `onRefused`) rather than failing the folder payload.+ Do not hard-fail here for those arms or the per-field degrade contract+ breaks; do not delete the resolver-side gate, which is what makes the+ degrade safe. The same unconditional `.ok` identity check also gates+ the folder-history arm (http/history-routes.ts) for a uniform+ refuse-by-identity posture, even though that arm only uses the path as+ a `git log` pathspec and the aliasing risk above does not apply there.+ Only an actual+ symlink short-circuits here; a non-ENOENT lstat failure+ (`unverifiable`) is left to the `assertNoSymlinkEscape` asserts below,+ which classify it (ELOOP → path-escape, other errnos → 500) rather+ than mislabel a non-symlink path as a symlink. */+ const okDir = resolve(candidateAbs, '.ok');+ if (checkSymlinkLeaf(okDir).kind === 'symlink') {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:symlink-refused',+ `${folderRel || '.'}/.ok is a symlink — refusing to operate through it. Replace the symlink with a real file or directory and retry.`,+ { handler, detail: folderRel || '.' },+ );+ return null;+ }+ const okTemplatesDir = resolve(candidateAbs, '.ok', 'templates');+ if (components === 'ok-and-templates' && checkSymlinkLeaf(okTemplatesDir).kind === 'symlink') {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:symlink-refused',+ `${folderRel || '.'}/.ok/templates is a symlink — refusing to operate through it. Replace the symlink with a real file or directory and retry.`,+ { handler, detail: folderRel || '.' },+ );+ return null;+ }try {- const okDir = resolve(candidateAbs, '.ok');assertNoSymlinkEscape(okDir, resolvedContentDir);- assertNoSymlinkEscape(resolve(okDir, 'templates'), resolvedContentDir);+ if (components === 'ok-and-templates') {+ assertNoSymlinkEscape(okTemplatesDir, resolvedContentDir);+ }} catch (err) {if (isContainmentRejection(err)) {errorResponse(res, 400, 'urn:ok:error:path-escape', 'Path escapes content directory.', {diff --git a/packages/server/src/api-folder-config.test.ts b/packages/server/src/api-folder-config.test.tsindex ea3808005..3106d14d4 100644--- a/packages/server/src/api-folder-config.test.ts+++ b/packages/server/src/api-folder-config.test.ts@@ -1,4 +1,14 @@-import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import {+ chmodSync,+ existsSync,+ lstatSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from 'node:fs';import { readFile } from 'node:fs/promises';import type { IncomingMessage, ServerResponse } from 'node:http';import { tmpdir } from 'node:os';@@ -93,6 +103,8 @@ describe('GET/PUT /api/folder-config', () => {};expect(typeof body.folder).toBe('object');expect(body.frontmatter_local).toEqual({ status: 'active', owner: 'omar' });+ expect(body).not.toHaveProperty('warningCodes');+ expect(body).not.toHaveProperty('warnings');});test('GET reports null frontmatter_local when the sidecar is absent', async () => {@@ -121,7 +133,12 @@ describe('GET/PUT /api/folder-config', () => {const broken = await dispatch(ext, '/api/folder-config?path=broken', 'GET');expect(broken.status).toBe(200);- expect(JSON.parse(broken.body).frontmatter_local).toBeNull();+ const brokenBody = JSON.parse(broken.body) as {+ frontmatter_local: Record<string, unknown> | null;+ warningCodes?: string[];+ };+ expect(brokenBody.frontmatter_local).toBeNull();+ expect(brokenBody.warningCodes).toEqual(['malformed-yaml']);});test('GET rejects traversal and absolute paths as not project-root-relative', async () => {@@ -142,6 +159,304 @@ describe('GET/PUT /api/folder-config', () => {expect(absolute.status).toBe(400);});+ test('GET degrades a symlinked frontmatter.yml leaf: null field + signal, no leak, folder meta intact', async () => {+ const secret = join(tmpDir, 'gh-hosts.yml');+ writeFileSync(secret, 'oauth_token: leak-me-not\n');+ mkdirSync(join(contentDir, 'linked', '.ok'), { recursive: true });+ symlinkSync(secret, join(contentDir, 'linked', '.ok', 'frontmatter.yml'));+ const ext = buildExt();+ const captured = await dispatch(ext, '/api/folder-config?path=linked', 'GET');+ expect(captured.status).toBe(200);+ const body = JSON.parse(captured.body) as {+ folder: Record<string, unknown>;+ frontmatter_local: Record<string, unknown> | null;+ warningCodes?: string[];+ };+ expect(body.frontmatter_local).toBeNull();+ expect(body.warningCodes).toEqual(['symlink-refused']);+ expect(typeof body.folder).toBe('object');+ expect(captured.body).not.toContain('leak-me-not');+ });++ test('GET degrades a symlinked frontmatter.yml leaf even when the target stays in-root', async () => {+ mkdirSync(join(contentDir, '.git'), { recursive: true });+ writeFileSync(join(contentDir, '.git', 'config'), 'password: in-root-secret\n');+ mkdirSync(join(contentDir, 'inroot', '.ok'), { recursive: true });+ symlinkSync('../../.git/config', join(contentDir, 'inroot', '.ok', 'frontmatter.yml'));+ const ext = buildExt();+ const captured = await dispatch(ext, '/api/folder-config?path=inroot', 'GET');+ expect(captured.status).toBe(200);+ const body = JSON.parse(captured.body) as {+ frontmatter_local: Record<string, unknown> | null;+ warningCodes?: string[];+ };+ expect(body.frontmatter_local).toBeNull();+ expect(body.warningCodes).toEqual(['symlink-refused']);+ expect(captured.body).not.toContain('in-root-secret');+ });++ test('GET refuses an in-root symlinked .ok directory outright (aliasing bypass)', async () => {+ mkdirSync(join(contentDir, 'secretdir'), { recursive: true });+ writeFileSync(join(contentDir, 'secretdir', 'frontmatter.yml'), 'hidden: aliased-secret\n');+ mkdirSync(join(contentDir, 'aliased'), { recursive: true });+ symlinkSync('../secretdir', join(contentDir, 'aliased', '.ok'), 'dir');+ const ext = buildExt();+ const captured = await dispatch(ext, '/api/folder-config?path=aliased', 'GET');+ expect(captured.status).toBe(400);+ expect(JSON.parse(captured.body).type).toBe('urn:ok:error:symlink-refused');+ expect(captured.body).not.toContain('aliased-secret');+ });++ test('PUT refuses a symlinked frontmatter.yml leaf and does not materialize it', async () => {+ const secret = join(tmpDir, 'kube-config.yml');+ writeFileSync(secret, 'token: hush\n');+ mkdirSync(join(contentDir, 'linkput', '.ok'), { recursive: true });+ const leaf = join(contentDir, 'linkput', '.ok', 'frontmatter.yml');+ symlinkSync(secret, leaf);+ const ext = buildExt();+ const captured = await dispatch(ext, '/api/folder-config', 'PUT', {+ path: 'linkput',+ frontmatter: { status: 'draft' },+ });+ expect(captured.status).toBe(400);+ expect(JSON.parse(captured.body).type).toBe('urn:ok:error:symlink-refused');+ expect(lstatSync(leaf).isSymbolicLink()).toBe(true);+ expect(readFileSync(secret, 'utf-8')).toBe('token: hush\n');+ });++ test('PUT refuses an in-root symlinked leaf (leaf identity, not containment)', async () => {+ mkdirSync(join(contentDir, '.git'), { recursive: true });+ writeFileSync(join(contentDir, '.git', 'config'), 'password: put-in-root\n');+ mkdirSync(join(contentDir, 'inrootput', '.ok'), { recursive: true });+ const leaf = join(contentDir, 'inrootput', '.ok', 'frontmatter.yml');+ symlinkSync('../../.git/config', leaf);+ const ext = buildExt();+ const captured = await dispatch(ext, '/api/folder-config', 'PUT', {+ path: 'inrootput',+ frontmatter: { status: 'draft' },+ });+ expect(captured.status).toBe(400);+ expect(JSON.parse(captured.body).type).toBe('urn:ok:error:symlink-refused');+ expect(lstatSync(leaf).isSymbolicLink()).toBe(true);+ expect(readFileSync(join(contentDir, '.git', 'config'), 'utf-8')).toBe(+ 'password: put-in-root\n',+ );+ });++ test('GET degrades a requested folder whose .ok/templates symlinks OUT of the content root (same as in-root)', async () => {+ const outside = join(tmpDir, 'outside-tpl');+ mkdirSync(outside);+ writeFileSync(join(outside, 'leak.md'), '---\ntitle: Leak\n---\n');+ mkdirSync(join(contentDir, 'esc', '.ok'), { recursive: true });+ symlinkSync(outside, join(contentDir, 'esc', '.ok', 'templates'), 'dir');+ const get = await dispatch(buildExt(), '/api/folder-config?path=esc', 'GET');+ expect(get.status).toBe(200);+ const body = JSON.parse(get.body) as {+ folder: { templates_available?: Array<{ name: string }> };+ warningCodes?: string[];+ };+ expect(body.folder.templates_available ?? []).toEqual([]);+ expect(body.warningCodes).toEqual(['templates-symlink-refused']);+ expect(get.body).not.toContain('leak');+ });++ test('GET no longer 500s when the requested folder has a regular FILE named .ok', async () => {+ mkdirSync(join(contentDir, 'flatok'), { recursive: true });+ writeFileSync(join(contentDir, 'flatok', '.ok'), 'not a directory\n');+ const get = await dispatch(buildExt(), '/api/folder-config?path=flatok', 'GET');+ expect(get.status).toBe(200);+ expect(JSON.parse(get.body).warningCodes).toEqual(['unverifiable']);+ });++ test.runIf(process.getuid?.() !== 0)(+ 'GET degrades an uninspectable OWN .ok (EACCES) instead of 500ing, templates from the root still resolve',+ async () => {+ const ownOk = join(contentDir, 'unvown', '.ok');+ mkdirSync(join(ownOk, 'templates'), { recursive: true });+ mkdirSync(join(contentDir, '.ok', 'templates'), { recursive: true });+ writeFileSync(join(contentDir, '.ok', 'templates', 'global.md'), '---\ntitle: Global\n---\n');+ chmodSync(ownOk, 0o000);+ try {+ const get = await dispatch(buildExt(), '/api/folder-config?path=unvown', 'GET');+ expect(get.status).toBe(200);+ const body = JSON.parse(get.body) as {+ folder: { templates_available?: Array<{ name: string }> };+ warningCodes?: string[];+ };+ expect((body.folder.templates_available ?? []).map((t) => t.name)).toEqual(['global']);+ expect(body.warningCodes).toEqual(['templates-unverifiable', 'unverifiable']);+ } finally {+ chmodSync(ownOk, 0o755);+ }+ },+ );++ test('GET degrades a DANGLING .ok/templates link (what a clone of a committed link produces)', async () => {+ mkdirSync(join(contentDir, 'dangle', '.ok'), { recursive: true });+ symlinkSync(+ '/nonexistent/attacker/templates',+ join(contentDir, 'dangle', '.ok', 'templates'),+ 'dir',+ );+ const get = await dispatch(buildExt(), '/api/folder-config?path=dangle', 'GET');+ expect(get.status).toBe(200);+ const body = JSON.parse(get.body) as { warningCodes?: string[]; warnings?: string[] };+ expect(body.warningCodes).toEqual(['templates-symlink-refused']);+ expect(body.warnings?.[0]).toContain('dangle/.ok/templates is a symlink');+ });++ test('an in-root symlinked .ok/templates refuses the template arms but degrades folder-config', async () => {+ mkdirSync(join(contentDir, 'agentsdir'), { recursive: true });+ writeFileSync(join(contentDir, 'agentsdir', 'keep.md'), '# keep me\n');+ mkdirSync(join(contentDir, 'aliased3', '.ok'), { recursive: true });+ symlinkSync('../../agentsdir', join(contentDir, 'aliased3', '.ok', 'templates'), 'dir');+ mkdirSync(join(contentDir, '.ok', 'templates'), { recursive: true });+ writeFileSync(join(contentDir, '.ok', 'templates', 'global.md'), '---\ntitle: Global\n---\n');+ const ext = buildExt();++ const get = await dispatch(ext, '/api/folder-config?path=aliased3', 'GET');+ expect(get.status).toBe(200);+ const getBody = JSON.parse(get.body) as {+ folder: { templates_available?: Array<{ name: string }> };+ warnings?: string[];+ warningCodes?: string[];+ };+ expect((getBody.folder.templates_available ?? []).map((t) => t.name)).toEqual(['global']);+ expect(getBody.warningCodes).toEqual(['templates-symlink-refused']);+ expect(getBody.warnings).toEqual([+ 'aliased3/.ok/templates is a symlink — its templates are not enumerated. Replace the symlink with a real file or directory and retry.',+ ]);+ expect(get.body).not.toContain('keep.md');++ const put = await dispatch(ext, '/api/template', 'PUT', {+ folder: 'aliased3',+ name: 'planted',+ body: '# planted\n',+ frontmatter: { title: 'Planted' },+ });+ expect(put.status).toBe(400);+ expect(JSON.parse(put.body).type).toBe('urn:ok:error:symlink-refused');++ const del = await dispatch(ext, `/api/template?folder=aliased3&name=keep`, 'DELETE');+ expect(del.status).toBe(400);+ expect(JSON.parse(del.body).type).toBe('urn:ok:error:symlink-refused');+ });++ test('GET reports a symlinked ANCESTOR .ok/templates the folder would inherit from', async () => {+ mkdirSync(join(contentDir, 'agentsdir-anc'), { recursive: true });+ writeFileSync(join(contentDir, 'agentsdir-anc', 'keep.md'), '# keep me\n');+ mkdirSync(join(contentDir, 'anc', '.ok'), { recursive: true });+ mkdirSync(join(contentDir, 'anc', 'child'), { recursive: true });+ symlinkSync('../../agentsdir-anc', join(contentDir, 'anc', '.ok', 'templates'), 'dir');+ const ext = buildExt();++ mkdirSync(join(contentDir, '.ok', 'templates'), { recursive: true });+ writeFileSync(join(contentDir, '.ok', 'templates', 'global.md'), '---\ntitle: Global\n---\n');++ const get = await dispatch(ext, '/api/folder-config?path=anc/child', 'GET');+ expect(get.status).toBe(200);+ const getBody = JSON.parse(get.body) as {+ folder: { templates_available?: Array<{ name: string }> };+ warnings?: string[];+ warningCodes?: string[];+ };+ expect((getBody.folder.templates_available ?? []).map((t) => t.name)).toEqual(['global']);+ expect(getBody.warningCodes).toEqual(['templates-symlink-refused']);+ expect(getBody.warnings?.[0]).toContain('anc/.ok/templates is a symlink');+ expect(get.body).not.toContain('keep.md');+ });++ test('GET reports a symlinked ANCESTOR .ok (menu skips it) while the requested folder still resolves', async () => {+ mkdirSync(join(contentDir, 'agentsdir-ancok', 'templates'), { recursive: true });+ writeFileSync(join(contentDir, 'agentsdir-ancok', 'templates', 'keep.md'), '# keep me\n');+ mkdirSync(join(contentDir, 'ancok', 'child'), { recursive: true });+ symlinkSync('../agentsdir-ancok', join(contentDir, 'ancok', '.ok'), 'dir');+ const ext = buildExt();++ mkdirSync(join(contentDir, '.ok', 'templates'), { recursive: true });+ writeFileSync(join(contentDir, '.ok', 'templates', 'global.md'), '---\ntitle: Global\n---\n');++ const get = await dispatch(ext, '/api/folder-config?path=ancok/child', 'GET');+ expect(get.status).toBe(200);+ const getBody = JSON.parse(get.body) as {+ folder: { templates_available?: Array<{ name: string }> };+ warnings?: string[];+ warningCodes?: string[];+ };+ expect((getBody.folder.templates_available ?? []).map((t) => t.name)).toEqual(['global']);+ expect(getBody.warningCodes).toEqual(['templates-symlink-refused']);+ expect(getBody.warnings?.[0]).toContain('ancok/.ok is a symlink');+ expect(get.body).not.toContain('keep.md');+ });++ test.runIf(process.getuid?.() !== 0)(+ 'GET reports an ANCESTOR .ok/templates it cannot inspect as unverifiable, not as absent',+ async () => {+ const ancestorOk = join(contentDir, 'unv', '.ok');+ mkdirSync(join(ancestorOk, 'templates'), { recursive: true });+ mkdirSync(join(contentDir, 'unv', 'child'), { recursive: true });+ mkdirSync(join(contentDir, '.ok', 'templates'), { recursive: true });+ writeFileSync(join(contentDir, '.ok', 'templates', 'global.md'), '---\ntitle: Global\n---\n');+ chmodSync(ancestorOk, 0o000);+ try {+ const ext = buildExt();+ const get = await dispatch(ext, '/api/folder-config?path=unv/child', 'GET');+ expect(get.status).toBe(200);+ const getBody = JSON.parse(get.body) as {+ folder: { templates_available?: Array<{ name: string }> };+ warnings?: string[];+ warningCodes?: string[];+ };+ expect((getBody.folder.templates_available ?? []).map((t) => t.name)).toEqual(['global']);+ expect(getBody.warningCodes).toEqual(['templates-unverifiable']);+ expect(getBody.warnings?.[0]).toContain(+ 'unv/.ok/templates could not be inspected (EACCES)',+ );+ } finally {+ chmodSync(ancestorOk, 0o755);+ }+ },+ );++ test('template PUT refuses an in-root symlinked template LEAF before any write', async () => {+ mkdirSync(join(contentDir, '.claude'), { recursive: true });+ writeFileSync(join(contentDir, '.claude', 'CLAUDE.md'), '# victim agent definition\n');+ mkdirSync(join(contentDir, 'notes', '.ok', 'templates'), { recursive: true });+ const leaf = join(contentDir, 'notes', '.ok', 'templates', 'meeting.md');+ symlinkSync('../../../.claude/CLAUDE.md', leaf);+ const ext = buildExt();++ const put = await dispatch(ext, '/api/template', 'PUT', {+ folder: 'notes',+ name: 'meeting',+ body: '# overwritten\n',+ frontmatter: { title: 'Meeting' },+ });+ expect(put.status).toBe(400);+ expect(JSON.parse(put.body).type).toBe('urn:ok:error:symlink-refused');+ expect(lstatSync(leaf).isSymbolicLink()).toBe(true);+ expect(readFileSync(join(contentDir, '.claude', 'CLAUDE.md'), 'utf-8')).toBe(+ '# victim agent definition\n',+ );+ });++ test('PUT refuses an in-root symlinked .ok directory and writes nothing through it', async () => {+ mkdirSync(join(contentDir, 'secretdir2'), { recursive: true });+ writeFileSync(join(contentDir, 'secretdir2', 'frontmatter.yml'), 'existing: keep\n');+ mkdirSync(join(contentDir, 'aliased2'), { recursive: true });+ symlinkSync('../secretdir2', join(contentDir, 'aliased2', '.ok'), 'dir');+ const ext = buildExt();+ const captured = await dispatch(ext, '/api/folder-config', 'PUT', {+ path: 'aliased2',+ frontmatter: { status: 'draft' },+ });+ expect(captured.status).toBe(400);+ expect(JSON.parse(captured.body).type).toBe('urn:ok:error:symlink-refused');+ expect(readFileSync(join(contentDir, 'secretdir2', 'frontmatter.yml'), 'utf-8')).toBe(+ 'existing: keep\n',+ );+ });+test('PUT refuses a folder that symlinks out of the content root', async () => {const outside = join(tmpDir, 'outside');mkdirSync(outside);@@ -167,7 +482,7 @@ describe('GET/PUT /api/folder-config', () => {frontmatter: { status: 'draft' },});expect(captured.status).toBe(400);- expect(JSON.parse(captured.body).type).toBe('urn:ok:error:path-escape');+ expect(JSON.parse(captured.body).type).toBe('urn:ok:error:symlink-refused');expect(existsSync(join(outside, 'frontmatter.yml'))).toBe(false);});@@ -182,6 +497,36 @@ describe('GET/PUT /api/folder-config', () => {expect(JSON.parse(captured.body).type).toBe('urn:ok:error:internal-server-error');});+ test('PUT no longer rejects a folder whose own .ok/templates resolves outside the content root (the write never touches it)', async () => {+ const outside = join(tmpDir, 'outside-tpl-put');+ mkdirSync(outside);+ mkdirSync(join(contentDir, 'escput', '.ok'), { recursive: true });+ symlinkSync(outside, join(contentDir, 'escput', '.ok', 'templates'), 'dir');+ const put = await dispatch(buildExt(), '/api/folder-config', 'PUT', {+ path: 'escput',+ frontmatter: { status: 'draft' },+ });+ expect(put.status).toBe(200);+ expect(JSON.parse(put.body).applied).toEqual([+ { path: 'escput/.ok/frontmatter.yml', action: 'written' },+ ]);+ expect(readFileSync(join(contentDir, 'escput', '.ok', 'frontmatter.yml'), 'utf-8')).toContain(+ 'status: draft',+ );+ expect(existsSync(join(outside, 'frontmatter.yml'))).toBe(false);+ });++ test('PUT fails on a malformed frontmatter.yml and leaves it byte-identical', async () => {+ const fmPath = join(contentDir, 'broken', '.ok', 'frontmatter.yml');+ const before = readFileSync(fmPath, 'utf-8');+ const put = await dispatch(buildExt(), '/api/folder-config', 'PUT', {+ path: 'broken',+ frontmatter: { status: 'draft' },+ });+ expect(put.status).not.toBe(200);+ expect(readFileSync(fmPath, 'utf-8')).toBe(before);+ });+test('PUT writes the sidecar and reports written, then noop on an identical patch', async () => {const ext = buildExt();const first = await dispatch(ext, '/api/folder-config', 'PUT', {diff --git a/packages/server/src/api-folder-template-composition.test.ts b/packages/server/src/api-folder-template-composition.test.tsindex 9fe95a577..66f8d2a56 100644--- a/packages/server/src/api-folder-template-composition.test.ts+++ b/packages/server/src/api-folder-template-composition.test.ts@@ -1,4 +1,13 @@-import { existsSync, mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from 'node:fs';+import {+ chmodSync,+ existsSync,+ lstatSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ symlinkSync,+ writeFileSync,+} from 'node:fs';import { mkdtemp, rm } from 'node:fs/promises';import { tmpdir } from 'node:os';import { resolve } from 'node:path';@@ -104,10 +113,116 @@ describe('folder-template group over the composed listener — served natively',}),});expect(res.status).toBe(400);- expect(((await res.json()) as { type?: string }).type).toBe('urn:ok:error:path-escape');+ expect(((await res.json()) as { type?: string }).type).toBe('urn:ok:error:symlink-refused');expect(existsSync(resolve(outside, 'planted.md'))).toBe(false);});+ test('PUT /api/template refuses an IN-ROOT symlinked templates dir and writes nothing through it', async () => {+ mkdirSync(resolve(contentDir, 'inroot-target'), { recursive: true });+ mkdirSync(resolve(contentDir, 'tpl-inroot', '.ok'), { recursive: true });+ symlinkSync(+ '../../inroot-target',+ resolve(contentDir, 'tpl-inroot', '.ok', 'templates'),+ 'dir',+ );+ const res = await fetch(`http://127.0.0.1:${server.port}/api/template`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ folder: 'tpl-inroot',+ name: 'planted',+ body: 'body',+ frontmatter: { title: 'Planted' },+ }),+ });+ expect(res.status).toBe(400);+ expect(((await res.json()) as { type?: string }).type).toBe('urn:ok:error:symlink-refused');+ expect(existsSync(resolve(contentDir, 'inroot-target', 'planted.md'))).toBe(false);+ });++ test('PUT /api/template refuses an IN-ROOT symlinked template LEAF and leaves the target intact', async () => {+ mkdirSync(resolve(contentDir, '.claude'), { recursive: true });+ writeFileSync(resolve(contentDir, '.claude', 'CLAUDE.md'), '# victim\n', 'utf-8');+ mkdirSync(resolve(contentDir, 'tpl-leaf', '.ok', 'templates'), { recursive: true });+ const leaf = resolve(contentDir, 'tpl-leaf', '.ok', 'templates', 'meeting.md');+ symlinkSync('../../../.claude/CLAUDE.md', leaf);+ const res = await fetch(`http://127.0.0.1:${server.port}/api/template`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ folder: 'tpl-leaf',+ name: 'meeting',+ body: '# overwritten body',+ frontmatter: { title: 'Meeting' },+ }),+ });+ expect(res.status).toBe(400);+ expect(((await res.json()) as { type?: string }).type).toBe('urn:ok:error:symlink-refused');+ expect(lstatSync(leaf).isSymbolicLink()).toBe(true);+ expect(readFileSync(resolve(contentDir, '.claude', 'CLAUDE.md'), 'utf-8')).toBe('# victim\n');+ });++ test('DELETE /api/template refuses an IN-ROOT symlinked templates dir and unlinks nothing through it', async () => {+ mkdirSync(resolve(contentDir, 'del-target'), { recursive: true });+ const victim = resolve(contentDir, 'del-target', 'keep.md');+ writeFileSync(victim, '# keep me\n', 'utf-8');+ mkdirSync(resolve(contentDir, 'tpl-del', '.ok'), { recursive: true });+ symlinkSync('../../del-target', resolve(contentDir, 'tpl-del', '.ok', 'templates'), 'dir');+ const res = await fetch(+ `http://127.0.0.1:${server.port}/api/template?folder=tpl-del&name=keep`,+ { method: 'DELETE' },+ );+ expect(res.status).toBe(400);+ expect(((await res.json()) as { type?: string }).type).toBe('urn:ok:error:symlink-refused');+ expect(readFileSync(victim, 'utf-8')).toBe('# keep me\n');+ });++ test('POST /api/template/import refuses an IN-ROOT symlinked template LEAF and leaves the link and its target intact', async () => {+ mkdirSync(resolve(contentDir, '.agents'), { recursive: true });+ const victim = resolve(contentDir, '.agents', 'AGENTS.md');+ writeFileSync(victim, '# victim agent definition\n', 'utf-8');+ mkdirSync(resolve(contentDir, 'tpl-import', '.ok', 'templates'), { recursive: true });+ const leaf = resolve(contentDir, 'tpl-import', '.ok', 'templates', 'alpha.md');+ symlinkSync('../../../.agents/AGENTS.md', leaf);+ const res = await fetch(`http://127.0.0.1:${server.port}/api/template/import`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ sourcePath: 'alpha', targetFolder: 'tpl-import', name: 'alpha' }),+ });+ expect(res.status).toBe(400);+ expect(((await res.json()) as { type?: string }).type).toBe('urn:ok:error:symlink-refused');+ expect(lstatSync(leaf).isSymbolicLink()).toBe(true);+ expect(readFileSync(victim, 'utf-8')).toBe('# victim agent definition\n');+ });++ test.runIf(process.getuid?.() !== 0)(+ 'POST /api/template (move) surfaces an uninspectable ANCESTOR .ok/templates as 500, not 404',+ async () => {+ const ancestorOk = resolve(contentDir, 'mv-root', '.ok');+ mkdirSync(ancestorOk, { recursive: true });+ mkdirSync(resolve(contentDir, 'mv-root', 'child'), { recursive: true });+ chmodSync(ancestorOk, 0o000);+ try {+ const res = await fetch(`http://127.0.0.1:${server.port}/api/template`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ fromFolder: 'mv-root/child',+ fromName: 'ghost',+ toFolder: 'mv-root/child',+ toName: 'ghost-renamed',+ }),+ });+ expect(res.status).toBe(500);+ const body = (await res.json()) as { type?: string; detail?: string };+ expect(body.type).toBe('urn:ok:error:internal-server-error');+ expect(body.detail).toBe('EACCES');+ } finally {+ chmodSync(ancestorOk, 0o755);+ }+ },+ );+test('template/import refuses a schema-invalid body with 400 before any doc read', async () => {const res = await fetch(`http://127.0.0.1:${server.port}/api/template/import`, {method: 'POST',diff --git a/packages/server/src/api-history-composition.test.ts b/packages/server/src/api-history-composition.test.tsindex 3983c44db..e63ab5234 100644--- a/packages/server/src/api-history-composition.test.ts+++ b/packages/server/src/api-history-composition.test.ts@@ -1,4 +1,4 @@-import { mkdtempSync, writeFileSync } from 'node:fs';+import { chmodSync, mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from 'node:fs';import { mkdtemp, rm } from 'node:fs/promises';import { tmpdir } from 'node:os';import { resolve } from 'node:path';@@ -9,11 +9,12 @@ import { bootCompositionRig } from './composition-rig.test-helper.ts';const A_SHA = 'a'.repeat(40);let tmpRoot: string;+let contentDir: string;let server: BootedServer;beforeAll(async () => {tmpRoot = await mkdtemp(resolve(tmpdir(), 'ok-history-native-'));- const contentDir = mkdtempSync(resolve(tmpRoot, 'content-'));+ contentDir = mkdtempSync(resolve(tmpRoot, 'content-'));writeFileSync(resolve(contentDir, 'alpha.md'), '# Alpha\n\nBody.\n', 'utf-8');server = await bootCompositionRig(contentDir);await server.ready;@@ -51,6 +52,55 @@ describe('history group over the composed listener — served natively', () => {expect(res.status).toBe(404);});+ test('the folder arm (?folder=) serves a 200 timeline for a plain folder', async () => {+ mkdirSync(resolve(contentDir, 'plain-folder'), { recursive: true });+ const res = await fetch(`http://127.0.0.1:${server.port}/api/history?folder=plain-folder`);+ expect(res.status).toBe(200);+ expect(res.headers.get('content-type')).toBe('application/json');+ });++ test('the folder arm refuses a folder whose own .ok is a symlink (400 symlink-refused)', async () => {+ mkdirSync(resolve(contentDir, 'hist-target', 'templates'), { recursive: true });+ mkdirSync(resolve(contentDir, 'hist-aliased'), { recursive: true });+ symlinkSync('../hist-target', resolve(contentDir, 'hist-aliased', '.ok'), 'dir');+ const res = await fetch(`http://127.0.0.1:${server.port}/api/history?folder=hist-aliased`);+ expect(res.status).toBe(400);+ expect(((await res.json()) as { type?: string }).type).toBe('urn:ok:error:symlink-refused');+ });++ test('the folder arm answers 200 for a folder with a regular FILE named .ok (no templates gate here)', async () => {+ mkdirSync(resolve(contentDir, 'hist-flatok'), { recursive: true });+ writeFileSync(resolve(contentDir, 'hist-flatok', '.ok'), 'not a directory\n', 'utf-8');+ const res = await fetch(`http://127.0.0.1:${server.port}/api/history?folder=hist-flatok`);+ expect(res.status).toBe(200);+ });++ test.runIf(process.getuid?.() !== 0)(+ 'the folder arm answers 200 for a folder whose .ok directory cannot be searched',+ async () => {+ const ownOk = resolve(contentDir, 'hist-unsearchable', '.ok');+ mkdirSync(ownOk, { recursive: true });+ chmodSync(ownOk, 0o000);+ try {+ const res = await fetch(+ `http://127.0.0.1:${server.port}/api/history?folder=hist-unsearchable`,+ );+ expect(res.status).toBe(200);+ } finally {+ chmodSync(ownOk, 0o755);+ }+ },+ );++ test('the folder arm answers 200 for an own .ok/templates link resolving outside the content root', async () => {+ const outside = resolve(tmpRoot, 'hist-outside-templates');+ mkdirSync(outside, { recursive: true });+ mkdirSync(resolve(contentDir, 'hist-esc', '.ok'), { recursive: true });+ symlinkSync(outside, resolve(contentDir, 'hist-esc', '.ok', 'templates'), 'dir');+ const res = await fetch(`http://127.0.0.1:${server.port}/api/history?folder=hist-esc`);+ expect(res.status).toBe(200);+ });+test('both chained groups answer on one server (multi-group dispatch)', async () => {const linkGraph = await fetch(`http://127.0.0.1:${server.port}/api/backlinks?docName=alpha`);expect(linkGraph.status).toBe(200);diff --git a/packages/server/src/api-template-get.test.ts b/packages/server/src/api-template-get.test.tsindex 22893cc3b..9af6ead23 100644--- a/packages/server/src/api-template-get.test.ts+++ b/packages/server/src/api-template-get.test.ts@@ -1,4 +1,4 @@-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';import type { IncomingMessage, ServerResponse } from 'node:http';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -32,7 +32,11 @@ function makeRes(): { res: ServerResponse; captured: CapturedResponse } {return { res, captured };}-async function getTemplate(contentDir: string, name: string): Promise<CapturedResponse> {+async function getTemplate(+ contentDir: string,+ name: string,+ folder?: string,+): Promise<CapturedResponse> {const ext = createApiExtension({hocuspocus: {} as unknown as Parameters<typeof createApiExtension>[0]['hocuspocus'],sessionManager: {} as unknown as Parameters<typeof createApiExtension>[0]['sessionManager'],@@ -40,7 +44,8 @@ async function getTemplate(contentDir: string, name: string): Promise<CapturedReserverInstanceId: 'test-instance',getFileIndex: () => new Map(),});- const req = makeReq(`/api/template?name=${name}`);+ const folderQs = folder !== undefined ? `&folder=${encodeURIComponent(folder)}` : '';+ const req = makeReq(`/api/template?name=${name}${folderQs}`);const { res, captured } = makeRes();await (ext as {@@ -121,3 +126,115 @@ describe('GET /api/template — fence trailing whitespace (fm-delimiter hazard)'}});});++describe('GET /api/template — symlinked leaf refusal', () => {+ test('refuses a template leaf that is a symlink and leaks none of the target', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'ok-template-get-'));+ try {+ const secret = join(dir, 'planted-key');+ writeFileSync(secret, 'PRIVATE-KEY-MATERIAL-do-not-leak\n', 'utf-8');+ mkdirSync(join(dir, '.ok/templates'), { recursive: true });+ symlinkSync(secret, join(dir, '.ok/templates/stolen.md'));++ const result = await getTemplate(dir, 'stolen');++ expect(result.status).toBe(400);+ expect(JSON.parse(result.body).type).toBe('urn:ok:error:symlink-refused');+ expect(result.body).not.toContain('PRIVATE-KEY-MATERIAL');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('refuses an in-root symlinked template leaf (leaf identity, not containment)', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'ok-template-get-'));+ try {+ writeFileSync(join(dir, 'ordinary.md'), '# In-root but not a template\n', 'utf-8');+ mkdirSync(join(dir, '.ok/templates'), { recursive: true });+ symlinkSync('../../ordinary.md', join(dir, '.ok/templates/aliased.md'));++ const result = await getTemplate(dir, 'aliased');++ expect(result.status).toBe(400);+ expect(JSON.parse(result.body).type).toBe('urn:ok:error:symlink-refused');+ expect(result.body).not.toContain('In-root but not a template');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('refuses a symlinked ANCESTOR .ok/templates reached via a descendant folder', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'ok-template-get-'));+ const outside = mkdtempSync(join(tmpdir(), 'ok-template-outside-'));+ try {+ writeFileSync(join(outside, 'meeting.md'), 'PRIVATE-ANCESTOR-TARGET\n', 'utf-8');+ mkdirSync(join(dir, 'notes', '.ok'), { recursive: true });+ symlinkSync(outside, join(dir, 'notes', '.ok', 'templates'), 'dir');+ mkdirSync(join(dir, 'notes', 'sub'), { recursive: true });++ const result = await getTemplate(dir, 'meeting', 'notes/sub');++ expect(result.status).toBe(400);+ expect(JSON.parse(result.body).type).toBe('urn:ok:error:symlink-refused');+ expect(result.body).not.toContain('PRIVATE-ANCESTOR-TARGET');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ rmSync(outside, { recursive: true, force: true });+ }+ });++ test('refuses an IN-ROOT symlinked .ok/templates (the case containment cannot see)', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'ok-template-get-'));+ try {+ mkdirSync(join(dir, '.claude'), { recursive: true });+ writeFileSync(join(dir, '.claude', 'CLAUDE.md'), 'IN-ROOT-HIDDEN-CONTENT\n', 'utf-8');+ mkdirSync(join(dir, '.ok'), { recursive: true });+ symlinkSync('../.claude', join(dir, '.ok', 'templates'), 'dir');++ const result = await getTemplate(dir, 'CLAUDE');++ expect(result.status).toBe(400);+ expect(JSON.parse(result.body).type).toBe('urn:ok:error:symlink-refused');+ expect(result.body).not.toContain('IN-ROOT-HIDDEN-CONTENT');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('a regular FILE named .ok on an ancestor is skipped like an absent one (ENOTDIR continues the walk)', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'ok-template-get-'));+ try {+ mkdirSync(join(dir, '.ok', 'templates'), { recursive: true });+ writeFileSync(join(dir, '.ok', 'templates', 'x.md'), '---\ntitle: X\n---\n# X\n', 'utf-8');+ mkdirSync(join(dir, 'a', 'b'), { recursive: true });+ writeFileSync(join(dir, 'a', '.ok'), 'a regular file, not a directory', 'utf-8');++ const result = await getTemplate(dir, 'x', 'a/b');++ expect(result.status).toBe(200);+ const body = JSON.parse(result.body) as TemplateGetBody;+ expect(body.template?.frontmatter).toEqual({ title: 'X' });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('refuses an in-root symlinked ancestor .ok via a descendant folder', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'ok-template-get-'));+ try {+ mkdirSync(join(dir, 'secretdir', 'templates'), { recursive: true });+ writeFileSync(join(dir, 'secretdir', 'templates', 'note.md'), 'ALIASED-OK-DIR\n', 'utf-8');+ mkdirSync(join(dir, 'notes'), { recursive: true });+ symlinkSync('../secretdir', join(dir, 'notes', '.ok'), 'dir');+ mkdirSync(join(dir, 'notes', 'sub'), { recursive: true });++ const result = await getTemplate(dir, 'note', 'notes/sub');++ expect(result.status).toBe(400);+ expect(JSON.parse(result.body).type).toBe('urn:ok:error:symlink-refused');+ expect(result.body).not.toContain('ALIASED-OK-DIR');+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});diff --git a/packages/server/src/content/enrichment.ts b/packages/server/src/content/enrichment.tsindex b80113581..49db0f79a 100644--- a/packages/server/src/content/enrichment.ts+++ b/packages/server/src/content/enrichment.ts@@ -15,7 +15,11 @@ import { extractFirstHeading } from '../page-identity.ts';import { readFolderFrontmatter } from './nested-folder-rules.ts';import { type GitCommit, type ProjectHistorySource, readProjectGitLog } from './project-log.ts';import { type HistorySource, readShadowLog, type ShadowCommit } from './shadow-log.ts';-import { resolveTemplatesAvailable, type TemplateEntry } from './templates-resolver.ts';+import {+ resolveTemplatesAvailable,+ type TemplateDirRefusalListener,+ type TemplateEntry,+} from './templates-resolver.ts';const DIRECTORY_SCAN_CAP = 1000;@@ -543,9 +547,14 @@ async function scanDirectory(absDir: string, projectDir: string): Promise<DirScareturn result;}+export interface EnrichDirectoryOptions {+ onTemplateRefused?: TemplateDirRefusalListener;+}+export async function enrichDirectory(relPathInput: string,deps: Pick<EnrichPathDeps, 'projectDir' | 'contentDir' | 'frontmatterSchemas' | 'serverUrl'>,+ options: EnrichDirectoryOptions = {},): Promise<DirectoryMeta> {const contained = resolveWithinRoot(deps.projectDir, relPathInput);if (!contained.ok) {@@ -580,7 +589,9 @@ export async function enrichDirectory(if (own.description !== undefined) result.description = own.description;if ((own.tags?.length ?? 0) > 0) result.tags = own.tags;- const templates = resolveTemplatesAvailable(deps.projectDir, relPath);+ const templates = resolveTemplatesAvailable(deps.projectDir, relPath, {+ onRefused: options.onTemplateRefused,+ });if (templates.length > 0) result.templates_available = templates;const folderSchemas = schemasApplicableToFolder(deps, relPath);diff --git a/packages/server/src/content/folder-frontmatter-write.ts b/packages/server/src/content/folder-frontmatter-write.tsindex e1ee162ef..affba9543 100644--- a/packages/server/src/content/folder-frontmatter-write.ts+++ b/packages/server/src/content/folder-frontmatter-write.ts@@ -10,6 +10,7 @@ import {} from 'node:fs';import { isAbsolute, join, resolve, sep } from 'node:path';import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';+import { checkSymlinkLeaf } from '../fs-safety.ts';import { type FrontmatterRecord, mergePatch } from './frontmatter-merge.ts';export interface FolderFrontmatterPatchInput {@@ -18,12 +19,18 @@ export interface FolderFrontmatterPatchInput {patch: FrontmatterRecord;}+export type FolderFrontmatterErrorCode =+ | 'BAD_CONTENT_DIR'+ | 'PATH_ESCAPE'+ | 'SYMLINK_REFUSED'+ | 'WRITE_ERROR';+export type FolderFrontmatterPatchResult =| { ok: true; path: string; action: 'written' | 'deleted' | 'noop' }| {ok: false;error: {- code: 'BAD_CONTENT_DIR' | 'PATH_ESCAPE' | 'WRITE_ERROR';+ code: FolderFrontmatterErrorCode;message: string;};};@@ -59,6 +66,16 @@ export function applyFolderFrontmatterPatch(const okDir = join(targetAbs, '.ok');const fmPath = join(okDir, 'frontmatter.yml');+ if (checkSymlinkLeaf(fmPath).kind === 'symlink') {+ return {+ ok: false,+ error: {+ code: 'SYMLINK_REFUSED',+ message: `Refusing to operate on "${folderRel === '' ? '' : `${folderRel}/`}.ok/frontmatter.yml": it is a symlink. Replace the symlink with a real file or directory and retry.`,+ },+ };+ }+try {const existing = readExistingFrontmatter(fmPath);const isEmptyPatch = Object.keys(input.patch).length === 0;diff --git a/packages/server/src/content/nested-folder-rules.test.ts b/packages/server/src/content/nested-folder-rules.test.tsindex 9d582b8b4..6e183b933 100644--- a/packages/server/src/content/nested-folder-rules.test.ts+++ b/packages/server/src/content/nested-folder-rules.test.ts@@ -1,4 +1,4 @@-import { mkdirSync, writeFileSync } from 'node:fs';+import { mkdirSync, symlinkSync, writeFileSync } from 'node:fs';import { mkdtemp, rm } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -41,6 +41,34 @@ describe('readFolderFrontmatter — self-only (no cascade)', () => {});});+ test('treats a symlinked frontmatter.yml leaf as absent', () => {+ const secret = join(projectDir, 'secret.yml');+ writeFileSync(secret, 'title: Stolen\ndescription: exfiltrated\n');+ mkdirSync(join(projectDir, 'linked', '.ok'), { recursive: true });+ symlinkSync(secret, join(projectDir, 'linked', '.ok', 'frontmatter.yml'));+ expect(readFolderFrontmatter(projectDir, 'linked')).toEqual({});+ });++ test('treats a leaf behind an IN-ROOT symlinked .ok as absent', () => {+ mkdirSync(join(projectDir, 'secretdir'), { recursive: true });+ writeFileSync(join(projectDir, 'secretdir', 'frontmatter.yml'), 'title: AliasedInRoot\n');+ mkdirSync(join(projectDir, 'aliased'), { recursive: true });+ symlinkSync('../secretdir', join(projectDir, 'aliased', '.ok'), 'dir');+ expect(readFolderFrontmatter(projectDir, 'aliased')).toEqual({});+ });++ test('treats a leaf behind an out-of-root symlinked .ok ancestor as absent', async () => {+ const outside = await mkdtemp(join(tmpdir(), 'folder-frontmatter-outside-'));+ try {+ writeFileSync(join(outside, 'frontmatter.yml'), 'title: OutsideSecret\n');+ mkdirSync(join(projectDir, 'escaped'), { recursive: true });+ symlinkSync(outside, join(projectDir, 'escaped', '.ok'), 'dir');+ expect(readFolderFrontmatter(projectDir, 'escaped')).toEqual({});+ } finally {+ await rm(outside, { recursive: true, force: true });+ }+ });+test('does NOT inherit from ancestor folders (self-only)', () => {mkdirSync(join(projectDir, 'a', '.ok'), { recursive: true });writeFileSync(diff --git a/packages/server/src/content/nested-folder-rules.ts b/packages/server/src/content/nested-folder-rules.tsindex d48025493..c956eb8ff 100644--- a/packages/server/src/content/nested-folder-rules.ts+++ b/packages/server/src/content/nested-folder-rules.ts@@ -1,6 +1,7 @@import { existsSync, readFileSync } from 'node:fs';-import { join } from 'node:path';+import { dirname, join, resolve } from 'node:path';import { parse as parseYaml } from 'yaml';+import { assertNoSymlinkEscape, checkSymlinkLeaf, isContainmentRejection } from '../fs-safety.ts';import { getLogger } from '../logger.ts';export type FolderFrontmatter = {@@ -14,7 +15,51 @@ export function readFolderFrontmatter(folderRelPath: string,): FolderFrontmatter {const yamlPath = nestedOkPath(projectDir, folderRelPath, 'frontmatter.yml');+ /* STOP: the leaf lstat below cannot see a symlinked `.ok` ANCESTOR — the+ kernel dereferences it before reaching the final component — so the+ containing `.ok` dir gets its own identity check, matching+ `collectFromFolder` and the fetch-by-name walk. */+ if (checkSymlinkLeaf(dirname(yamlPath)).kind === 'symlink') {+ warnOnce(+ 'symlink',+ yamlPath,+ `${dirname(yamlPath)} is a symlink — folder metadata skipped. Replace the symlink with a real directory.`,+ );+ return {};+ }+ const leafCheck = checkSymlinkLeaf(yamlPath);+ if (leafCheck.kind === 'symlink') {+ warnOnce(+ 'symlink',+ yamlPath,+ `symlink at ${yamlPath} — folder metadata skipped. Replace it with a regular file.`,+ );+ return {};+ }+ if (leafCheck.kind === 'unverifiable') {+ warnOnce(+ 'unverifiable',+ yamlPath,+ `cannot lstat ${yamlPath} (${leafCheck.code ?? 'unknown errno'}) — folder metadata skipped.`,+ );+ return {};+ }if (!existsSync(yamlPath)) return {};+ /* STOP: unlike the folder-config route arms, this reader's other caller+ (`enrichDirectory` via MCP `exec`) has only lexical containment in front+ of it, so a symlinked ancestor (`<folder>/.ok -> /outside`) must be+ refused HERE — the leaf check above cannot see it. */+ try {+ assertNoSymlinkEscape(yamlPath, resolve(projectDir));+ } catch (err) {+ const reason = err instanceof Error ? err.message : String(err);+ warnOnce(+ isContainmentRejection(err) ? 'escape' : 'canonicalize',+ yamlPath,+ `cannot safely read ${yamlPath} — folder metadata skipped. Reason: ${reason}`,+ );+ return {};+ }const parsed = readFrontmatterYaml(yamlPath);return parsed != null ? coerceWellKnown(parsed) : {};}@@ -36,8 +81,28 @@ function coerceWellKnown(raw: Record<string, unknown>): FolderFrontmatter {return out;}+const WARN_CLASSES = [+ 'symlink',+ 'unverifiable',+ 'escape',+ 'canonicalize',+ 'malformed-yaml',+] as const;+type WarnClass = (typeof WARN_CLASSES)[number];+const warnedPaths = new Set<string>();+function warnOnce(kind: WarnClass, absPath: string, message: string): void {+ const key = `${kind}:${absPath}`;+ if (warnedPaths.has(key)) return;+ warnedPaths.add(key);+ getLogger('folder-frontmatter').warn({ path: absPath, kind }, message);+}++function clearWarns(absPath: string): void {+ for (const kind of WARN_CLASSES) warnedPaths.delete(`${kind}:${absPath}`);+}+function readFrontmatterYaml(absYamlPath: string): Record<string, unknown> | null {let content: string;try {@@ -50,19 +115,17 @@ function readFrontmatterYaml(absYamlPath: string): Record<string, unknown> | nultry {parsed = parseYaml(content);} catch (err) {- if (!warnedPaths.has(absYamlPath)) {- warnedPaths.add(absYamlPath);- const reason = err instanceof Error ? err.message : String(err);- getLogger('folder-frontmatter').warn(- { path: absYamlPath, reason },- `malformed YAML at ${absYamlPath} — folder metadata skipped. Fix the file or delete it. Reason: ${reason}`,- );- }+ const reason = err instanceof Error ? err.message : String(err);+ warnOnce(+ 'malformed-yaml',+ absYamlPath,+ `malformed YAML at ${absYamlPath} — folder metadata skipped. Fix the file or delete it. Reason: ${reason}`,+ );return null;}if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed)) return null;- warnedPaths.delete(absYamlPath);+ clearWarns(absYamlPath);return parsed as Record<string, unknown>;}diff --git a/packages/server/src/content/templates-resolver.test.ts b/packages/server/src/content/templates-resolver.test.tsindex ad4467066..a8df601fe 100644--- a/packages/server/src/content/templates-resolver.test.ts+++ b/packages/server/src/content/templates-resolver.test.ts@@ -3,7 +3,13 @@ import { mkdtemp, rm } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';import { afterEach, beforeEach, describe, expect, test } from 'vitest';-import { resolveProjectTemplates, resolveTemplatesAvailable } from './templates-resolver.ts';+import {+ resolveProjectTemplates,+ resolveTemplatesAvailable,+ type TemplateDirRefusalListener,+} from './templates-resolver.ts';++type TemplateDirRefusal = Parameters<TemplateDirRefusalListener>[0];describe('resolveTemplatesAvailable', () => {let projectDir: string;@@ -90,6 +96,98 @@ describe('resolveTemplatesAvailable', () => {expect(tpls.find((t) => t.name === 'prep-notes')).toBeUndefined();});+ test('a non-directory ancestor .ok is skipped WITHOUT a refusal and the walk continues to the root', () => {+ writeTemplate('', 'global', withFm('Global', 'Survives the skip.'));+ mkdirSync(join(projectDir, 'anc', 'child'), { recursive: true });+ writeFileSync(join(projectDir, 'anc', '.ok'), 'not a directory\n');+ const refusals: TemplateDirRefusal[] = [];+ const tpls = resolveTemplatesAvailable(projectDir, 'anc/child', {+ onRefused: (r) => refusals.push(r),+ });+ expect(tpls.map((t) => t.name)).toEqual(['global']);+ expect(tpls[0]?.scope).toBe('inherited');+ expect(refusals).toEqual([]);+ });++ test('a regular FILE at .ok/templates is skipped WITHOUT a refusal and inherited templates still resolve', () => {+ writeTemplate('', 'global', withFm('Global', 'Survives the skip.'));+ mkdirSync(join(projectDir, 'flat', '.ok'), { recursive: true });+ writeFileSync(join(projectDir, 'flat', '.ok', 'templates'), 'not a directory\n');+ const refusals: TemplateDirRefusal[] = [];+ const tpls = resolveTemplatesAvailable(projectDir, 'flat', {+ onRefused: (r) => refusals.push(r),+ });+ expect(tpls.map((t) => t.name)).toEqual(['global']);+ expect(refusals).toEqual([]);+ });++ test('a self-referential symlink on the path reaches onRefused as unverifiable (no chmod needed)', () => {+ symlinkSync('loop', join(projectDir, 'loop'), 'dir');+ const refusals: TemplateDirRefusal[] = [];+ expect(+ resolveTemplatesAvailable(projectDir, 'loop', { onRefused: (r) => refusals.push(r) }),+ ).toEqual([]);+ expect(refusals).toHaveLength(1);+ expect(refusals[0]).toMatchObject({+ kind: 'unverifiable',+ folder: 'loop',+ component: '.ok/templates',+ });+ expect((refusals[0] as { code?: string }).code).toBe('ELOOP');+ });++ test('a symlinked ancestor .ok and a symlinked templates dir each reach onRefused, naming the folder', () => {+ mkdirSync(join(projectDir, 'target-a', 'templates'), { recursive: true });+ writeFileSync(join(projectDir, 'target-a', 'templates', 'x.md'), withFm('X', 'x'));+ mkdirSync(join(projectDir, 'a', 'child'), { recursive: true });+ symlinkSync('../target-a', join(projectDir, 'a', '.ok'), 'dir');+ mkdirSync(join(projectDir, 'target-b'), { recursive: true });+ writeFileSync(join(projectDir, 'target-b', 'y.md'), withFm('Y', 'y'));+ mkdirSync(join(projectDir, 'b', '.ok'), { recursive: true });+ symlinkSync('../../target-b', join(projectDir, 'b', '.ok', 'templates'), 'dir');++ writeTemplate('', 'global', withFm('Global', 'Survives the skip.'));+ const fromA: TemplateDirRefusal[] = [];+ const viaA = resolveTemplatesAvailable(projectDir, 'a/child', {+ onRefused: (r) => fromA.push(r),+ });+ expect(viaA.map((t) => t.name)).toEqual(['global']);+ expect(fromA).toEqual([{ kind: 'symlink', folder: 'a', component: '.ok' }]);++ const fromB: TemplateDirRefusal[] = [];+ const viaB = resolveTemplatesAvailable(projectDir, 'b', { onRefused: (r) => fromB.push(r) });+ expect(viaB.map((t) => t.name)).toEqual(['global']);+ expect(fromB).toEqual([{ kind: 'symlink', folder: 'b', component: '.ok/templates' }]);+ });++ test('an in-root symlinked ancestor .ok is not enumerated (menu matches fetch-by-name)', () => {+ mkdirSync(join(projectDir, 'secretdir', 'templates'), { recursive: true });+ writeFileSync(+ join(projectDir, 'secretdir', 'templates', 'note.md'),+ withFm('Hidden', 'Aliased through .ok'),+ 'utf-8',+ );+ mkdirSync(join(projectDir, 'notes'), { recursive: true });+ symlinkSync('../secretdir', join(projectDir, 'notes', '.ok'), 'dir');+ mkdirSync(join(projectDir, 'notes', 'sub'), { recursive: true });+ writeTemplate('', 'global', withFm('Global', 'Survives the skip.'));++ expect(resolveTemplatesAvailable(projectDir, 'notes/sub').map((t) => t.name)).toEqual([+ 'global',+ ]);+ expect(resolveTemplatesAvailable(projectDir, 'notes').map((t) => t.name)).toEqual(['global']);+ });++ test('an in-root symlinked templates dir is not enumerated', () => {+ mkdirSync(join(projectDir, 'elsewhere'), { recursive: true });+ writeFileSync(join(projectDir, 'elsewhere', 'x.md'), withFm('X', 'aliased'), 'utf-8');+ mkdirSync(join(projectDir, 'notes2', '.ok'), { recursive: true });+ symlinkSync('../../elsewhere', join(projectDir, 'notes2', '.ok', 'templates'), 'dir');+ writeTemplate('', 'global', withFm('Global', 'Survives the skip.'));++ expect(resolveTemplatesAvailable(projectDir, 'notes2').map((t) => t.name)).toEqual(['global']);+ });+test('descendant templates do NOT surface in the parent folder (D17 — two-value scope)', () => {writeTemplate('meetings/prep-notes',@@ -99,9 +197,6 @@ describe('resolveTemplatesAvailable', () => {expect(resolveTemplatesAvailable(projectDir, 'meetings')).toEqual([]);- expect(resolveTemplatesAvailable(projectDir, 'meetings', { depth: 2 })).toEqual([]);- expect(resolveTemplatesAvailable(projectDir, 'meetings', { depth: Infinity })).toEqual([]);-const ownTpls = resolveTemplatesAvailable(projectDir, 'meetings/prep-notes');expect(ownTpls).toHaveLength(1);expect(ownTpls[0]?.name).toBe('agenda');@@ -109,13 +204,11 @@ describe('resolveTemplatesAvailable', () => {expect(ownTpls[0]?.source_folder).toBe('meetings/prep-notes');});- test('depth parameter is a no-op — no descent into subfolders from the resolver', () => {+ test('the resolver never descends into subfolders — only leaf→root ancestors', () => {writeTemplate('a/b/c', 'deep', withFm('Deep', 'Buried in a/b/c.'));expect(resolveTemplatesAvailable(projectDir, 'a')).toEqual([]);- expect(resolveTemplatesAvailable(projectDir, 'a', { depth: 2 })).toEqual([]);- expect(resolveTemplatesAvailable(projectDir, 'a', { depth: 100 })).toEqual([]);- expect(resolveTemplatesAvailable(projectDir, 'a', { depth: Infinity })).toEqual([]);+ expect(resolveTemplatesAvailable(projectDir, 'a/b')).toEqual([]);const own = resolveTemplatesAvailable(projectDir, 'a/b/c');expect(own).toHaveLength(1);@@ -239,8 +332,9 @@ describe('resolveTemplatesAvailable', () => {writeFileSync(join(outside, 'leak.md'), withFm('Leak', 'Foreign template.'));mkdirSync(join(projectDir, 'notes', '.ok'), { recursive: true });symlinkSync(outside, join(projectDir, 'notes', '.ok', 'templates'), 'dir');+ writeTemplate('', 'global', withFm('Global', 'Survives the skip.'));- expect(resolveTemplatesAvailable(projectDir, 'notes')).toEqual([]);+ expect(resolveTemplatesAvailable(projectDir, 'notes').map((t) => t.name)).toEqual(['global']);} finally {await rm(outside, { recursive: true, force: true });}@@ -250,8 +344,9 @@ describe('resolveTemplatesAvailable', () => {writeFileSync(join(projectDir, 'stash.md'), withFm('Stash', 'Not a template.'));mkdirSync(join(projectDir, 'notes', '.ok'), { recursive: true });symlinkSync(projectDir, join(projectDir, 'notes', '.ok', 'templates'), 'dir');+ writeTemplate('', 'global', withFm('Global', 'Survives the skip.'));- expect(resolveTemplatesAvailable(projectDir, 'notes')).toEqual([]);+ expect(resolveTemplatesAvailable(projectDir, 'notes').map((t) => t.name)).toEqual(['global']);});});diff --git a/packages/server/src/content/templates-resolver.ts b/packages/server/src/content/templates-resolver.tsindex 54b509c55..258c62d52 100644--- a/packages/server/src/content/templates-resolver.ts+++ b/packages/server/src/content/templates-resolver.ts@@ -3,7 +3,7 @@ import { readdir, stat } from 'node:fs/promises';import { join, posix } from 'node:path';import { parseTemplateFile } from '@inkeep/open-knowledge-core';import { SymlinkEscapeError } from '../apply-managed-rename.ts';-import { assertNoSymlinkEscape } from '../fs-safety.ts';+import { assertNoSymlinkEscape, checkSymlinkLeaf } from '../fs-safety.ts';import { errnoCode } from '../http/handler-utils.ts';import { getLogger } from '../logger.ts';@@ -18,29 +18,36 @@ export interface TemplateEntry {scope: TemplateScope;}+type TemplateDirRefusal =+ | { kind: 'symlink'; folder: string; component: '.ok' | '.ok/templates' }+ | { kind: 'unverifiable'; folder: string; component: '.ok/templates'; code: string | undefined };++export type TemplateDirRefusalListener = (refusal: TemplateDirRefusal) => void;+interface ResolveTemplatesOptions {- depth?: number;+ onRefused?: TemplateDirRefusalListener;}export function resolveTemplatesAvailable(projectDir: string,folderRelPath: string,- _options: ResolveTemplatesOptions = {},+ options: ResolveTemplatesOptions = {},): TemplateEntry[] {const normalized = normalizeFolderPath(folderRelPath);const segments = normalized === '' ? [] : normalized.split('/');const seen = new Set<string>();const out: TemplateEntry[] = [];+ const onRefused = options.onRefused;- collectFromFolder(projectDir, normalized, 'local', seen, out);+ collectFromFolder(projectDir, normalized, 'local', seen, out, onRefused);for (let i = segments.length - 1; i >= 1; i--) {const ancestorPath = segments.slice(0, i).join('/');- collectFromFolder(projectDir, ancestorPath, 'inherited', seen, out);+ collectFromFolder(projectDir, ancestorPath, 'inherited', seen, out, onRefused);}if (segments.length > 0) {- collectFromFolder(projectDir, '', 'inherited', seen, out);+ collectFromFolder(projectDir, '', 'inherited', seen, out, onRefused);}return out;@@ -137,16 +144,56 @@ function collectFromFolder(scope: TemplateScope,seen: Set<string>,out: TemplateEntry[],+ onRefused?: TemplateDirRefusalListener,): void {- const templatesDir = folderRelPath- ? join(projectDir, folderRelPath, '.ok', 'templates')- : join(projectDir, '.ok', 'templates');+ const okDir = join(projectDir, folderRelPath, '.ok');+ const templatesDir = join(okDir, 'templates');++ /* STOP: `lstat` below refuses only when `templates` ITSELF is the link —+ the kernel dereferences a symlinked `.ok` on the way there, so the `.ok`+ component needs its own identity check or an in-root `.ok` alias is+ enumerated here while the fetch-by-name walk+ (`findTemplateLeafToRoot` in folder-template-routes.ts) refuses it.+ `onRefused` fires only for a symlink or a non-ENOTDIR lstat failure: a+ non-directory `templates` (a regular file, or ENOTDIR under a+ non-directory `.ok`) provably holds no templates, so it degrades to a+ log warn with no refusal and no API warning code — matching the+ ANCESTOR walk's ENOTDIR carve-out in `findTemplateLeafToRoot`. On the+ TEMPLATE arms the entry gate (`validateFolderRel`, `'ok-and-templates'`)+ has no such carve-out for a non-directory `.ok` on the REQUESTED folder:+ `assertNoSymlinkEscape(okTemplatesDir)` raises ENOTDIR and the gate+ 500s. The folder-config arm skips that assert, so the same shape reaches+ this function and degrades here. The folder-history arm skips it too+ (same `'ok'` scope) but never reaches this function — `getFolderTimeline`+ uses `<folder>/.ok` only as a `git log` pathspec — so the shape produces+ no signal there. */+ if (checkSymlinkLeaf(okDir).kind === 'symlink') {+ onRefused?.({ kind: 'symlink', folder: folderRelPath, component: '.ok' });+ if (!templateMetaWarnedPaths.has(okDir)) {+ templateMetaWarnedPaths.add(okDir);+ getLogger('templates').warn(+ { dir: okDir },+ `${okDir} is a symlink — its templates are not enumerated. Replace the symlink with a real directory.`,+ );+ }+ return;+ }let dirStat: ReturnType<typeof lstatSync>;try {dirStat = lstatSync(templatesDir);} catch (err) {- if (errnoCode(err) !== 'ENOENT' && !templateMetaWarnedPaths.has(templatesDir)) {+ const code = errnoCode(err);+ if (code === 'ENOENT') return;+ if (code !== 'ENOTDIR') {+ onRefused?.({+ kind: 'unverifiable',+ folder: folderRelPath,+ component: '.ok/templates',+ code,+ });+ }+ if (!templateMetaWarnedPaths.has(templatesDir)) {templateMetaWarnedPaths.add(templatesDir);const reason = err instanceof Error ? err.message : String(err);getLogger('templates').warn(@@ -157,6 +204,9 @@ function collectFromFolder(return;}if (!dirStat.isDirectory()) {+ if (dirStat.isSymbolicLink()) {+ onRefused?.({ kind: 'symlink', folder: folderRelPath, component: '.ok/templates' });+ }if (!templateMetaWarnedPaths.has(templatesDir)) {templateMetaWarnedPaths.add(templatesDir);getLogger('templates').warn(diff --git a/packages/server/src/fs-safety.ts b/packages/server/src/fs-safety.tsindex 1eb23565d..7bbbe4e75 100644--- a/packages/server/src/fs-safety.ts+++ b/packages/server/src/fs-safety.ts@@ -1,4 +1,4 @@-import { realpathSync } from 'node:fs';+import { lstatSync, realpathSync } from 'node:fs';import { dirname, join, relative, sep } from 'node:path';import { isWithinContentDir } from './content-path.ts';import { normalizeFsPath } from './fs-traced.ts';@@ -58,6 +58,49 @@ export function assertNoSymlinkEscape(fullPath: string, resolvedContentDir: stri}}+export type SymlinkLeafCheck =+ | { kind: 'not-symlink' }+ | { kind: 'symlink' }+ | { kind: 'unverifiable'; code: string | undefined };++/* STOP: an `<folder>/.ok` artifact path (the `frontmatter.yml` leaf or the+ `.ok` directory itself) must never be a symlink on the arms this guard+ fronts — the folder-config, template, and folder-history HTTP arms plus+ the `readFolderFrontmatter` / `collectFromFolder` readers they share with+ directory enrichment — even though the sync plane admits in-root+ shareable-artifact symlinks via `assertRealpathWithinDir`'s+ `allowShareableOkArtifact`: the folder-config PUT merges and rewrites the+ leaf in place (`renameSync` replaces the link), so realpath containment+ alone would let a committed link materialize foreign content as in-root+ git-trackable bytes. Do not harmonize the `symlink` case back to+ containment semantics. This is NOT a whole-plane claim: the MCP+ `edit({ template })` leaf read and the `exec` cat-path enrichment+ (`enrichPath` → `readFrontmatter`) still resolve lexically and are not+ covered here. `unverifiable` (a non-ENOENT lstat failure —+ EACCES/ELOOP/ENOTDIR) is reported DISTINCTLY from `symlink` so callers+ never assert "it is a symlink" for a path that is not one; read arms+ surface it as a warning, the template ancestor walk fails loud (500+ carrying the errno) except for ENOTDIR, which it treats as absent and+ walks past (a non-directory `.ok` / `templates` provably holds no+ templates, matching the menu's skip), and everywhere else the follow-on+ syscall (containment realpath, or the write itself) fails on the same+ errno. `lstat` differs from open/stat only in not following the FINAL+ component, and a symlinked final component makes lstat SUCCEED (→+ `symlink`), so no errno can make this return `unverifiable` while a+ follow-on read of the same path succeeds. The `frontmatter.yml`-leaf+ accessors and every call site of this guard (pinned per file by argument+ expression) are enforced by `symlink-leaf-guard-enforcement.test.ts`;+ loop-free call sites keep each guarded component pin-visible. */+export function checkSymlinkLeaf(absPath: string): SymlinkLeafCheck {+ try {+ return lstatSync(absPath).isSymbolicLink() ? { kind: 'symlink' } : { kind: 'not-symlink' };+ } catch (err) {+ const code = errnoCode(err);+ if (code === 'ENOENT') return { kind: 'not-symlink' };+ return { kind: 'unverifiable', code };+ }+}+export class PathContainmentError extends Error {constructor(message: string) {super(message);diff --git a/packages/server/src/http/folder-template-routes.ts b/packages/server/src/http/folder-template-routes.tsindex 98704a156..7e5736507 100644--- a/packages/server/src/http/folder-template-routes.ts+++ b/packages/server/src/http/folder-template-routes.ts@@ -8,8 +8,10 @@ import {FolderConfigGetSuccessSchema,FolderConfigPutRequestSchema,FolderConfigPutSuccessSchema,+ type FolderConfigWarningCode,instantiateDoc,type Principal,+ type ProblemType,parseTemplateFile,stripFrontmatter,TEMPLATE_NAME_REGEX,@@ -30,7 +32,10 @@ import { composeAndWriteRawBody } from '../bridge-intake.ts';import { isConfigDoc, isSystemDoc } from '../cc1-broadcast.ts';import { DocInConflictError, isDocInConflict, respondDocInConflict } from '../conflict-errors.ts';import { enrichDirectory } from '../content/enrichment.ts';-import { applyFolderFrontmatterPatch } from '../content/folder-frontmatter-write.ts';+import {+ applyFolderFrontmatterPatch,+ type FolderFrontmatterErrorCode,+} from '../content/folder-frontmatter-write.ts';import {applyTemplateDelete,applyTemplateMove,@@ -41,6 +46,7 @@ import {import type { StoreFailure } from '../document-durability-state.ts';import { extractActorIdentity } from '../extract-actor-identity.ts';import type { DiskEvent } from '../file-watcher.ts';+import { assertNoSymlinkEscape, checkSymlinkLeaf, isContainmentRejection } from '../fs-safety.ts';import { tracedUnlinkSync } from '../fs-traced.ts';import type { PinoLogger } from '../logger.ts';import { extractPageTitle } from '../page-identity.ts';@@ -69,8 +75,9 @@ export interface FolderTemplateRouteDeps {validateFolderRel: (raw: string,res: ServerResponse,- label?: 'path' | 'folder',- handler?: string,+ label: 'path' | 'folder',+ handler: string,+ components: 'ok' | 'ok-and-templates',) => { folderRel: string; resolvedContentDir: string } | null;extractAgentIdentity: (body: Record<string, unknown>) => {agentId: string;@@ -120,6 +127,13 @@ export interface FolderTemplateRouteDeps {mutateFileIndex: ((event: DiskEvent) => void) | undefined;}+const FOLDER_FRONTMATTER_ERROR_META = {+ BAD_CONTENT_DIR: { status: 400, urn: 'urn:ok:error:invalid-request' },+ PATH_ESCAPE: { status: 400, urn: 'urn:ok:error:path-escape' },+ SYMLINK_REFUSED: { status: 400, urn: 'urn:ok:error:symlink-refused' },+ WRITE_ERROR: { status: 500, urn: 'urn:ok:error:internal-server-error' },+} as const satisfies Record<FolderFrontmatterErrorCode, { status: 400 | 500; urn: ProblemType }>;+export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRouteGroup {const {contentDir,@@ -171,7 +185,11 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRoresolvedContentDir: string,folderRel: string,name: string,- ): { abs: string; folder: string; scope: 'local' | 'inherited' } | null {+ ):+ | { kind: 'found'; abs: string; folder: string; scope: 'local' | 'inherited' }+ | { kind: 'refused'; folder: string }+ | { kind: 'unverifiable'; folder: string; code: string | undefined }+ | { kind: 'absent' } {const segments = folderRel === '' ? [] : folderRel.split('/');for (let depth = segments.length; depth >= 0; depth--) {const ancestorFolder = depth === 0 ? '' : segments.slice(0, depth).join('/');@@ -183,16 +201,44 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRo) {continue;}- const candidate = resolve(ancestorAbs, '.ok', 'templates', `${name}.md`);+ /* STOP: identity, not containment — an IN-ROOT symlinked ancestor+ `.ok` / `.ok/templates` realpaths inside the content root and defeats+ every root-anchored check, exactly like the leaf case. The invariant+ is one-directional: this walk must never SERVE what the menu+ (`collectFromFolder` in templates-resolver.ts) hides; refusing more+ than the menu is permitted. A symlink aborts loudly (400). ENOTDIR is+ treated as absent and the walk continues — a non-directory `.ok` or+ `templates` provably holds no templates, matching the menu's skip.+ Every OTHER lstat errno (EACCES/ELOOP) aborts loudly (500): an+ unreadable ancestor COULD hold a shadowing name, so resolving past it+ from a higher folder would be a silent wrong answer. */+ const okAbs = resolve(ancestorAbs, '.ok');+ const okCheck = checkSymlinkLeaf(okAbs);+ if (okCheck.kind === 'symlink') {+ return { kind: 'refused', folder: ancestorFolder };+ }+ if (okCheck.kind === 'unverifiable' && okCheck.code !== 'ENOTDIR') {+ return { kind: 'unverifiable', folder: ancestorFolder, code: okCheck.code };+ }+ const templatesAbs = resolve(okAbs, 'templates');+ const templatesCheck = checkSymlinkLeaf(templatesAbs);+ if (templatesCheck.kind === 'symlink') {+ return { kind: 'refused', folder: ancestorFolder };+ }+ if (templatesCheck.kind === 'unverifiable' && templatesCheck.code !== 'ENOTDIR') {+ return { kind: 'unverifiable', folder: ancestorFolder, code: templatesCheck.code };+ }+ const candidate = resolve(templatesAbs, `${name}.md`);if (existsSync(candidate)) {return {+ kind: 'found',abs: candidate,folder: ancestorFolder,scope: depth === segments.length ? 'local' : 'inherited',};}}- return null;+ return { kind: 'absent' };}function pickFrontmatterFields(raw: unknown): Record<string, unknown> {@@ -219,15 +265,76 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRores,'path','folder-config-get',+ 'ok',);if (!validated) return;- const meta = await enrichDirectory(validated.folderRel, {- projectDir: validated.resolvedContentDir,- });const folderOkDir = resolve(validated.resolvedContentDir, validated.folderRel, '.ok');const localFmPath = resolve(folderOkDir, 'frontmatter.yml');+ const warnings: string[] = [];+ const warningCodes: FolderConfigWarningCode[] = [];+ const addWarning = (code: FolderConfigWarningCode, text: string): void => {+ warnings.push(text);+ warningCodes.push(code);+ };+ const meta = await enrichDirectory(+ validated.folderRel,+ { projectDir: validated.resolvedContentDir },+ {+ onTemplateRefused: (refusal) => {+ const where = `${refusal.folder || '.'}/${refusal.component}`;+ const path = resolve(validated.resolvedContentDir, refusal.folder, refusal.component);+ switch (refusal.kind) {+ case 'symlink':+ addWarning(+ 'templates-symlink-refused',+ `${where} is a symlink — its templates are not enumerated. Replace the symlink with a real file or directory and retry.`,+ );+ log.warn(+ { path, folder: validated.folderRel || '.' },+ `[folder-config:get] ${where} is a symlink — templates_available skips it.`,+ );+ break;+ case 'unverifiable':+ addWarning(+ 'templates-unverifiable',+ `${where} could not be inspected (${refusal.code ?? 'unknown errno'}) — its templates are not enumerated. The errno may come from ${refusal.folder || '.'}/.ok itself; check its permissions.`,+ );+ log.warn(+ { path, folder: validated.folderRel || '.', code: refusal.code },+ `[folder-config:get] cannot lstat ${where} (${refusal.code ?? 'unknown errno'}) — templates_available skips it.`,+ );+ break;+ default: {+ const _exhaustive: never = refusal;+ throw new Error(+ `Unhandled template refusal kind in handleFolderConfigGet: ${String((_exhaustive as { kind?: unknown }).kind)}`,+ );+ }+ }+ },+ },+ );let frontmatterLocal: Record<string, unknown> | null = null;- if (existsSync(localFmPath)) {+ const leafCheck = checkSymlinkLeaf(localFmPath);+ if (leafCheck.kind === 'symlink') {+ addWarning(+ 'symlink-refused',+ `${validated.folderRel || '.'}/.ok/frontmatter.yml is a symlink — refusing to read through it. Replace the symlink with a real file or directory and retry.`,+ );+ log.warn(+ { path: localFmPath, folder: validated.folderRel || '.' },+ `[folder-config:get] ${validated.folderRel || '.'}/.ok/frontmatter.yml is a symlink — refusing to read through it.`,+ );+ } else if (leafCheck.kind === 'unverifiable') {+ addWarning(+ 'unverifiable',+ `${validated.folderRel || '.'}/.ok/frontmatter.yml could not be inspected (${leafCheck.code ?? 'unknown errno'}) — folder properties skipped.`,+ );+ log.warn(+ { path: localFmPath, code: leafCheck.code },+ `[folder-config:get] cannot lstat ${localFmPath} (${leafCheck.code ?? 'unknown errno'}) — frontmatter_local skipped.`,+ );+ } else if (existsSync(localFmPath)) {try {const raw = await readFile(localFmPath, 'utf-8');const parsed = parseYaml(raw);@@ -238,6 +345,10 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRo}} catch (err) {const reason = err instanceof Error ? err.message : String(err);+ addWarning(+ 'malformed-yaml',+ `${validated.folderRel || '.'}/.ok/frontmatter.yml has malformed YAML.`,+ );log.warn({ path: localFmPath, reason },`[folder-config:get] malformed YAML in ${localFmPath}: ${reason}`,@@ -253,6 +364,7 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRo{folder: meta,frontmatter_local: frontmatterLocal,+ ...(warningCodes.length > 0 ? { warnings, warningCodes } : {}),},{ handler: 'folder-config-get' },);@@ -293,7 +405,7 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRo});return;}- const validated = validateFolderRel(body.path, res, 'path', 'folder-config-put');+ const validated = validateFolderRel(body.path, res, 'path', 'folder-config-put', 'ok');if (!validated) return;const allApplied: Array<{ path: string; action: 'written' | 'deleted' | 'noop' }> = [];@@ -304,11 +416,7 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRopatch: body.frontmatter,});if (!result.ok) {- const status = result.error.code === 'WRITE_ERROR' ? 500 : 400;- const urn =- status === 500- ? 'urn:ok:error:internal-server-error'- : 'urn:ok:error:invalid-request';+ const { status, urn } = FOLDER_FRONTMATTER_ERROR_META[result.error.code];const title = status === 500 ? 'Failed to write folder config.' : result.error.message;errorResponse(res, status, urn, title, {handler: 'folder-config-put',@@ -379,12 +487,33 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRores,'folder','template-get',+ 'ok-and-templates',);if (!validated) return;const { folderRel, resolvedContentDir } = validated;const found = findTemplateLeafToRoot(resolvedContentDir, folderRel, name);- if (!found) {+ if (found.kind === 'refused') {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:symlink-refused',+ `"${found.folder || '.'}/.ok" or its templates directory is a symlink — refusing to resolve templates through it. Replace the symlink with a real file or directory and retry.`,+ { handler: 'template-get', detail: found.folder || '.' },+ );+ return;+ }+ if (found.kind === 'unverifiable') {+ errorResponse(+ res,+ 500,+ 'urn:ok:error:internal-server-error',+ `Cannot inspect "${found.folder || '.'}/.ok" (${found.code ?? 'unknown errno'}) — refusing to resolve templates through it.`,+ { handler: 'template-get', detail: found.code ?? 'unknown-errno' },+ );+ return;+ }+ if (found.kind === 'absent') {errorResponse(res, 404, 'urn:ok:error:template-not-found', 'Template not found.', {handler: 'template-get',detail: `Template "${name}" not found for folder "${folderRel || '.'}". Walked leaf → root.`,@@ -393,6 +522,38 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRo}const { abs: foundAbs, folder: foundFolder, scope: foundScope } = found;+ /* STOP: the walk above refuses symlinked ancestor `.ok` /+ `.ok/templates` dirs BY IDENTITY (in-root included); the two checks+ below cover the remaining shapes — a symlinked `<name>.md` leaf,+ and (defence in depth) a resolved path escaping the content root.+ The fetch-by-name arm bypasses the resolver's guarded enumeration+ (`collectFromFolder`), so all three must live here. */+ if (checkSymlinkLeaf(foundAbs).kind === 'symlink') {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:symlink-refused',+ `Template "${name}" at "${foundFolder || '.'}/.ok/templates/${name}.md" is a symlink — refusing to read through it. Replace the symlink with a real file or directory and retry.`,+ { handler: 'template-get', detail: foundFolder || '.' },+ );+ return;+ }+ try {+ assertNoSymlinkEscape(foundAbs, resolvedContentDir);+ } catch (err) {+ if (isContainmentRejection(err)) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:symlink-refused',+ `Template "${name}" resolves through a symlink outside the content directory — refusing to read through it. Replace the symlink with a real file or directory and retry.`,+ { handler: 'template-get', detail: foundFolder || '.' },+ );+ return;+ }+ throw err;+ }+const raw = await readFile(foundAbs, 'utf-8');const model = parseTemplateFile(raw);const frontmatter = model.identity as Record<string, unknown>;@@ -455,9 +616,38 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRo}const name = body.name;if (!validateTemplateName(name, res, 'template-put')) return;- const validated = validateFolderRel(body.folder, res, 'folder', 'template-put');+ const validated = validateFolderRel(+ body.folder,+ res,+ 'folder',+ 'template-put',+ 'ok-and-templates',+ );if (!validated) return;+ const templateFilePath = resolve(+ validated.resolvedContentDir,+ validated.folderRel,+ '.ok',+ 'templates',+ `${name}.md`,+ );+ /* STOP: the persistence plane realpaths this leaf and renames onto+ the TARGET, so a committed in-root symlink here lets a template+ save overwrite any in-root `.md` — including paths the content+ plane refuses to serve (`.claude/`, `.agents/`). The leaf is+ refused on GET; the write arms must refuse it too. */+ if (checkSymlinkLeaf(templateFilePath).kind === 'symlink') {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:symlink-refused',+ `${validated.folderRel || '.'}/.ok/templates/${name}.md is a symlink — refusing to write through it. Replace the symlink with a real file or directory and retry.`,+ { handler: 'template-put', detail: validated.folderRel || '.' },+ );+ return;+ }+if (checkTemplateConflictGate(templateDocNameFor(validated.folderRel, name),@@ -481,13 +671,6 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRoreturn;}- const templateFilePath = resolve(- validated.resolvedContentDir,- validated.folderRel,- '.ok',- 'templates',- `${name}.md`,- );const templateCreated = !existsSync(templateFilePath);const templateRelPath = relative(validated.resolvedContentDir, templateFilePath).split(/[\\/]/)@@ -562,6 +745,7 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRores,'folder','template-delete',+ 'ok-and-templates',);if (!validated) return;@@ -655,9 +839,21 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRo}if (!validateTemplateName(body.fromName, res, 'template-move')) return;if (!validateTemplateName(body.toName, res, 'template-move')) return;- const fromValidated = validateFolderRel(body.fromFolder, res, 'folder', 'template-move');+ const fromValidated = validateFolderRel(+ body.fromFolder,+ res,+ 'folder',+ 'template-move',+ 'ok-and-templates',+ );if (!fromValidated) return;- const toValidated = validateFolderRel(body.toFolder, res, 'folder', 'template-move');+ const toValidated = validateFolderRel(+ body.toFolder,+ res,+ 'folder',+ 'template-move',+ 'ok-and-templates',+ );if (!toValidated) return;if (@@ -695,7 +891,27 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRofromValidated.folderRel,body.fromName,);- if (found?.scope === 'inherited') {+ if (found.kind === 'refused') {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:symlink-refused',+ `"${found.folder || '.'}/.ok" or its templates directory is a symlink — refusing to resolve templates through it. Replace the symlink with a real file or directory and retry.`,+ { handler: 'template-move', detail: found.folder || '.' },+ );+ return;+ }+ if (found.kind === 'unverifiable') {+ errorResponse(+ res,+ 500,+ 'urn:ok:error:internal-server-error',+ `Cannot inspect "${found.folder || '.'}/.ok" (${found.code ?? 'unknown errno'}) — refusing to resolve templates through it.`,+ { handler: 'template-move', detail: found.code ?? 'unknown-errno' },+ );+ return;+ }+ if (found.kind === 'found' && found.scope === 'inherited') {errorResponse(res,400,@@ -736,6 +952,43 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRorecentlyRemovedDocs?.setDeleted(templateDocNameFor(fromValidated.folderRel, body.fromName));+ const movedAbs = resolve(toValidated.resolvedContentDir, result.toPath);+ const movedIsSymlink = checkSymlinkLeaf(movedAbs).kind === 'symlink';++ attributeOkArtifactWrite(+ actor,+ okArtifactKey('template', toValidated.folderRel, body.toName),+ `template-rename: ${result.fromPath} -> ${result.toPath}`,+ [{ from: result.fromPath, to: result.toPath }],+ );+ scheduleOkArtifactFlush('template-move');+ signalChannel?.('files');++ if (movedIsSymlink) {+ log.warn(+ { path: movedAbs, folder: toValidated.folderRel || '.' },+ `[template-move] moved template "${result.toPath}" is a symlink — skipping content read-back and index registration.`,+ );+ if (body.body !== undefined || body.frontmatter !== undefined) {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:symlink-refused',+ `Template moved to "${result.toPath}", but it is a symlink — refusing to read or rewrite through it. Replace it with a regular file and retry the edit.`,+ { handler: 'template-move', detail: toValidated.folderRel || '.' },+ );+ return;+ }+ successResponse(+ res,+ 200,+ TemplateMoveSuccessSchema,+ { from: result.fromPath, to: result.toPath, committed: result.committed },+ { handler: 'template-move' },+ );+ return;+ }+let contentEditError: { code: string; message: string } | null = null;if (body.body !== undefined || body.frontmatter !== undefined) {let writeBody: string | null;@@ -743,9 +996,7 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRowriteBody = body.body;} else {try {- writeBody = instantiateDoc(- readFileSync(resolve(toValidated.resolvedContentDir, result.toPath), 'utf-8'),- );+ writeBody = instantiateDoc(readFileSync(movedAbs, 'utf-8'));} catch {writeBody = null;}@@ -771,19 +1022,10 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRotry {registerWrittenDocInFileIndex(templateDocNameFor(toValidated.folderRel, body.toName),- readFileSync(resolve(toValidated.resolvedContentDir, result.toPath), 'utf-8'),+ readFileSync(movedAbs, 'utf-8'),);} catch {}- attributeOkArtifactWrite(- actor,- okArtifactKey('template', toValidated.folderRel, body.toName),- `template-rename: ${result.fromPath} -> ${result.toPath}`,- [{ from: result.fromPath, to: result.toPath }],- );- scheduleOkArtifactFlush('template-move');- signalChannel?.('files');-if (contentEditError) {const isServerError =contentEditError.code === 'WRITE_ERROR' || contentEditError.code === 'READ_FAILED';@@ -941,9 +1183,33 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRoif (!validateTemplateName(name, res, 'template-import')) return;- const validated = validateFolderRel(body.targetFolder, res, 'folder', 'template-import');+ const validated = validateFolderRel(+ body.targetFolder,+ res,+ 'folder',+ 'template-import',+ 'ok-and-templates',+ );if (!validated) return;+ const templateFilePath = resolve(+ validated.resolvedContentDir,+ validated.folderRel,+ '.ok',+ 'templates',+ `${name}.md`,+ );+ if (checkSymlinkLeaf(templateFilePath).kind === 'symlink') {+ errorResponse(+ res,+ 400,+ 'urn:ok:error:symlink-refused',+ `${validated.folderRel || '.'}/.ok/templates/${name}.md is a symlink — refusing to write through it. Replace the symlink with a real file or directory and retry.`,+ { handler: 'template-import', detail: validated.folderRel || '.' },+ );+ return;+ }+if (checkTemplateConflictGate(templateDocNameFor(validated.folderRel, name),@@ -997,13 +1263,6 @@ export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRoreturn;}- const templateFilePath = resolve(- validated.resolvedContentDir,- validated.folderRel,- '.ok',- 'templates',- `${name}.md`,- );const templateCreated = !existsSync(templateFilePath);const templateRelPath = relative(validated.resolvedContentDir, templateFilePath).split(/[\\/]/)diff --git a/packages/server/src/http/history-routes.ts b/packages/server/src/http/history-routes.tsindex 1c02145b6..e0795fd64 100644--- a/packages/server/src/http/history-routes.ts+++ b/packages/server/src/http/history-routes.ts@@ -30,8 +30,9 @@ export interface HistoryRouteDeps {validateFolderRel: (raw: string,res: ServerResponse,- label?: 'path' | 'folder',- handler?: string,+ label: 'path' | 'folder',+ handler: string,+ components: 'ok' | 'ok-and-templates',) => { folderRel: string; resolvedContentDir: string } | null;safeDocPath: (docName: string, contentRoot: string) => { path: string } | { error: string };docTreePathCandidates: (docName: string, contentRoot: string) => readonly string[];@@ -107,7 +108,7 @@ export function createHistoryRoutes(deps: HistoryRouteDeps): HistoryRoutes {}if (folderParam !== null && !docName) {- const validated = validateFolderRel(folderParam, res, 'folder', 'history');+ const validated = validateFolderRel(folderParam, res, 'folder', 'history', 'ok');if (!validated) return;const rawFolderLimit = Number(url.searchParams.get('limit') ?? '50');const folderLimit = Math.min(200, Number.isFinite(rawFolderLimit) ? rawFolderLimit : 50);diff --git a/packages/server/src/mcp/tools/write.ts b/packages/server/src/mcp/tools/write.tsindex 3afdd5d6b..c02204046 100644--- a/packages/server/src/mcp/tools/write.ts+++ b/packages/server/src/mcp/tools/write.ts@@ -236,7 +236,7 @@ async function writeOneDoc(let templateHint: readonly { name: string; description?: string }[] | undefined;if (spec.template === undefined && !docExists) {- const available = resolveTemplatesAvailable(cwd, parentFolderOf(docName), { depth: 1 });+ const available = resolveTemplatesAvailable(cwd, parentFolderOf(docName));if (available.length > 0) {templateHint = available.map((t) => ({name: t.name,@@ -247,7 +247,7 @@ async function writeOneDoc(if (spec.template !== undefined) {const parentFolder = parentFolderOf(docName);- const available = resolveTemplatesAvailable(cwd, parentFolder, { depth: 1 });+ const available = resolveTemplatesAvailable(cwd, parentFolder);const matched = available.find((t) => t.name === spec.template);if (!matched) {return {diff --git a/packages/server/src/seed/apply.test.ts b/packages/server/src/seed/apply.test.tsindex 732224e8b..1345c34c6 100644--- a/packages/server/src/seed/apply.test.ts+++ b/packages/server/src/seed/apply.test.ts@@ -1,4 +1,12 @@-import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';+import {+ existsSync,+ lstatSync,+ mkdirSync,+ readdirSync,+ readFileSync,+ symlinkSync,+ writeFileSync,+} from 'node:fs';import { mkdtemp, rm } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -47,6 +55,22 @@ describe('applySeed — nested .ok/ era', () => {expect(existsSync(join(projectDir, 'log.md'))).toBe(true);});+ test('refuses to write through a committed dangling symlinked leaf (no write-through)', async () => {+ const plan = await planSeed({ projectDir });+ const fileEntry = plan.created.find((e) => e.kind === 'file');+ expect(fileEntry).toBeDefined();+ const leafAbs = join(projectDir, (fileEntry as { path: string }).path);+ const outsideTarget = join(tmpdir(), `seed-symlink-target-${process.pid}.yml`);+ mkdirSync(join(leafAbs, '..'), { recursive: true });+ symlinkSync(outsideTarget, leafAbs);++ const result = await applySeed(plan, { projectDir });++ expect(result.errors.some((e) => e.path === (fileEntry as { path: string }).path)).toBe(true);+ expect(existsSync(outsideTarget)).toBe(false);+ expect(lstatSync(leafAbs).isSymbolicLink()).toBe(true);+ });+test('frontmatter.yml carries the folder defaults verbatim from STARTER_FOLDERS', async () => {const plan = await planSeed({ projectDir });await applySeed(plan, { projectDir });diff --git a/packages/server/src/seed/apply.ts b/packages/server/src/seed/apply.tsindex 4a99934da..afafeae90 100644--- a/packages/server/src/seed/apply.ts+++ b/packages/server/src/seed/apply.ts@@ -1,6 +1,7 @@-import { existsSync, mkdirSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync } from 'node:fs';import { join, resolve } from 'node:path';import type { LintPluginId } from '@inkeep/open-knowledge-core';+import { tracedWriteFileSync } from '../fs-traced.ts';import { scanInPlaceSkills } from '../in-place-skills.ts';import { CONFIG_FILENAME } from '../init-project.ts';import {@@ -91,7 +92,12 @@ export async function applySeed(plan: ScaffoldPlan, opts: SeedOptions = {}): Procontinue;}try {- writeFileSync(absPath, content, 'utf-8');+ /* STOP: `wx` (O_EXCL) is load-bearing — `path-safety`'s ancestor walk+ short-circuits on the first existing component and cannot see a+ DANGLING symlinked leaf (existsSync reports it absent), so O_EXCL is+ what stops a write-through to the link target outside the project.+ Do not relax to `w`. */+ tracedWriteFileSync(absPath, content, { encoding: 'utf-8', flag: 'wx' });applied += 1;} catch (err) {errors.push({ path: entry.path, error: err instanceof Error ? err.message : String(err) });diff --git a/packages/server/src/symlink-leaf-guard-enforcement.test.ts b/packages/server/src/symlink-leaf-guard-enforcement.test.tsnew file mode 100644index 000000000..ada1d966f--- /dev/null+++ b/packages/server/src/symlink-leaf-guard-enforcement.test.ts@@ -0,0 +1,208 @@+import {+ lstatSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, relative } from 'node:path';+import { fileURLToPath } from 'node:url';+import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import { checkSymlinkLeaf } from './fs-safety.ts';++const SERVER_SRC = dirname(fileURLToPath(import.meta.url));++const LEAF_REFERRERS: Record<string, 'guarded' | 'seed-plane' | 'path-match'> = {+ 'content/folder-frontmatter-write.ts': 'guarded',+ 'content/nested-folder-rules.ts': 'guarded',+ 'http/folder-template-routes.ts': 'guarded',+ 'seed/plan.ts': 'seed-plane',+ 'seed/starter.ts': 'seed-plane',+ 'seed/index.ts': 'seed-plane',+ 'content-filter.ts': 'path-match',+ 'index.ts': 'path-match',+ 'mcp/tools/edit.ts': 'path-match',+ 'mcp/tools/write.ts': 'path-match',+ 'fs-safety.ts': 'path-match',+};++const LEAF_TOKEN = /frontmatter\.yml|STARTER_FOLDER_FRONTMATTER_FILENAME/;+const GUARD_CALL = /checkSymlinkLeaf\s*\(((?:[^()]|\([^()]*\))*)\)/g;+const GUARD_DEFINING_MODULE = 'fs-safety.ts';++const GUARD_CALL_SITES: Record<string, readonly string[]> = {+ 'api-extension.ts': ['okDir', 'okTemplatesDir'],+ 'content/folder-frontmatter-write.ts': ['fmPath'],+ 'content/nested-folder-rules.ts': ['dirname(yamlPath)', 'yamlPath'],+ 'content/templates-resolver.ts': ['okDir'],+ 'http/folder-template-routes.ts': [+ 'foundAbs',+ 'localFmPath',+ 'movedAbs',+ 'okAbs',+ 'templateFilePath',+ 'templateFilePath',+ 'templatesAbs',+ ],+};++const SEED_EXCL_WRITE = /tracedWriteFileSync\([^)]*flag:\s*'wx'/;++function listServerSourceFiles(root: string): string[] {+ const out: string[] = [];+ for (const entry of readdirSync(root, { withFileTypes: true })) {+ const abs = join(root, entry.name);+ if (entry.isDirectory()) {+ out.push(...listServerSourceFiles(abs));+ } else if (+ entry.isFile() &&+ entry.name.endsWith('.ts') &&+ !entry.name.endsWith('.test.ts') &&+ !entry.name.endsWith('.test-helper.ts')+ ) {+ out.push(abs);+ }+ }+ return out;+}++describe('symlink-leaf guard enforcement (frontmatter.yml referrers)', () => {+ const referrers = new Map<string, string>();+ for (const abs of listServerSourceFiles(SERVER_SRC)) {+ const source = readFileSync(abs, 'utf-8');+ if (LEAF_TOKEN.test(source)) {+ referrers.set(relative(SERVER_SRC, abs).split('\\').join('/'), source);+ }+ }++ test('every module naming the frontmatter.yml leaf is classified', () => {+ const unclassified = [...referrers.keys()].filter((f) => !(f in LEAF_REFERRERS));+ expect(+ unclassified,+ `These modules name the frontmatter.yml leaf but are not classified in LEAF_REFERRERS. ` ++ `Classify each as 'guarded' (refuses a symlinked leaf via checkSymlinkLeaf), 'seed-plane' ` ++ `(names the leaf only to PLAN it; the actual writer is seed/apply.ts, pinned below via ` ++ `its O_EXCL write), or 'path-match' (only matches path strings, never opens the ` ++ `leaf):\n${unclassified.map((f) => ` ${f}`).join('\n')}`,+ ).toEqual([]);++ const stale = Object.keys(LEAF_REFERRERS).filter((f) => !referrers.has(f));+ expect(+ stale,+ `Classified referrers that no longer name the leaf — remove them from LEAF_REFERRERS:\n${stale+ .map((f) => ` ${f}`)+ .join('\n')}`,+ ).toEqual([]);+ });++ test('per-file checkSymlinkLeaf call sites (by argument expression) match the pinned map exactly', () => {+ const actual: Record<string, string[]> = {};+ for (const abs of listServerSourceFiles(SERVER_SRC)) {+ const rel = relative(SERVER_SRC, abs).split('\\').join('/');+ if (rel === GUARD_DEFINING_MODULE) continue;+ const source = readFileSync(abs, 'utf-8');+ const args = [...source.matchAll(GUARD_CALL)].map((m) => (m[1] ?? '').trim()).sort();+ if (args.length > 0) {+ actual[rel] = args;+ }+ }+ expect(+ actual,+ `checkSymlinkLeaf call sites changed. Removing one deletes a symlink refusal; ` ++ `adding or re-pointing one changes the guard surface. Review the change and update ` ++ `GUARD_CALL_SITES in this test to the new per-file argument expressions.`,+ ).toEqual(+ Object.fromEntries(+ Object.entries(GUARD_CALL_SITES).map(([f, args]) => [f, [...args].sort()]),+ ),+ );+ });++ test("every 'guarded' referrer holds a pinned call site and no 'path-match' referrer does", () => {+ const guarded = Object.entries(LEAF_REFERRERS)+ .filter(([, cls]) => cls === 'guarded')+ .map(([f]) => f);+ expect(+ guarded.filter((f) => !(f in GUARD_CALL_SITES)),+ `'guarded' referrers must appear in GUARD_CALL_SITES with at least one call`,+ ).toEqual([]);++ const pathMatch = Object.entries(LEAF_REFERRERS)+ .filter(([, cls]) => cls === 'path-match')+ .map(([f]) => f)+ .filter((f) => f !== GUARD_DEFINING_MODULE);+ expect(+ pathMatch.filter((f) => f in GUARD_CALL_SITES),+ `'path-match' referrers must not call the guard — reclassify as 'guarded' if one now does`,+ ).toEqual([]);++ const seedPlane = Object.entries(LEAF_REFERRERS)+ .filter(([, cls]) => cls === 'seed-plane')+ .map(([f]) => f);+ expect(+ seedPlane.filter((f) => f in GUARD_CALL_SITES),+ `'seed-plane' referrers plan the leaf but never open it — their writer is seed/apply.ts ` ++ `(pinned via the O_EXCL leg below); reclassify as 'guarded' if one starts calling the guard`,+ ).toEqual([]);+ });++ test('seed/apply.ts keeps the O_EXCL (flag wx) write for scaffolded leaves', () => {+ const source = readFileSync(join(SERVER_SRC, 'seed', 'apply.ts'), 'utf-8');+ expect(+ SEED_EXCL_WRITE.test(source),+ `seed/apply.ts must write scaffolded files via tracedWriteFileSync with flag: 'wx' — ` ++ `O_EXCL is what stops a write-through of a committed DANGLING symlinked leaf that ` ++ `existsSync reports as absent and seed/path-safety's ancestor walk cannot see.`,+ ).toBe(true);+ });+});++describe('checkSymlinkLeaf (tri-state semantics)', () => {+ let dir: string;++ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'ok-symlink-leaf-'));+ });++ afterEach(() => {+ rmSync(dir, { recursive: true, force: true });+ });++ test('a regular file is not a symlink', () => {+ const p = join(dir, 'frontmatter.yml');+ writeFileSync(p, 'title: x\n');+ expect(checkSymlinkLeaf(p)).toEqual({ kind: 'not-symlink' });+ });++ test('a symlinked leaf is reported as symlink, including a dangling one', () => {+ const live = join(dir, 'live.yml');+ writeFileSync(live, 'a: 1\n');+ const link = join(dir, 'link.yml');+ symlinkSync(live, link);+ expect(checkSymlinkLeaf(link)).toEqual({ kind: 'symlink' });++ const dangling = join(dir, 'dangling.yml');+ symlinkSync(join(dir, 'never-created.yml'), dangling);+ expect(lstatSync(dangling).isSymbolicLink()).toBe(true);+ expect(checkSymlinkLeaf(dangling)).toEqual({ kind: 'symlink' });+ });++ test('an absent leaf is not a symlink (ENOENT is benign)', () => {+ expect(checkSymlinkLeaf(join(dir, 'absent', 'frontmatter.yml'))).toEqual({+ kind: 'not-symlink',+ });+ });++ test('a non-ENOENT lstat failure is reported as unverifiable, not symlink', () => {+ const file = join(dir, 'a-file');+ writeFileSync(file, 'not a dir');+ const result = checkSymlinkLeaf(join(file, 'frontmatter.yml'));+ expect(result.kind).toBe('unverifiable');+ if (result.kind === 'unverifiable') {+ expect(result.code).toBe('ENOTDIR');+ }+ });+});