Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Refuse frontmatter writes that would silently drop a field (#7414)

Nick Gomez909be298922f
diff --git a/.changeset/frontmatter-key-refusal.md b/.changeset/frontmatter-key-refusal.md
new file mode 100644
index 000000000..8a1994637
--- /dev/null
+++ b/.changeset/frontmatter-key-refusal.md
@@ -0,0 +1,5 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+Reject `__proto__` fields in frontmatter patches and merged document writes before saving, preventing silent data loss.
diff --git a/docs/content/reference/mcp.mdx b/docs/content/reference/mcp.mdx
index a8088732a..da80463b8 100644
--- a/docs/content/reference/mcp.mdx
+++ b/docs/content/reference/mcp.mdx
@@ -62,6 +62,8 @@ The write verbs nest their result under the same target key you wrote, mirroring
Use `edit({ document: { path, frontmatter } })` for frontmatter edits: it applies a top-level merge patch (set or create a key with a value, delete a key by passing `null`; a nested object replaces that key's whole subtree, and `null` inside a subtree is rejected). A document body find/replace (`edit({ document: { path, find, replace } })`) is body-only and refuses patterns that touch frontmatter; `write` with `position: "replace"` is the only write mode that includes the `---\n…\n---` block (other positions ignore any frontmatter in the payload). Folders and templates take frontmatter the same way: `edit({ folder: { path, frontmatter } })`.
+A field named `__proto__`, at the top level or nested at any depth, is refused and nothing is written: the `frontmatter` argument of `edit` and `write` rejects it. `write` also refuses with `EMBEDDED_FRONTMATTER_UNSUPPORTED_KEY` when the `---` block in `content` holds such a field and a `frontmatter` argument would be merged into it.
+
## Edit summaries
The write tools (`write`, `edit`, `move`, `install`, `checkpoint`, `restore_version`) accept an optional `summary` describing the intent of the edit, e.g. `"Fixed token-refresh race"`. Summaries appear on the document's timeline so readers can scan recent agent activity.
diff --git a/packages/core/src/bridge/frontmatter-region.ts b/packages/core/src/bridge/frontmatter-region.ts
index a5ad8f5f9..8b66f34a0 100644
--- a/packages/core/src/bridge/frontmatter-region.ts
+++ b/packages/core/src/bridge/frontmatter-region.ts
@@ -12,6 +12,7 @@ import { FRONTMATTER_RE, unwrapFrontmatterFences } from '../extensions/frontmatt
import {
type FrontmatterMap,
FrontmatterMapSchema,
+ FrontmatterPatchSchema,
type FrontmatterValue,
FrontmatterValueSchema,
RESERVED_FRONTMATTER_KEY,
@@ -200,26 +201,27 @@ export function applyPatchToFm(
return { ok: false, error: { kind: 'parse_failed', reason: 'fm region unparseable' } };
}
+ const parsed = FrontmatterPatchSchema.safeParse(patch);
+ if (!parsed.success) {
+ return {
+ ok: false,
+ error: {
+ kind: 'invalid_value',
+ key: String(parsed.error.issues[0]?.path[0] ?? ''),
+ reason: parsed.error.issues[0]?.message ?? 'invalid value',
+ },
+ };
+ }
+
try {
ensureContents(doc);
- for (const [key, value] of Object.entries(patch)) {
+ for (const [key, value] of Object.entries(parsed.data)) {
if (value === null) {
doc.delete(key);
continue;
}
- const parsed = FrontmatterValueSchema.safeParse(value);
- if (!parsed.success) {
- return {
- ok: false,
- error: {
- kind: 'invalid_value',
- key,
- reason: parsed.error.issues[0]?.message ?? 'invalid value',
- },
- };
- }
- doc.set(key, buildValueNode(doc, doc.get(key, true), parsed.data));
+ doc.set(key, buildValueNode(doc, doc.get(key, true), value));
}
return finalizeFenced(doc);
diff --git a/packages/core/src/frontmatter/key-refusal.test.ts b/packages/core/src/frontmatter/key-refusal.test.ts
new file mode 100644
index 000000000..6760473b7
--- /dev/null
+++ b/packages/core/src/frontmatter/key-refusal.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, test } from 'vitest';
+import { Document } from 'yaml';
+import { applyPatchToFm, applyPathSetToFm } from '../bridge/frontmatter-region.ts';
+import { FrontmatterPatchRequestSchema } from '../schemas/api/agent-write.ts';
+import { type FrontmatterPatch, FrontmatterPatchSchema, FrontmatterValueSchema } from './schema.ts';
+import { applyPatchToDocument } from './yaml-codec.ts';
+
+const cases: { name: string; patch: FrontmatterPatch }[] = [
+ { name: 'top-level', patch: JSON.parse('{"__proto__":0,"keep":1}') },
+ { name: 'nested object', patch: JSON.parse('{"key":{"__proto__":0,"keep":1}}') },
+ { name: 'literal list', patch: JSON.parse('{"key":[{"__proto__":0}]}') },
+ { name: 'nested lists', patch: JSON.parse('{"key":[[{"__proto__":0,"keep":1}]]}') },
+ { name: 'object value', patch: JSON.parse('{"key":{"__proto__":{"value":true}}}') },
+ { name: 'later invalid field', patch: JSON.parse('{"keep":2,"key":[{"__proto__":0}]}') },
+];
+
+describe('frontmatter key refusal', () => {
+ test.each(cases)('rejects $name records at every shared schema entry', ({ patch }) => {
+ expect.soft(FrontmatterValueSchema.safeParse(patch).success).toBe(false);
+ expect.soft(FrontmatterPatchSchema.safeParse(patch).success).toBe(false);
+ expect
+ .soft(FrontmatterPatchRequestSchema.safeParse({ docName: 'note', patch }).success)
+ .toBe(false);
+ });
+
+ test.each(cases)('refuses $name patches before changing YAML', ({ patch }) => {
+ const doc = new Document({ keep: 'baseline', key: 'before' });
+ const before = doc.toString();
+ expect.soft(applyPatchToFm(`---\n${before}---\n`, patch).ok).toBe(false);
+ expect.soft(() => applyPatchToDocument(doc, patch)).toThrow(Error);
+ expect.soft(doc.toString()).toBe(before);
+ });
+
+ test('refuses the literal list through the path-value helper', () => {
+ const value = JSON.parse('[{"__proto__":0}]');
+ expect(applyPathSetToFm('---\nkey: before\n---\n', ['key'], value).ok).toBe(false);
+ });
+
+ test('preserves ordinary objects and the existing list scalar conversion', () => {
+ const input = {
+ key: {
+ number: 7,
+ flag: false,
+ nested: { count: 3, yes: true },
+ list: [0, true, false, ['x', 2], { count: 3, yes: true }],
+ constructor: { prototype: 'ordinary' },
+ prototype: 'ordinary',
+ },
+ };
+ const expected = {
+ key: {
+ ...input.key,
+ list: ['0', 'true', 'false', ['x', '2'], { count: 3, yes: true }],
+ },
+ };
+ expect(FrontmatterPatchSchema.parse(input)).toEqual(expected);
+ });
+});
diff --git a/packages/core/src/frontmatter/schema.test.ts b/packages/core/src/frontmatter/schema.test.ts
index 9ea256288..57c491644 100644
--- a/packages/core/src/frontmatter/schema.test.ts
+++ b/packages/core/src/frontmatter/schema.test.ts
@@ -2,6 +2,8 @@ import { describe, expect, test } from 'vitest';
import {
FRONTMATTER_TYPES,
FrontmatterMapSchema,
+ FrontmatterPatchSchema,
+ FrontmatterValueSchema,
frontmatterValuesEqual,
inferType,
isFrontmatterValueEmpty,
@@ -157,3 +159,59 @@ describe('FrontmatterMapSchema — Obsidian null coercion', () => {
expect(result.data).toEqual({ title: 'Hello', tags: ['a', 'b'], meta: { n: 1 } });
});
});
+
+function countedLeafChain(depth: number, wrap: (child: unknown) => unknown) {
+ let inspections = 0;
+ const leaf = new Proxy(
+ { leaf: 'value' },
+ {
+ ownKeys(target) {
+ inspections += 1;
+ return Reflect.ownKeys(target);
+ },
+ getOwnPropertyDescriptor(target, key) {
+ inspections += 1;
+ return Reflect.getOwnPropertyDescriptor(target, key);
+ },
+ get(target, key, receiver) {
+ inspections += 1;
+ return Reflect.get(target, key, receiver);
+ },
+ has(target, key) {
+ inspections += 1;
+ return Reflect.has(target, key);
+ },
+ },
+ );
+ let root: unknown = leaf;
+ for (let level = 0; level < depth; level += 1) root = { child: wrap(root) };
+ return { root, inspections: () => inspections };
+}
+
+const nestingShapes = [
+ { name: 'nested objects', wrap: (child: unknown) => child },
+ { name: 'objects inside lists', wrap: (child: unknown) => [child] },
+];
+
+const entrySchemas = [
+ { name: 'FrontmatterPatchSchema', schema: FrontmatterPatchSchema },
+ { name: 'FrontmatterValueSchema', schema: FrontmatterValueSchema },
+];
+
+describe('frontmatter record validation cost', () => {
+ describe.each(entrySchemas)('$name', ({ schema }) => {
+ test.each(nestingShapes)(
+ 'inspects the innermost record of $name as often at depth 40 as at depth 4',
+ ({ wrap }) => {
+ const leafInspectionsAt = (depth: number) => {
+ const chain = countedLeafChain(depth, wrap);
+ expect(schema.safeParse(chain.root).success).toBe(true);
+ return chain.inspections();
+ };
+ const shallow = leafInspectionsAt(4);
+ expect(shallow).toBeGreaterThan(0);
+ expect(leafInspectionsAt(40)).toBe(shallow);
+ },
+ );
+ });
+});
diff --git a/packages/core/src/frontmatter/schema.ts b/packages/core/src/frontmatter/schema.ts
index 747da4260..ebe110f23 100644
--- a/packages/core/src/frontmatter/schema.ts
+++ b/packages/core/src/frontmatter/schema.ts
@@ -16,10 +16,65 @@ export type FrontmatterValue =
const FrontmatterScalarLeafSchema = z.union([z.string(), z.number(), z.boolean()]);
+function findOwnProtoKeyPath(value: unknown): (string | number)[] | null {
+ if (Array.isArray(value)) {
+ for (const [index, element] of value.entries()) {
+ const path = findOwnProtoKeyPath(element);
+ if (path !== null) return [index, ...path];
+ }
+ return null;
+ }
+ if (value !== null && typeof value === 'object') {
+ if (Object.hasOwn(value, '__proto__')) return ['__proto__'];
+ for (const [key, child] of Object.entries(value)) {
+ const path = findOwnProtoKeyPath(child);
+ if (path !== null) return [key, ...path];
+ }
+ }
+ return null;
+}
+
+function findTopLevelProtoKeyPath(value: unknown): (string | number)[] | null {
+ if (value !== null && typeof value === 'object' && Object.hasOwn(value, '__proto__')) {
+ return ['__proto__'];
+ }
+ return null;
+}
+
+function protoKeyRefusingRecord<T extends z.ZodType>(
+ valueSchema: T,
+ findProtoKeyPath: (value: unknown) => (string | number)[] | null,
+) {
+ return z
+ .preprocess(
+ (value, ctx) => {
+ const path = findProtoKeyPath(value);
+ if (path !== null) {
+ ctx.addIssue({
+ code: 'custom',
+ path,
+ message: 'Unsupported frontmatter key: __proto__',
+ });
+ }
+ return value;
+ },
+ z.record(z.string(), valueSchema),
+ )
+ .nonoptional();
+}
+
+export function frontmatterRecord<T extends z.ZodType>(valueSchema: T) {
+ return protoKeyRefusingRecord(valueSchema, findOwnProtoKeyPath);
+}
+
+export function topLevelFrontmatterRecord<T extends z.ZodType>(valueSchema: T) {
+ return protoKeyRefusingRecord(valueSchema, findTopLevelProtoKeyPath);
+}
+
const FrontmatterArrayElementSchema: z.ZodType<FrontmatterValue> = z.lazy(() =>
z.union([
FrontmatterScalarLeafSchema.transform((v) => String(v)),
- z.record(z.string(), FrontmatterValueSchema),
+ topLevelFrontmatterRecord(FrontmatterValueSchema),
z.array(FrontmatterArrayElementSchema),
]),
);
@@ -30,7 +85,7 @@ export const FrontmatterValueSchema: z.ZodType<FrontmatterValue> = z.lazy(() =>
z.number(),
z.boolean(),
z.array(FrontmatterArrayElementSchema),
- z.record(z.string(), FrontmatterValueSchema),
+ topLevelFrontmatterRecord(FrontmatterValueSchema),
]),
);
@@ -73,8 +128,7 @@ export const FrontmatterMapSchema = z.preprocess(
);
export type FrontmatterMap = Record<string, FrontmatterValue>;
-export const FrontmatterPatchSchema = z.record(
- z.string(),
+export const FrontmatterPatchSchema = frontmatterRecord(
z.union([FrontmatterValueSchema, z.null()]),
);
export type FrontmatterPatch = Record<string, FrontmatterValue | null>;
diff --git a/packages/core/src/frontmatter/yaml-codec.ts b/packages/core/src/frontmatter/yaml-codec.ts
index d29a8c7ef..3eb7a17f7 100644
--- a/packages/core/src/frontmatter/yaml-codec.ts
+++ b/packages/core/src/frontmatter/yaml-codec.ts
@@ -8,7 +8,7 @@ import {
type YAMLMap,
type YAMLSeq,
} from 'yaml';
-import { type FrontmatterMap, FrontmatterMapSchema, FrontmatterValueSchema } from './schema.ts';
+import { type FrontmatterMap, FrontmatterMapSchema, FrontmatterPatchSchema } from './schema.ts';
export const STRINGIFY_OPTIONS: ToStringOptions = {
defaultKeyType: 'PLAIN',
@@ -67,16 +67,16 @@ export function serializeFrontmatterMap(map: FrontmatterMap): string {
}
export function applyPatchToDocument(doc: Document, patch: Record<string, unknown>): string {
- for (const [key, value] of Object.entries(patch)) {
+ const result = FrontmatterPatchSchema.safeParse(patch);
+ if (!result.success) {
+ throw new Error(`Invalid frontmatter patch: ${result.error.message}`);
+ }
+ for (const [key, value] of Object.entries(result.data)) {
if (value === null) {
doc.delete(key);
continue;
}
- const result = FrontmatterValueSchema.safeParse(value);
- if (!result.success) {
- throw new Error(`Invalid frontmatter value for "${key}": ${result.error.message}`);
- }
- doc.set(key, buildValueNode(doc, doc.get(key, true), result.data));
+ doc.set(key, buildValueNode(doc, doc.get(key, true), value));
}
return doc.toString(STRINGIFY_OPTIONS);
}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 4dde207b3..8b6766ae4 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -733,6 +733,7 @@ export {
FrontmatterTypeSchema,
type FrontmatterValue,
FrontmatterValueSchema,
+ frontmatterRecord,
frontmatterValuesEqual,
inferType,
isFrontmatterValueEmpty,
diff --git a/packages/core/src/schemas/api/agent-write.ts b/packages/core/src/schemas/api/agent-write.ts
index 5c973945a..f97c7ee72 100644
--- a/packages/core/src/schemas/api/agent-write.ts
+++ b/packages/core/src/schemas/api/agent-write.ts
@@ -7,7 +7,7 @@ import type { StandardSchemaV1 } from '@standard-schema/spec';
import { z } from 'zod';
import { SUPPORTED_DOC_EXTENSIONS } from '../../constants/doc-extensions.ts';
-import { FRONTMATTER_TYPES, FrontmatterValueSchema } from '../../frontmatter/schema.ts';
+import { FRONTMATTER_TYPES, FrontmatterPatchSchema } from '../../frontmatter/schema.ts';
import { ProblemTypeSchema } from './_envelope.ts';
import {
agentContentField,
@@ -364,7 +364,7 @@ export type AgentWriteBatchSuccess = z.infer<typeof AgentWriteBatchSuccessSchema
export const FrontmatterPatchRequestSchema = z
.object({
docName: safeDocNameField,
- patch: z.record(z.string(), z.union([FrontmatterValueSchema, z.null()])),
+ patch: FrontmatterPatchSchema,
types: z.record(z.string(), z.enum(FRONTMATTER_TYPES)).optional(),
summary: summaryField,
...agentIdentityFields,
diff --git a/packages/core/src/schemas/api/tags-search.ts b/packages/core/src/schemas/api/tags-search.ts
index 7b38cd9e0..4c8948267 100644
--- a/packages/core/src/schemas/api/tags-search.ts
+++ b/packages/core/src/schemas/api/tags-search.ts
@@ -1,6 +1,7 @@
import type { StandardSchemaV1 } from '@standard-schema/spec';
import { z } from 'zod';
import { MANAGED_ARTIFACT_SCOPES } from '../../constants/cc1.ts';
+import { topLevelFrontmatterRecord } from '../../frontmatter/schema.ts';
import {
SkillTargetEditorSchema,
SkillUserTargetEditorSchema,
@@ -77,7 +78,7 @@ export type FolderConfigGetSuccess = z.infer<typeof FolderConfigGetSuccessSchema
export const FolderConfigPutRequestSchema = z
.object({
path: z.string(),
- frontmatter: z.record(z.string(), z.unknown()).optional(),
+ frontmatter: topLevelFrontmatterRecord(z.unknown()).optional(),
})
.loose() satisfies StandardSchemaV1;
export type FolderConfigPutRequest = z.infer<typeof FolderConfigPutRequestSchema>;
diff --git a/packages/server/src/api-agent-write-composition.test.ts b/packages/server/src/api-agent-write-composition.test.ts
index f5121f9c9..eac185709 100644
--- a/packages/server/src/api-agent-write-composition.test.ts
+++ b/packages/server/src/api-agent-write-composition.test.ts
@@ -2,6 +2,7 @@ import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterAll, beforeAll, expect, test } from 'vitest';
+import { parseDocument } from 'yaml';
import type { BootedServer } from './boot.ts';
import { bootCompositionRig, rawRequest } from './composition-rig.test-helper.ts';
import { __formatContributorsForTests } from './contributor-tracker.ts';
@@ -96,6 +97,52 @@ test('frontmatter patch preserves the existing body bytes', async () => {
expect(readFileSync(join(root, `${docName}.md`), 'utf8')).toBe(`---\ntitle: After\n---\n${body}`);
});
+test.each([
+ ['top-level', '{"__proto__":0,"keep":1}', 'patch.__proto__'],
+ ['nested-object', '{"key":{"__proto__":0,"keep":1}}', 'patch.key.__proto__'],
+ ['literal-list', '{"key":[{"__proto__":0}]}', 'patch.key.0.__proto__'],
+ ['nested-lists', '{"key":[[{"__proto__":0,"keep":1}]]}', 'patch.key.0.0.__proto__'],
+])(
+ 'frontmatter key refusal returns a typed error without writing %s input',
+ async (name, rawPatch, field) => {
+ const docName = `refused-frontmatter-${name}`;
+ const markdown = '---\nkeep: baseline\nkey: before\n---\n\n# Body\n';
+ await request('/api/agent-write-md', { docName, markdown, position: 'replace' });
+ const session = await server.serverInstance.sessionManager.getSession(docName);
+ const response = await rawRequest(server.port, '/api/frontmatter-patch', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: `{"docName":${JSON.stringify(docName)},"patch":${rawPatch}}`,
+ });
+ expect.soft(response.status).toBe(400);
+ const problem = JSON.parse(response.body);
+ expect.soft(problem).toMatchObject({
+ type: 'urn:ok:error:invalid-request',
+ status: 400,
+ });
+ expect.soft(problem.detail).toContain(`${field}: Unsupported frontmatter key`);
+ expect.soft(problem.detail).not.toContain('Invalid input');
+ expect.soft(session.dc.document.getText('source').toString()).toBe(markdown);
+ expect.soft(readFileSync(join(root, `${docName}.md`), 'utf8')).toBe(markdown);
+ },
+);
+
+test('frontmatter key refusal preserves ordinary values and body bytes', async () => {
+ const docName = 'frontmatter-ordinary-values';
+ const body = '\n# Body\n';
+ await request('/api/agent-write-md', { docName, markdown: body, position: 'replace' });
+ await request('/api/frontmatter-patch', {
+ docName,
+ patch: { key: { number: 7, flag: false, list: [0, true, { count: 3, yes: true }] } },
+ });
+ const stored = readFileSync(join(root, `${docName}.md`), 'utf8');
+ const end = stored.indexOf('\n---\n', 4);
+ expect(stored.slice(end + 5)).toBe(body);
+ expect(parseDocument(stored.slice(4, end)).toJS()).toEqual({
+ key: { number: 7, flag: false, list: ['0', 'true', { count: 3, yes: true }] },
+ });
+});
+
test('save and rollback retain shadow history and the principal loaded after route construction', async () => {
const docName = 'native-version';
const markdown = '# Saved version\n\nExact \\* bytes.\n';
diff --git a/packages/server/src/api-folder-config.test.ts b/packages/server/src/api-folder-config.test.ts
index 3106d14d4..1b6593781 100644
--- a/packages/server/src/api-folder-config.test.ts
+++ b/packages/server/src/api-folder-config.test.ts
@@ -15,6 +15,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { parse as parseYaml } from 'yaml';
import { createApiExtension } from './api-extension.test-helper.ts';
interface CapturedResponse {
@@ -24,7 +25,10 @@ interface CapturedResponse {
}
function makeReq(url: string, method: string, body?: unknown): IncomingMessage {
- const raw = body === undefined ? '' : JSON.stringify(body);
+ return makeRawReq(url, method, body === undefined ? '' : JSON.stringify(body));
+}
+
+function makeRawReq(url: string, method: string, raw: string): IncomingMessage {
const readable = Readable.from(Buffer.from(raw)) as unknown as IncomingMessage;
readable.method = method;
readable.url = url;
@@ -74,6 +78,17 @@ describe('GET/PUT /api/folder-config', () => {
return captured;
}
+ async function dispatchRaw(
+ ext: ReturnType<typeof buildExt>,
+ url: string,
+ method: string,
+ rawBody: string,
+ ): Promise<CapturedResponse> {
+ const { res, captured } = makeRes();
+ await ext.onRequest({ request: makeRawReq(url, method, rawBody), response: res });
+ return captured;
+ }
+
beforeEach(() => {
tmpDir = mkdtempSync(join(tmpdir(), 'ok-folder-config-'));
contentDir = join(tmpDir, 'content');
@@ -573,6 +588,66 @@ describe('GET/PUT /api/folder-config', () => {
expect(existsSync(join(contentDir, 'docs', '.ok', 'frontmatter.yml'))).toBe(false);
});
+ test.each([
+ ['only-reserved-key', '{"__proto__":{"status":null}}'],
+ ['reserved-key-with-ordinary-key', '{"__proto__":{"status":null},"owner":"nina"}'],
+ ])(
+ 'PUT refuses a reserved frontmatter key and leaves the sidecar byte-identical (%s)',
+ async (_name, rawFrontmatter) => {
+ const fmPath = join(contentDir, 'docs', '.ok', 'frontmatter.yml');
+ const before = readFileSync(fmPath, 'utf-8');
+ const captured = await dispatchRaw(
+ buildExt(),
+ '/api/folder-config',
+ 'PUT',
+ `{"path":"docs","frontmatter":${rawFrontmatter}}`,
+ );
+ expect.soft(captured.status).toBe(400);
+ const problem = JSON.parse(captured.body);
+ expect.soft(problem).toMatchObject({ type: 'urn:ok:error:invalid-request', status: 400 });
+ expect.soft(problem.detail).toContain('frontmatter.__proto__: Unsupported frontmatter key');
+ expect.soft(existsSync(fmPath)).toBe(true);
+ expect.soft(readFileSync(fmPath, 'utf-8')).toBe(before);
+ },
+ );
+
+ test.each([
+ [
+ 'inside-a-nested-object',
+ '{"meta":{"__proto__":{"x":1},"y":2}}',
+ '{"status":"active","owner":"omar","meta":{"__proto__":{"x":1},"y":2}}',
+ ],
+ [
+ 'inside-an-object-in-a-list',
+ '{"items":[{"__proto__":0,"k":"v"}]}',
+ '{"status":"active","owner":"omar","items":[{"__proto__":0,"k":"v"}]}',
+ ],
+ ])(
+ 'PUT stores a nested reserved-name key and GET returns it unchanged (%s)',
+ async (_name, rawFrontmatter, expectedMergedJson) => {
+ const ext = buildExt();
+ const fmPath = join(contentDir, 'docs', '.ok', 'frontmatter.yml');
+ const expected = JSON.parse(expectedMergedJson);
+
+ const put = await dispatchRaw(
+ ext,
+ '/api/folder-config',
+ 'PUT',
+ `{"path":"docs","frontmatter":${rawFrontmatter}}`,
+ );
+ expect(put.status, put.body).toBe(200);
+ expect(JSON.parse(put.body).applied).toEqual([
+ { path: 'docs/.ok/frontmatter.yml', action: 'written' },
+ ]);
+
+ expect(parseYaml(readFileSync(fmPath, 'utf-8'))).toEqual(expected);
+
+ const get = await dispatch(ext, '/api/folder-config?path=docs', 'GET');
+ expect(get.status).toBe(200);
+ expect(JSON.parse(get.body).frontmatter_local).toEqual(expected);
+ },
+ );
+
test('PUT without a frontmatter field applies nothing', async () => {
const ext = buildExt();
const captured = await dispatch(ext, '/api/folder-config', 'PUT', { path: 'plain' });
diff --git a/packages/server/src/api-mcp-frontmatter-key.test.ts b/packages/server/src/api-mcp-frontmatter-key.test.ts
new file mode 100644
index 000000000..45340a688
--- /dev/null
+++ b/packages/server/src/api-mcp-frontmatter-key.test.ts
@@ -0,0 +1,135 @@
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { createServer, type Server } from 'node:http';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { afterAll, beforeAll, expect, test } from 'vitest';
+import { parseDocument } from 'yaml';
+import type { BootedServer } from './boot.ts';
+import { bootCompositionRig } from './composition-rig.test-helper.ts';
+import { ConfigSchema } from './config/schema.ts';
+import { connectMcpTestClient } from './mcp/client.test-helper.ts';
+import { createMcpHttpHandler, type McpHttpHandler } from './mcp-http.ts';
+
+const cases = [
+ ['top-level', '__proto__: 0'],
+ ['nested-object', 'key: { __proto__: 0, keep: 1 }'],
+ ['nested-list', 'key: [{ __proto__: 0 }]'],
+ ['nested-lists', 'key: [[{ __proto__: 0, keep: 1 }]]'],
+ ['object-value', 'key: { __proto__: { retained: value }, keep: 1 }'],
+ ['alias-key', 'anchor: &key __proto__\n*key : 0'],
+ ['aliased-complex-key', '? &obj { __proto__: 0 }\n: ordinary\nkey: *obj'],
+ ['escaped-key', '"\\u005f_proto__": 0'],
+] as const;
+const original = '---\nkeep: baseline\n---\n\n# Original bytes\n';
+const body = '\n# Body\n\nBackslash \\* and <custom>raw</custom>.\n\n';
+let root: string;
+let server: BootedServer;
+let handler: McpHttpHandler;
+let transportServer: Server;
+let client: Client;
+
+beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'ok-mcp-frontmatter-key-'));
+ for (const [name] of cases) writeFileSync(join(root, `${name}.md`), original);
+ writeFileSync(join(root, 'ordinary.md'), original);
+ server = await bootCompositionRig(root);
+ await server.ready;
+ handler = createMcpHttpHandler({
+ contentDir: server.contentDir,
+ projectDir: server.contentDir,
+ config: ConfigSchema.parse({}),
+ getServerUrl: () => `http://127.0.0.1:${server.port}`,
+ });
+ transportServer = createServer((req, res) => {
+ void handler.handle(req, res);
+ });
+ await new Promise<void>((resolve, reject) => {
+ transportServer.once('error', reject);
+ transportServer.listen(0, '127.0.0.1', resolve);
+ });
+ const address = transportServer.address();
+ if (address === null || typeof address === 'string') throw new Error('MCP listener absent');
+ client = await connectMcpTestClient(`http://127.0.0.1:${address.port}/mcp`);
+}, 60_000);
+
+afterAll(async () => {
+ await client?.close();
+ await handler?.close();
+ if (transportServer) {
+ transportServer.closeAllConnections();
+ await new Promise<void>((resolve, reject) => {
+ transportServer.close((error) => (error ? reject(error) : resolve()));
+ });
+ }
+ await server?.destroy();
+ if (root) rmSync(root, { recursive: true, force: true });
+});
+
+test.for(cases)(
+ 'embedded frontmatter key refusal leaves Y.Text and disk unchanged for %s',
+ async ([name, yaml], { signal }) => {
+ const session = await server.serverInstance.sessionManager.getSession(name);
+ const source = session.dc.document.getText('source');
+ expect(source.toString()).toBe(original);
+ const beforeDisk = readFileSync(join(root, `${name}.md`));
+ expect(beforeDisk.toString('utf8')).toBe(original);
+ const result = await client.callTool(
+ {
+ name: 'write',
+ arguments: {
+ document: {
+ path: name,
+ content: `---\n${yaml}\n---\n${body}`,
+ frontmatter: { added: 'ordinary' },
+ position: 'replace',
+ },
+ },
+ },
+ undefined,
+ { signal },
+ );
+ expect.soft(result.isError).toBe(true);
+ expect
+ .soft(JSON.stringify(result.content))
+ .toMatch(/\bEMBEDDED_FRONTMATTER_UNSUPPORTED_KEY — /);
+ expect.soft(source.toString()).toBe(original);
+ expect.soft(readFileSync(join(root, `${name}.md`))).toEqual(beforeDisk);
+ },
+);
+
+test('embedded frontmatter composition preserves ordinary values and body bytes', async ({
+ signal,
+}) => {
+ const session = await server.serverInstance.sessionManager.getSession('ordinary');
+ const result = await client.callTool(
+ {
+ name: 'write',
+ arguments: {
+ document: {
+ path: 'ordinary',
+ content: `---\nnumber: 7\nflag: false\nempty: null\nlabel: __proto__\n? { __proto__: 0 }\n: ordinary\nkey: [0, true, null, { count: 3, yes: true }]\n---\n${body}`,
+ frontmatter: { added: 'ordinary' },
+ position: 'replace',
+ },
+ },
+ },
+ undefined,
+ { signal },
+ );
+ expect(result.isError, JSON.stringify(result.content)).not.toBe(true);
+ const stored = readFileSync(join(root, 'ordinary.md'), 'utf8');
+ expect(session.dc.document.getText('source').toString()).toBe(stored);
+ const end = stored.indexOf('\n---\n', 4);
+ expect(end).toBeGreaterThan(4);
+ expect(stored.slice(end + 5)).toBe(body);
+ expect(parseDocument(stored.slice(4, end)).toJS()).toEqual({
+ number: 7,
+ flag: false,
+ empty: '',
+ label: '__proto__',
+ '{ __proto__: 0 }': 'ordinary',
+ key: ['0', 'true', { count: 3, yes: true }],
+ added: 'ordinary',
+ });
+});
diff --git a/packages/server/src/mcp/tools/verb-schemas.test.ts b/packages/server/src/mcp/tools/verb-schemas.test.ts
index dad04a6c6..ca8106806 100644
--- a/packages/server/src/mcp/tools/verb-schemas.test.ts
+++ b/packages/server/src/mcp/tools/verb-schemas.test.ts
@@ -1,11 +1,20 @@
-import { describe, expect, test } from 'vitest';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import { ConfigSchema } from '../../config/schema.ts';
import { SUPPORTED_DOC_EXTENSIONS } from '../../doc-extensions.ts';
+import { installPrettyZodErrors } from '../pretty-zod-errors.ts';
import {
DocExtensionArg,
FrontmatterArg,
resolveSkillFilePath,
resolveTemplatePath,
} from './verb-schemas.ts';
+import { register as registerWrite } from './write.ts';
describe('FrontmatterArg — recursive value contract (PRD-6947)', () => {
test('flat scalar values still parse (regression guard for the pre-PRD-6947 contract)', () => {
@@ -72,6 +81,115 @@ describe('FrontmatterArg — recursive value contract (PRD-6947)', () => {
});
});
+describe('frontmatter key refusal at MCP admission', () => {
+ test.each([
+ ['top-level', '{"__proto__":0,"keep":1}'],
+ ['nested object', '{"key":{"__proto__":0,"keep":1}}'],
+ ['literal list', '{"key":[{"__proto__":0}]}'],
+ ['nested lists', '{"key":[[{"__proto__":0,"keep":1}]]}'],
+ ])('rejects %s records', (_name, raw) => {
+ expect(FrontmatterArg.safeParse(JSON.parse(raw)).success).toBe(false);
+ });
+
+ test('preserves ordinary values before downstream storage conversion', () => {
+ const input = { key: { number: 7, flag: false, list: [0, true, { count: 3 }] } };
+ expect(FrontmatterArg.parse(input)).toEqual(input);
+ });
+});
+
+function countedLeafChain(depth: number, wrap: (child: unknown) => unknown) {
+ let inspections = 0;
+ const leaf = new Proxy(
+ { leaf: 'value' },
+ {
+ ownKeys(target) {
+ inspections += 1;
+ return Reflect.ownKeys(target);
+ },
+ getOwnPropertyDescriptor(target, key) {
+ inspections += 1;
+ return Reflect.getOwnPropertyDescriptor(target, key);
+ },
+ get(target, key, receiver) {
+ inspections += 1;
+ return Reflect.get(target, key, receiver);
+ },
+ has(target, key) {
+ inspections += 1;
+ return Reflect.has(target, key);
+ },
+ },
+ );
+ let root: unknown = leaf;
+ for (let level = 0; level < depth; level += 1) root = { child: wrap(root) };
+ return { root, inspections: () => inspections };
+}
+
+describe('FrontmatterArg validation cost', () => {
+ test.each([
+ { name: 'nested objects', wrap: (child: unknown) => child },
+ { name: 'objects inside lists', wrap: (child: unknown) => [child] },
+ ])('inspects the innermost record of $name as often at depth 40 as at depth 4', ({ wrap }) => {
+ const leafInspectionsAt = (depth: number) => {
+ const chain = countedLeafChain(depth, wrap);
+ expect(FrontmatterArg.safeParse(chain.root).success).toBe(true);
+ return chain.inspections();
+ };
+ const shallow = leafInspectionsAt(4);
+ expect(shallow).toBeGreaterThan(0);
+ expect(leafInspectionsAt(40)).toBe(shallow);
+ });
+});
+
+describe('frontmatter key refusal in the MCP write argument error', () => {
+ let root: string;
+ let mcp: McpServer;
+ let client: Client;
+
+ beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'ok-frontmatter-key-refusal-mcp-'));
+ mcp = new McpServer({ name: 'frontmatter-key-refusal', version: '1' });
+ installPrettyZodErrors(mcp);
+ registerWrite(mcp, {
+ config: ConfigSchema.parse({ content: { dir: '.' } }),
+ resolveCwd: async () => root,
+ serverUrl: 'http://127.0.0.1:9',
+ });
+ client = new Client({ name: 'frontmatter-key-refusal', version: '1' });
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ await Promise.all([mcp.connect(serverTransport), client.connect(clientTransport)]);
+ });
+
+ afterAll(async () => {
+ await client?.close();
+ await mcp?.close();
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ test.each([
+ ['top-level', '{"__proto__":0,"keep":1}', 'document.frontmatter.__proto__'],
+ ['nested object', '{"key":{"__proto__":0,"keep":1}}', 'document.frontmatter.key.__proto__'],
+ ['literal list', '{"key":[{"__proto__":0}]}', 'document.frontmatter.key[0].__proto__'],
+ [
+ 'nested lists',
+ '{"key":[[{"__proto__":0,"keep":1}]]}',
+ 'document.frontmatter.key[0][0].__proto__',
+ ],
+ ])('names the %s field and the unsupported key', async (_name, raw, field) => {
+ const result = await client.callTool({
+ name: 'write',
+ arguments: { document: { path: 'note', content: 'Body.', frontmatter: JSON.parse(raw) } },
+ });
+ expect(result.isError).toBe(true);
+ expect(result.content).toEqual([{ type: 'text', text: expect.any(String) }]);
+ const [{ text }] = result.content as [{ type: 'text'; text: string }];
+ expect.soft(text).toContain('Unsupported frontmatter key');
+ expect.soft(text).toContain(field);
+ expect.soft(text).not.toContain('invalid frontmatter value');
+ expect.soft(text).not.toContain('Invalid input');
+ });
+});
+
describe('DocExtensionArg — explicit on-create file format', () => {
test('accepts every supported extension', () => {
for (const ext of SUPPORTED_DOC_EXTENSIONS) {
diff --git a/packages/server/src/mcp/tools/verb-schemas.ts b/packages/server/src/mcp/tools/verb-schemas.ts
index 9398af158..a48d7f092 100644
--- a/packages/server/src/mcp/tools/verb-schemas.ts
+++ b/packages/server/src/mcp/tools/verb-schemas.ts
@@ -1,6 +1,7 @@
import {
type FrontmatterValue,
FrontmatterValueSchema,
+ frontmatterRecord,
MANAGED_ARTIFACT_SCOPES,
SKILL_NAME_REGEX,
skillFilePathSegments,
@@ -21,8 +22,7 @@ const FrontmatterAdvertisedValue = z.union([
z.null(),
]) as unknown as z.ZodType<FrontmatterValue | null>;
-export const FrontmatterArg = z
- .record(z.string(), FrontmatterAdvertisedValue)
+export const FrontmatterArg = frontmatterRecord(FrontmatterAdvertisedValue)
.superRefine((patch, ctx) => {
for (const [key, value] of Object.entries(patch)) {
if (!FrontmatterPatchValue.safeParse(value).success) {
diff --git a/packages/server/src/mcp/tools/write.ts b/packages/server/src/mcp/tools/write.ts
index 05ced0631..5ae611ce2 100644
--- a/packages/server/src/mcp/tools/write.ts
+++ b/packages/server/src/mcp/tools/write.ts
@@ -208,6 +208,20 @@ export function composeWithFrontmatter(
error: `EMBEDDED_FRONTMATTER_MALFORMED — \`content\` opens with a \`---\` block whose YAML failed to parse (${parsed.parseError}), so it can't be merged with the \`frontmatter\` param. Fix the embedded YAML, or supply the frontmatter only via the \`frontmatter\` param (not also inline in \`content\`).`,
};
}
+ let unsupportedKey = false;
+ parsed.doc.toJS({
+ reviver(key: unknown, value: unknown) {
+ if (key === '__proto__') unsupportedKey = true;
+ return value;
+ },
+ });
+ if (unsupportedKey) {
+ return {
+ ok: false,
+ error:
+ 'EMBEDDED_FRONTMATTER_UNSUPPORTED_KEY — `content` opens with a `---` block containing a field named `__proto__` (written literally, escaped, or reached through a YAML alias), which frontmatter cannot store, so the block cannot be merged with the `frontmatter` param. Nothing was written. Rename or remove that field in the embedded YAML.',
+ };
+ }
base = parsed.map;
}