T-163: M2.1m — Filesystem library adapter for the MCP copilot read_knowledge tool: KnowledgePort.listLibraryCards over library.yml + cards/<section>/*.md in libs/research/src/mcp/adapters/library-cards.ts (injected read-only fs port, strict front-matter parser, no new deps)

This commit is contained in:
Studio 2026-12-02 10:28:22 -05:00 • committed by Boki
parent 8ee307678f
commit a255191b66
3 changed files with 604 additions and 177 deletions

View file

@ -266,8 +266,8 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported
### Filesystem Library Cards Adapter
- **`createLibraryCardReader({ root, fs })`** (exported from `@stock-bot/research/mcp` alongside `createNodeLibraryCardFs`, `LibraryCardFs`, `LibraryCardDirEntry`, `LibraryCardReaderOptions`, `LibraryCardReader`, `LibraryCardError`, and `LibraryCardErrorCode`) implements `Pick<KnowledgePort, 'listLibraryCards'>` over a configured read-only library root (`<root>/library.yml` and `<root>/cards/<sectionId>/<slug>.md`) with zero new dependencies.
- **Read-only boundary, fresh reads & symlink safety:** Resolves `root` once at construction, reads `library.yml` and eligible cards fresh on every call (no cache), discovers `cards/` and declared section directories via parent listings so symbolic links are never followed, and opens text files read-only with `O_NOFOLLOW` + regular-file verification in `createNodeLibraryCardFs()`.
- **`createLibraryCardReader({ root, fs })`** (exported from `@stock-bot/research/mcp` alongside `createNodeLibraryCardFs`, `LibraryCardFs`, `LibraryCardDirHandle`, `LibraryCardDirEntry`, `LibraryCardReaderOptions`, `LibraryCardReader`, `LibraryCardError`, and `LibraryCardErrorCode`) implements `Pick<KnowledgePort, 'listLibraryCards'>` over a configured read-only library root (`<root>/library.yml` and `<root>/cards/<sectionId>/<slug>.md`) with zero new dependencies.
- **Read-only boundary, fresh reads & symlink safety:** Resolves `root` once at construction, reads `library.yml` and eligible cards fresh on every call (no cache), anchors listings and file reads to opened directory handles (`openDir` / `/proc/self/fd/<fd>` in `createNodeLibraryCardFs()`), enforces `O_NOFOLLOW` on every component below the configured root with `fstat` regular-file/directory verification, and fails closed if the runtime cannot enforce that boundary.
- **Exact-ID narrowing & unverified-card assumption:** Returns all eligible cards in manifest section order and code-unit slug order without pre-slicing or truncating text, narrowing only on exact case-sensitive `q.id` (malformed or unknown IDs return an empty frozen array without opening card files) so `createReadKnowledgeTool` owns `query`/`tags` filtering, ranking, truncation, and `limit`. All eligible cards are returned regardless of `verified` status, and callers must bind `root` to a research-visible corpus free of holdout or Vault-only observations.
### Copilot Server

View file

@ -8,12 +8,13 @@
*/
import { constants as fsConstants } from 'node:fs';
import { open, readdir } from 'node:fs/promises';
import { type FileHandle, open, readdir, stat } from 'node:fs/promises';
import path from 'node:path';
import type { KnowledgePort, LibraryCardQuery, LibraryCardRecord } from '../tools/read-knowledge';
const SAFE_IDENT_RE = /^[a-z0-9][a-z0-9-]*$/;
const LIBRARY_ID_RE = /^[a-z0-9][a-z0-9_-]*$/;
const SECTION_KEY_SYNTAX_RE = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/;
const BLOCK_SCALAR_RE = /^[|>][+-]?$/;
/** Error codes thrown by {@link LibraryCardError}. */
@ -42,10 +43,19 @@ export interface LibraryCardDirEntry {
readonly isDirectory: boolean;
}
/** Anchored read-only directory handle for symlink-safe traversal below a configured root. */
export interface LibraryCardDirHandle {
listDir(): Promise<readonly LibraryCardDirEntry[]>;
openSubdir(name: string): Promise<LibraryCardDirHandle>;
readTextFile(name: string): Promise<string>;
close(): Promise<void>;
}
/** Minimal read-only filesystem port injected into {@link createLibraryCardReader}. */
export interface LibraryCardFs {
readTextFile(filePath: string): Promise<string>;
listDir(dirPath: string): Promise<readonly LibraryCardDirEntry[]>;
openDir?(dirPath: string): Promise<LibraryCardDirHandle>;
}
/** Factory options for {@link createLibraryCardReader}. */
@ -113,7 +123,8 @@ function validateFactoryOptions(options: LibraryCardReaderOptions): {
typeof fs !== 'object' ||
fs === null ||
typeof fs.readTextFile !== 'function' ||
typeof fs.listDir !== 'function'
typeof fs.listDir !== 'function' ||
(fs.openDir !== undefined && typeof fs.openDir !== 'function')
) {
throw new LibraryCardError(
'INVALID_FS',
@ -128,7 +139,7 @@ function validateFactoryOptions(options: LibraryCardReaderOptions): {
}
function parseLibraryScalar(rawValue: string): string {
if (rawValue.length === 0) {
if (rawValue.length === 0 || rawValue.startsWith('#')) {
throw invalidLibrary('"id" must not be empty.');
}
if (rawValue.startsWith("'")) {
@ -229,13 +240,25 @@ function parseLibraryManifest(content: string): ParsedLibraryManifest {
}
const body = line.slice(indent);
if (body === '-' || body.startsWith('- ') || body.startsWith('-\t')) {
throw invalidLibrary('sequence entries are not supported inside "sections" map.');
}
const colonIdx = body.indexOf(':');
if (colonIdx <= 0) {
throw invalidLibrary('malformed entry inside "sections" map.');
}
const sectionKey = body.slice(0, colonIdx).trim();
const sectionTitle = body.slice(colonIdx + 1).trim();
if (sectionKey.length === 0 || sectionTitle.length === 0) {
const rawKey = body.slice(0, colonIdx);
const sectionKey = rawKey.trim();
const afterColon = body.slice(colonIdx + 1);
if (
rawKey !== sectionKey ||
!SECTION_KEY_SYNTAX_RE.test(sectionKey) ||
(afterColon.length > 0 && afterColon[0] !== ' ' && afterColon[0] !== '\t')
) {
throw invalidLibrary('malformed entry inside "sections" map.');
}
const sectionTitle = afterColon.trim();
if (sectionTitle.length === 0 || sectionTitle.startsWith('#')) {
throw invalidLibrary('empty key or title inside "sections" map.');
}
if (seenSectionKeys.has(sectionKey)) {
@ -262,7 +285,7 @@ function parseLibraryManifest(content: string): ParsedLibraryManifest {
}
function parseFrontMatterValue(rawValue: string, relPath: string): FrontMatterValue {
if (rawValue.length === 0) {
if (rawValue.length === 0 || rawValue.startsWith('#')) {
throw invalidCard(relPath, 'empty or multiline front-matter value.');
}
if (BLOCK_SCALAR_RE.test(rawValue)) {
@ -434,15 +457,104 @@ function parseExactCardId(
return { sectionId, slug };
}
async function safeReadTextFile(
function assertSafeChildName(name: string): void {
if (
name.length === 0 ||
name === '.' ||
name === '..' ||
name.includes('/') ||
name.includes('\\') ||
name.includes('\0')
) {
throw new Error('Invalid directory child entry name.');
}
}
function isValidDirHandle(value: unknown): value is LibraryCardDirHandle {
return (
typeof value === 'object' &&
value !== null &&
typeof (value as { readonly listDir?: unknown }).listDir === 'function' &&
typeof (value as { readonly openSubdir?: unknown }).openSubdir === 'function' &&
typeof (value as { readonly readTextFile?: unknown }).readTextFile === 'function' &&
typeof (value as { readonly close?: unknown }).close === 'function'
);
}
function createPathBackedDirHandle(fs: LibraryCardFs, dirPath: string): LibraryCardDirHandle {
return {
listDir(): Promise<readonly LibraryCardDirEntry[]> {
return fs.listDir(dirPath);
},
async openSubdir(name: string): Promise<LibraryCardDirHandle> {
assertSafeChildName(name);
return createPathBackedDirHandle(fs, path.join(dirPath, name));
},
readTextFile(name: string): Promise<string> {
assertSafeChildName(name);
return fs.readTextFile(path.join(dirPath, name));
},
async close(): Promise<void> {
// No underlying OS handle to close for path-backed adapters.
},
};
}
async function safeOpenRootDir(
fs: LibraryCardFs,
filePath: string,
resolvedRoot: string
): Promise<LibraryCardDirHandle> {
if (fs.openDir === undefined) {
return createPathBackedDirHandle(fs, resolvedRoot);
}
let handle: unknown;
try {
handle = await fs.openDir(resolvedRoot);
} catch {
throw new LibraryCardError(
'INVALID_LIBRARY',
'Invalid library.yml: failed to open library root directory.'
);
}
if (!isValidDirHandle(handle)) {
throw new LibraryCardError(
'INVALID_LIBRARY',
'Invalid library.yml: failed to open library root directory.'
);
}
return handle;
}
async function safeOpenSubdir(
parent: LibraryCardDirHandle,
name: string,
errorMessage: string,
allowMissing: boolean
): Promise<LibraryCardDirHandle | null> {
let handle: unknown;
try {
handle = await parent.openSubdir(name);
} catch (err) {
if (allowMissing && isEnoentError(err)) {
return null;
}
throw new LibraryCardError('INVALID_LIBRARY', errorMessage);
}
if (!isValidDirHandle(handle)) {
throw new LibraryCardError('INVALID_LIBRARY', errorMessage);
}
return handle;
}
async function safeReadTextFileFromDir(
dir: LibraryCardDirHandle,
name: string,
errorCode: 'INVALID_LIBRARY' | 'INVALID_CARD',
errorMessage: string
): Promise<string> {
let content: unknown;
try {
content = await fs.readTextFile(filePath);
content = await dir.readTextFile(name);
} catch {
throw new LibraryCardError(errorCode, errorMessage);
}
@ -452,15 +564,14 @@ async function safeReadTextFile(
return content;
}
async function safeListDir(
fs: LibraryCardFs,
dirPath: string,
async function safeListDirHandle(
dir: LibraryCardDirHandle,
errorMessage: string,
allowMissing: boolean
): Promise<readonly LibraryCardDirEntry[]> {
let rawEntries: unknown;
try {
rawEntries = await fs.listDir(dirPath);
rawEntries = await dir.listDir();
} catch (err) {
if (allowMissing && isEnoentError(err)) {
return [];
@ -490,33 +601,43 @@ async function safeListDir(
return entries;
}
/**
* Creates a read-only {@link LibraryCardFs} backed by `node:fs/promises`.
*
* Opens text files read-only with `O_NOFOLLOW` (where supported) and confirms
* they are regular files before reading, and reports directory entry types
* without following symbolic links.
*/
export function createNodeLibraryCardFs(): LibraryCardFs {
const noFollowFlag = typeof fsConstants.O_NOFOLLOW === 'number' ? fsConstants.O_NOFOLLOW : 0;
const openFlags = fsConstants.O_RDONLY | noFollowFlag;
interface AnchoredOpenFlags {
readonly dirOpenFlags: number;
readonly subdirOpenFlags: number;
readonly fileOpenFlags: number;
}
function getAnchoredOpenFlags(): AnchoredOpenFlags {
if (
process.platform !== 'linux' ||
typeof fsConstants.O_NOFOLLOW !== 'number' ||
typeof fsConstants.O_DIRECTORY !== 'number'
) {
throw new Error('Anchored no-follow directory operations are not supported on this platform.');
}
return {
dirOpenFlags: fsConstants.O_RDONLY | fsConstants.O_DIRECTORY,
subdirOpenFlags: fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW,
fileOpenFlags: fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW,
};
}
function createAnchoredNodeDirHandle(
handle: FileHandle,
flags: AnchoredOpenFlags
): LibraryCardDirHandle {
let closed = false;
const getFdBase = (): string => {
if (closed) {
throw new Error('Directory handle is closed.');
}
return `/proc/self/fd/${handle.fd}`;
};
return {
async readTextFile(filePath: string): Promise<string> {
const handle = await open(filePath, openFlags);
try {
const stats = await handle.stat();
if (!stats.isFile()) {
throw new Error('Target path is not a regular file.');
}
return await handle.readFile({ encoding: 'utf8' });
} finally {
await handle.close();
}
},
async listDir(dirPath: string): Promise<readonly LibraryCardDirEntry[]> {
const dirents = await readdir(dirPath, { withFileTypes: true });
async listDir(): Promise<readonly LibraryCardDirEntry[]> {
const dirents = await readdir(getFdBase(), { withFileTypes: true });
const entries: LibraryCardDirEntry[] = [];
for (let i = 0; i < dirents.length; i += 1) {
const dirent = dirents[i];
@ -530,6 +651,103 @@ export function createNodeLibraryCardFs(): LibraryCardFs {
}
return entries;
},
async openSubdir(name: string): Promise<LibraryCardDirHandle> {
assertSafeChildName(name);
const childHandle = await open(`${getFdBase()}/${name}`, flags.subdirOpenFlags);
try {
const stats = await childHandle.stat();
if (!stats.isDirectory()) {
throw new Error('Target path is not a directory.');
}
} catch (err) {
await childHandle.close();
throw err;
}
return createAnchoredNodeDirHandle(childHandle, flags);
},
async readTextFile(name: string): Promise<string> {
assertSafeChildName(name);
const fileHandle = await open(`${getFdBase()}/${name}`, flags.fileOpenFlags);
try {
const stats = await fileHandle.stat();
if (!stats.isFile()) {
throw new Error('Target path is not a regular file.');
}
return await fileHandle.readFile({ encoding: 'utf8' });
} finally {
await fileHandle.close();
}
},
async close(): Promise<void> {
if (closed) {
return;
}
closed = true;
await handle.close();
},
};
}
/**
* Creates a read-only {@link LibraryCardFs} backed by `node:fs/promises`.
*
* Anchors directory listings and file reads to opened directory file descriptors
* via `/proc/self/fd/<fd>`, enforces `O_NOFOLLOW` on every component below the
* configured root, verifies regular-file/directory types via `fstat`, and fails
* closed on platforms that cannot enforce this boundary.
*/
export function createNodeLibraryCardFs(): LibraryCardFs {
return {
async readTextFile(filePath: string): Promise<string> {
const flags = getAnchoredOpenFlags();
const handle = await open(filePath, flags.fileOpenFlags);
try {
const stats = await handle.stat();
if (!stats.isFile()) {
throw new Error('Target path is not a regular file.');
}
return await handle.readFile({ encoding: 'utf8' });
} finally {
await handle.close();
}
},
async listDir(dirPath: string): Promise<readonly LibraryCardDirEntry[]> {
const flags = getAnchoredOpenFlags();
const handle = await open(dirPath, flags.subdirOpenFlags);
try {
const stats = await handle.stat();
if (!stats.isDirectory()) {
throw new Error('Target path is not a directory.');
}
const anchored = createAnchoredNodeDirHandle(handle, flags);
return await anchored.listDir();
} finally {
await handle.close();
}
},
async openDir(dirPath: string): Promise<LibraryCardDirHandle> {
const flags = getAnchoredOpenFlags();
const handle = await open(dirPath, flags.dirOpenFlags);
try {
const stats = await handle.stat();
if (!stats.isDirectory()) {
throw new Error('Target path is not a directory.');
}
const procStats = await stat(`/proc/self/fd/${handle.fd}`);
if (!procStats.isDirectory()) {
throw new Error('Anchored directory descriptor is not accessible.');
}
} catch (err) {
await handle.close();
throw err;
}
return createAnchoredNodeDirHandle(handle, flags);
},
};
}
@ -545,29 +763,111 @@ export function createNodeLibraryCardFs(): LibraryCardFs {
*/
export function createLibraryCardReader(options: LibraryCardReaderOptions): LibraryCardReader {
const { resolvedRoot, fs } = validateFactoryOptions(options);
const manifestPath = path.join(resolvedRoot, 'library.yml');
const cardsDirPath = path.join(resolvedRoot, 'cards');
return {
async listLibraryCards(q: LibraryCardQuery): Promise<readonly LibraryCardRecord[]> {
const manifestText = await safeReadTextFile(
fs,
manifestPath,
'INVALID_LIBRARY',
'Invalid library.yml: failed to read manifest.'
);
const manifest = parseLibraryManifest(manifestText);
const declaredSections = new Set(manifest.sections);
const rootDir = await safeOpenRootDir(fs, resolvedRoot);
try {
const manifestText = await safeReadTextFileFromDir(
rootDir,
'library.yml',
'INVALID_LIBRARY',
'Invalid library.yml: failed to read manifest.'
);
const manifest = parseLibraryManifest(manifestText);
const declaredSections = new Set(manifest.sections);
if (q.id !== undefined) {
const target = parseExactCardId(q.id, manifest.id, declaredSections);
if (target === null) {
return Object.freeze([]);
if (q.id !== undefined) {
const target = parseExactCardId(q.id, manifest.id, declaredSections);
if (target === null) {
return Object.freeze([]);
}
const rootEntries = await safeListDirHandle(
rootDir,
'Invalid library.yml: failed to list library root directory.',
false
);
const hasCardsDir = rootEntries.some(
entry => entry.name === 'cards' && entry.isDirectory && !entry.isFile
);
if (!hasCardsDir) {
return Object.freeze([]);
}
const cardsDir = await safeOpenSubdir(
rootDir,
'cards',
'Invalid library.yml: failed to open library cards directory.',
true
);
if (cardsDir === null) {
return Object.freeze([]);
}
try {
const cardDirEntries = await safeListDirHandle(
cardsDir,
'Invalid library.yml: failed to list library cards directory.',
true
);
const hasSectionDir = cardDirEntries.some(
entry => entry.name === target.sectionId && entry.isDirectory && !entry.isFile
);
if (!hasSectionDir) {
return Object.freeze([]);
}
const sectionDir = await safeOpenSubdir(
cardsDir,
target.sectionId,
`Invalid library.yml: failed to open section directory "cards/${target.sectionId}".`,
true
);
if (sectionDir === null) {
return Object.freeze([]);
}
try {
const sectionEntries = await safeListDirHandle(
sectionDir,
`Invalid library.yml: failed to list section directory "cards/${target.sectionId}".`,
true
);
const targetFileName = `${target.slug}.md`;
let matchCount = 0;
for (let i = 0; i < sectionEntries.length; i += 1) {
const entry = sectionEntries[i] as LibraryCardDirEntry;
if (entry.isFile && !entry.isDirectory && entry.name === targetFileName) {
matchCount += 1;
}
}
if (matchCount === 0) {
return Object.freeze([]);
}
const relPath = `cards/${target.sectionId}/${target.slug}.md`;
if (matchCount > 1) {
throw invalidCard(relPath, 'duplicate card id.');
}
const cardText = await safeReadTextFileFromDir(
sectionDir,
targetFileName,
'INVALID_CARD',
`Invalid card "${relPath}": failed to read card file.`
);
const record = parseCardDocument(cardText, manifest.id, target.sectionId, target.slug);
return Object.freeze([record]);
} finally {
await sectionDir.close();
}
} finally {
await cardsDir.close();
}
}
const rootEntries = await safeListDir(
fs,
resolvedRoot,
const rootEntries = await safeListDirHandle(
rootDir,
'Invalid library.yml: failed to list library root directory.',
false
);
@ -578,131 +878,100 @@ export function createLibraryCardReader(options: LibraryCardReaderOptions): Libr
return Object.freeze([]);
}
const cardDirEntries = await safeListDir(
fs,
cardsDirPath,
'Invalid library.yml: failed to list library cards directory.',
const cardsDir = await safeOpenSubdir(
rootDir,
'cards',
'Invalid library.yml: failed to open library cards directory.',
true
);
const hasSectionDir = cardDirEntries.some(
entry => entry.name === target.sectionId && entry.isDirectory && !entry.isFile
);
if (!hasSectionDir) {
if (cardsDir === null) {
return Object.freeze([]);
}
const sectionDirPath = path.join(cardsDirPath, target.sectionId);
const sectionEntries = await safeListDir(
fs,
sectionDirPath,
`Invalid library.yml: failed to list section directory "cards/${target.sectionId}".`,
true
);
const targetFileName = `${target.slug}.md`;
let matchCount = 0;
for (let i = 0; i < sectionEntries.length; i += 1) {
const entry = sectionEntries[i] as LibraryCardDirEntry;
if (entry.isFile && !entry.isDirectory && entry.name === targetFileName) {
matchCount += 1;
}
}
if (matchCount === 0) {
return Object.freeze([]);
}
const relPath = `cards/${target.sectionId}/${target.slug}.md`;
if (matchCount > 1) {
throw invalidCard(relPath, 'duplicate card id.');
}
const cardText = await safeReadTextFile(
fs,
path.join(sectionDirPath, targetFileName),
'INVALID_CARD',
`Invalid card "${relPath}": failed to read card file.`
);
const record = parseCardDocument(cardText, manifest.id, target.sectionId, target.slug);
return Object.freeze([record]);
}
const rootEntries = await safeListDir(
fs,
resolvedRoot,
'Invalid library.yml: failed to list library root directory.',
false
);
const hasCardsDir = rootEntries.some(
entry => entry.name === 'cards' && entry.isDirectory && !entry.isFile
);
if (!hasCardsDir) {
return Object.freeze([]);
}
const cardDirEntries = await safeListDir(
fs,
cardsDirPath,
'Invalid library.yml: failed to list library cards directory.',
true
);
const presentSectionDirs = new Set<string>();
for (let i = 0; i < cardDirEntries.length; i += 1) {
const entry = cardDirEntries[i] as LibraryCardDirEntry;
if (entry.isDirectory && !entry.isFile && SAFE_IDENT_RE.test(entry.name)) {
presentSectionDirs.add(entry.name);
}
}
const cards: LibraryCardRecord[] = [];
const seenIds = new Set<string>();
for (let s = 0; s < manifest.sections.length; s += 1) {
const sectionId = manifest.sections[s] as string;
if (!presentSectionDirs.has(sectionId)) {
continue;
}
const sectionDirPath = path.join(cardsDirPath, sectionId);
const sectionEntries = await safeListDir(
fs,
sectionDirPath,
`Invalid library.yml: failed to list section directory "cards/${sectionId}".`,
true
);
const slugs: string[] = [];
for (let i = 0; i < sectionEntries.length; i += 1) {
const entry = sectionEntries[i] as LibraryCardDirEntry;
if (!entry.isFile || entry.isDirectory || !entry.name.endsWith('.md')) {
continue;
}
const slug = entry.name.slice(0, -3);
if (!SAFE_IDENT_RE.test(slug)) {
continue;
}
slugs.push(slug);
}
slugs.sort(compareCodeUnits);
for (let i = 0; i < slugs.length; i += 1) {
const slug = slugs[i] as string;
const relPath = `cards/${sectionId}/${slug}.md`;
const canonicalId = `${manifest.id}:${sectionId}/${slug}`;
if (seenIds.has(canonicalId)) {
throw invalidCard(relPath, 'duplicate card id.');
}
seenIds.add(canonicalId);
const cardText = await safeReadTextFile(
fs,
path.join(sectionDirPath, `${slug}.md`),
'INVALID_CARD',
`Invalid card "${relPath}": failed to read card file.`
try {
const cardDirEntries = await safeListDirHandle(
cardsDir,
'Invalid library.yml: failed to list library cards directory.',
true
);
cards.push(parseCardDocument(cardText, manifest.id, sectionId, slug));
}
}
const presentSectionDirs = new Set<string>();
for (let i = 0; i < cardDirEntries.length; i += 1) {
const entry = cardDirEntries[i] as LibraryCardDirEntry;
if (entry.isDirectory && !entry.isFile && SAFE_IDENT_RE.test(entry.name)) {
presentSectionDirs.add(entry.name);
}
}
return Object.freeze(cards);
const cards: LibraryCardRecord[] = [];
const seenIds = new Set<string>();
for (let s = 0; s < manifest.sections.length; s += 1) {
const sectionId = manifest.sections[s] as string;
if (!presentSectionDirs.has(sectionId)) {
continue;
}
const sectionDir = await safeOpenSubdir(
cardsDir,
sectionId,
`Invalid library.yml: failed to open section directory "cards/${sectionId}".`,
true
);
if (sectionDir === null) {
continue;
}
try {
const sectionEntries = await safeListDirHandle(
sectionDir,
`Invalid library.yml: failed to list section directory "cards/${sectionId}".`,
true
);
const slugs: string[] = [];
for (let i = 0; i < sectionEntries.length; i += 1) {
const entry = sectionEntries[i] as LibraryCardDirEntry;
if (!entry.isFile || entry.isDirectory || !entry.name.endsWith('.md')) {
continue;
}
const slug = entry.name.slice(0, -3);
if (!SAFE_IDENT_RE.test(slug)) {
continue;
}
slugs.push(slug);
}
slugs.sort(compareCodeUnits);
for (let i = 0; i < slugs.length; i += 1) {
const slug = slugs[i] as string;
const relPath = `cards/${sectionId}/${slug}.md`;
const canonicalId = `${manifest.id}:${sectionId}/${slug}`;
if (seenIds.has(canonicalId)) {
throw invalidCard(relPath, 'duplicate card id.');
}
seenIds.add(canonicalId);
const cardText = await safeReadTextFileFromDir(
sectionDir,
`${slug}.md`,
'INVALID_CARD',
`Invalid card "${relPath}": failed to read card file.`
);
cards.push(parseCardDocument(cardText, manifest.id, sectionId, slug));
}
} finally {
await sectionDir.close();
}
}
return Object.freeze(cards);
} finally {
await cardsDir.close();
}
} finally {
await rootDir.close();
}
},
};
}

View file

@ -1,10 +1,11 @@
import { afterEach, describe, expect, test } from 'bun:test';
import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises';
import { mkdir, mkdtemp, rename, rm, symlink, unlink, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import {
type KnowledgePort,
type LibraryCardDirEntry,
type LibraryCardDirHandle,
LibraryCardError,
type LibraryCardFs,
READ_KNOWLEDGE_MAX_TEXT_LENGTH,
@ -371,6 +372,11 @@ sections:
'id: quant\nsections:\n alphas: A\nsections:\n beta: B\n', // duplicate sections
'id: quant\nsections:\n alphas: A\n alphas: B\n', // duplicate section key
'id: quant\nsections: []\n', // non-map sections
'id: quant\nsections:\n - alphas: Alphas\n', // YAML sequence under sections
'id: quant\nsections:\n - alphas\n', // YAML bare sequence under sections
'id: quant\nsections:\n alphas: # comment-only title\n', // comment-only title
'id: quant\nsections:\n alphas:NoSpace\n', // missing space after colon
'id: quant\nsections:\n bad key: Title\n', // whitespace in section key
];
for (const manifest of badManifests) {
@ -461,6 +467,14 @@ sections:
label: 'duplicate key',
content: `---\ntitle: "First"\ntitle: "Second ${SECRET_MARKER}"\nsummary: "S"\n---\n${SECRET_MARKER}`,
},
{
label: 'comment-only summary',
content: `---\ntitle: "T"\nsummary: # Fill in after review ${SECRET_MARKER}\n---\n${SECRET_MARKER}`,
},
{
label: 'comment-only title',
content: `---\ntitle: # Draft title ${SECRET_MARKER}\nsummary: "S"\n---\n${SECRET_MARKER}`,
},
];
for (const tc of badCards) {
@ -702,4 +716,148 @@ LEAKED_SIBLING_CONTENT
'INVALID_LIBRARY'
);
});
test('anchors directory listings and reads to open handles to block directory-symlink TOCTOU races', async () => {
const tempBase = await mkdtemp(path.join(os.tmpdir(), 'stock-bot-library-toctou-'));
tempDirs.push(tempBase);
const libRoot = path.join(tempBase, 'library');
const alphasDir = path.join(libRoot, 'cards', 'alphas');
const outsideDir = path.join(tempBase, 'outside-corpus');
const LEAK_MARKER = 'OUTSIDE_CORPUS_TOCTOU_LEAK_7741';
await mkdir(alphasDir, { recursive: true });
await mkdir(outsideDir, { recursive: true });
await writeFile(
path.join(libRoot, 'library.yml'),
`id: quant\nsections:\n alphas: Signal & alpha research\n`,
'utf8'
);
await writeFile(path.join(alphasDir, 'piotroski-f-score.md'), PIOTROSKI_CARD, 'utf8');
await writeFile(
path.join(outsideDir, 'piotroski-f-score.md'),
`---\ntitle: "Leaked Card"\nsummary: "Leaked summary"\n---\n\n${LEAK_MARKER}\n`,
'utf8'
);
const baseNodeFs = createNodeLibraryCardFs();
expect(typeof baseNodeFs.openDir).toBe('function');
// Race A: cards/alphas is replaced with a symlink after cards/ is listed, before opening alphas.
let raceATriggered = false;
const raceAFs: LibraryCardFs = {
readTextFile: p => baseNodeFs.readTextFile(p),
listDir: p => baseNodeFs.listDir(p),
async openDir(dirPath: string): Promise<LibraryCardDirHandle> {
const rootHandle = await (baseNodeFs.openDir as NonNullable<LibraryCardFs['openDir']>)(
dirPath
);
return {
listDir: () => rootHandle.listDir(),
readTextFile: name => rootHandle.readTextFile(name),
close: () => rootHandle.close(),
async openSubdir(name: string): Promise<LibraryCardDirHandle> {
const sub = await rootHandle.openSubdir(name);
if (name !== 'cards') {
return sub;
}
return {
async listDir(): Promise<readonly LibraryCardDirEntry[]> {
const entries = await sub.listDir();
if (!raceATriggered) {
raceATriggered = true;
await rename(alphasDir, path.join(libRoot, 'cards', 'alphas-moved-a'));
await symlink(outsideDir, alphasDir);
}
return entries;
},
openSubdir: child => sub.openSubdir(child),
readTextFile: child => sub.readTextFile(child),
close: () => sub.close(),
};
},
};
},
};
const raceAReader = createLibraryCardReader({ root: libRoot, fs: raceAFs });
const raceAErr = await expectLibraryCardError(
() => raceAReader.listLibraryCards({}),
'INVALID_LIBRARY'
);
expect(raceATriggered).toBe(true);
expect(raceAErr.message).not.toContain(LEAK_MARKER);
// Restore alphas directory for Race B.
await unlink(alphasDir);
await rename(path.join(libRoot, 'cards', 'alphas-moved-a'), alphasDir);
// Race B: cards/alphas is replaced with a symlink after alphas is opened and listed, before reading the card.
let raceBTriggered = false;
const raceBFs: LibraryCardFs = {
readTextFile: p => baseNodeFs.readTextFile(p),
listDir: p => baseNodeFs.listDir(p),
async openDir(dirPath: string): Promise<LibraryCardDirHandle> {
const rootHandle = await (baseNodeFs.openDir as NonNullable<LibraryCardFs['openDir']>)(
dirPath
);
return {
listDir: () => rootHandle.listDir(),
readTextFile: name => rootHandle.readTextFile(name),
close: () => rootHandle.close(),
async openSubdir(name: string): Promise<LibraryCardDirHandle> {
const cardsHandle = await rootHandle.openSubdir(name);
if (name !== 'cards') {
return cardsHandle;
}
return {
listDir: () => cardsHandle.listDir(),
readTextFile: child => cardsHandle.readTextFile(child),
close: () => cardsHandle.close(),
async openSubdir(sectionName: string): Promise<LibraryCardDirHandle> {
const sectionHandle = await cardsHandle.openSubdir(sectionName);
return {
async listDir(): Promise<readonly LibraryCardDirEntry[]> {
const entries = await sectionHandle.listDir();
if (!raceBTriggered && sectionName === 'alphas') {
raceBTriggered = true;
await rename(alphasDir, path.join(libRoot, 'cards', 'alphas-moved-b'));
await symlink(outsideDir, alphasDir);
}
return entries;
},
openSubdir: child => sectionHandle.openSubdir(child),
readTextFile: child => sectionHandle.readTextFile(child),
close: () => sectionHandle.close(),
};
},
};
},
};
},
};
const raceBReader = createLibraryCardReader({ root: libRoot, fs: raceBFs });
const anchoredCards = await raceBReader.listLibraryCards({});
expect(raceBTriggered).toBe(true);
expect(anchoredCards).toHaveLength(1);
expect(anchoredCards[0]?.id).toBe('quant:alphas/piotroski-f-score');
expect(anchoredCards[0]?.body).not.toContain(LEAK_MARKER);
expect(anchoredCards[0]?.body).toContain('Piotroski F-Score');
// Unsupported boundary enforcement on openDir fails closed with INVALID_LIBRARY.
const unsupportedFs: LibraryCardFs = {
readTextFile: p => baseNodeFs.readTextFile(p),
listDir: p => baseNodeFs.listDir(p),
async openDir(): Promise<LibraryCardDirHandle> {
throw new Error('Anchored no-follow directory operations are not supported.');
},
};
const unsupportedReader = createLibraryCardReader({ root: libRoot, fs: unsupportedFs });
await expectLibraryCardError(
() => unsupportedReader.listLibraryCards({}),
'INVALID_LIBRARY'
);
});
});