Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Turn four source-text checks into syntax-tree rules (#5222)
Nick Gomezd076b509ac25
diff --git a/packages/app/src/editor/editor-cache.test.ts b/packages/app/src/editor/editor-cache.test.tsindex b10a67471..5991eee5b 100644--- a/packages/app/src/editor/editor-cache.test.ts+++ b/packages/app/src/editor/editor-cache.test.ts@@ -1,8 +1,10 @@+import { readFileSync } from 'node:fs';import { Compartment } from '@codemirror/state';import type { EditorView } from '@codemirror/view';import type { HocuspocusProvider } from '@hocuspocus/provider';import type { Editor } from '@tiptap/core';import { yUndoPluginKey } from '@tiptap/y-tiptap';+import { Node, Project, type SourceFile, SyntaxKind } from 'ts-morph';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import * as Y from 'yjs';import {@@ -1346,15 +1348,249 @@ describe('CM6 cache — undoManager teardown', () => {});});+const cacheProject = new Project({+ useInMemoryFileSystem: true,+ skipAddingFilesFromTsConfig: true,+ skipFileDependencyResolution: true,+ skipLoadingLibFiles: true,+ compilerOptions: { noLib: true },+});++function unwrapEditorNode(node: Node | undefined): Node | undefined {+ while (+ Node.isParenthesizedExpression(node) ||+ Node.isAsExpression(node) ||+ Node.isTypeAssertion(node) ||+ Node.isExpressionWithTypeArguments(node) ||+ Node.isSatisfiesExpression(node) ||+ Node.isNonNullExpression(node)+ )+ node = node.getExpression();+ return node;+}++function isEditorReceiver(node: Node | undefined): boolean {+ node = unwrapEditorNode(node);+ return (+ (Node.isIdentifier(node) && node.getText().endsWith('editor')) ||+ (Node.isPropertyAccessExpression(node) && node.getName().endsWith('editor'))+ );+}++function lifecycleKey(node: Node | undefined, computed: boolean): boolean {+ node = unwrapEditorNode(node);+ if (Node.isComputedPropertyName(node)) return lifecycleKey(node.getExpression(), true);+ if (Node.isStringLiteral(node) || Node.isNoSubstitutionTemplateLiteral(node)) {+ return ['mount', 'unmount'].includes(node.getLiteralValue());+ }+ if (!computed && Node.isIdentifier(node)) return ['mount', 'unmount'].includes(node.getText());+ return !(+ Node.isLiteralExpression(node) ||+ node?.getKind() === SyntaxKind.TrueKeyword ||+ node?.getKind() === SyntaxKind.FalseKeyword ||+ node?.getKind() === SyntaxKind.NullKeyword+ );+}++function lifecycleReferences(file: SourceFile): string[] {+ const violations: string[] = [];+ for (const node of file.getDescendants()) {+ if (+ (Node.isPropertyAccessExpression(node) &&+ isEditorReceiver(node.getExpression()) &&+ ['mount', 'unmount'].includes(node.getName())) ||+ (Node.isElementAccessExpression(node) &&+ isEditorReceiver(node.getExpression()) &&+ lifecycleKey(node.getArgumentExpression(), true))+ ) {+ violations.push(`editor-lifecycle-reference: ${node.getText()}`);+ }+ if (Node.isVariableDeclaration(node) && isEditorReceiver(node.getInitializer())) {+ const pattern = node.getNameNode();+ if (Node.isObjectBindingPattern(pattern)) {+ for (const element of pattern.getElements()) {+ if (+ element.getDotDotDotToken() ||+ lifecycleKey(element.getPropertyNameNode() ?? element.getNameNode(), false)+ ) {+ violations.push(`editor-lifecycle-destructure: ${element.getText()}`);+ }+ }+ }+ }+ if (+ Node.isBinaryExpression(node) &&+ node.getOperatorToken().getKind() === SyntaxKind.EqualsToken &&+ isEditorReceiver(node.getRight())+ ) {+ const pattern = unwrapEditorNode(node.getLeft());+ if (Node.isObjectLiteralExpression(pattern)) {+ for (const property of pattern.getProperties()) {+ if (Node.isSpreadAssignment(property) || lifecycleKey(property.getNameNode(), false)) {+ violations.push(`editor-lifecycle-destructure: ${property.getText()}`);+ }+ }+ }+ }+ }+ return violations;+}++function editorLifecycleCalls(source: string): string[] {+ const file = cacheProject.createSourceFile('/editor-cache.ts', source, { overwrite: true });+ try {+ return lifecycleReferences(file);+ } finally {+ cacheProject.removeSourceFile(file);+ }+}++const cacheFunctions = [+ 'mountTiptapEditor',+ 'parkTiptapEditor',+ 'evictTiptapEditor',+ 'mountCmEditor',+ 'parkCmEditor',+ 'evictCmEditor',+] as const;++function editorCacheViolations(source: string): string[] {+ const file = cacheProject.createSourceFile('/editor-cache.ts', source, { overwrite: true });+ try {+ const violations = cacheProject+ .getProgram()+ .getSyntacticDiagnostics(file)+ .map((error) => `syntax: ${error.getCode()} at ${error.getStart()}`);+ if (file.getExportDeclarations().some((declaration) => declaration.getModuleSpecifier())) {+ violations.push('editor-cache re-export');+ }+ for (const name of cacheFunctions) {+ const functions = file+ .getFunctions()+ .filter(+ (declaration) =>+ declaration.getName() === name && declaration.isExported() && declaration.getBody(),+ );+ if (functions.length !== 1) violations.push(`editor-cache implementation: ${name}`);+ }+ return [...violations, ...lifecycleReferences(file)];+ } finally {+ cacheProject.removeSourceFile(file);+ }+}+describe('STOP rule: editor-cache never calls editor.mount() / editor.unmount()', () => {- test('source contains no reference to editor.mount( or editor.unmount(', async () => {- const sourceText = await Bun.file(`${import.meta.dir}/editor-cache.ts`).text();- const code = sourceText- .split('\n')- .filter((line) => !line.trimStart().startsWith('*') && !line.trimStart().startsWith('//'))- .join('\n');- expect(/editor\.mount\s*\(/.test(code)).toBe(false);- expect(/editor\.unmount\s*\(/.test(code)).toBe(false);+ test.each([+ 'editor.mount(target)',+ 'editor.mount (target)',+ 'editor.mount\n(target)',+ 'editor.unmount()',+ 'editor.unmount ()',+ 'editor.unmount\n()',+ 'entry.editor.mount(target)',+ 'editor?.mount(target)',+ 'editor.mount?.(target)',+ 'editor?.mount?.(target)',+ 'editor?.unmount()',+ 'editor.unmount?.()',+ 'editor?.unmount?.()',+ ])('detects lifecycle call %s', (source) => {+ expect(editorLifecycleCalls(source)).toHaveLength(1);+ });++ test('ignores adjacent methods, declarations, strings and comments', () => {+ expect(+ editorLifecycleCalls(`+ editor.destroy(); other.mount(target);+ interface Editor { mount(target): void; unmount(): void; }+ const example = 'editor.mount(target)';+ /* editor.mount(target); editor.unmount(); */+ `),+ ).toEqual([]);+ });++ test.each([+ ['new editor.mount(target)', 'new other.mount(target)'],+ ['new entry.editor.unmount()', 'new entry.other.unmount()'],+ ['new editor.mount', 'new other.mount'],+ ['const m = editor.mount; m(target)', 'const m = editor.destroy; m(target)'],+ ['editor.mount.call(editor, target)', 'editor.destroy.call(editor, target)'],+ ['editor.mount.apply(editor, [target])', 'editor.destroy.apply(editor, [target])'],+ ['editor.mount.bind(editor)', 'editor.destroy.bind(editor)'],+ ["editor['mount'](target)", "editor['destroy'](target)"],+ ['editor[`unmount`]()', 'editor[`destroy`]()'],+ ['editor[method](target)', 'editor[0]'],+ ["editor[('mount' as string)](target)", "editor[('destroy' as string)](target)"],+ ["editor['mount' satisfies string]", "editor['destroy' satisfies string]"],+ ["editor['mount'!]", "editor['destroy'!]"],+ ['(editor as Editor).mount(target)', '(editor as Editor).destroy(target)'],+ ['(<Editor>editor).mount(target)', '(<Editor>editor).destroy(target)'],+ ['(editor<Editor>).mount(target)', '(editor<Editor>).destroy(target)'],+ ['(editor satisfies Editor).mount(target)', '(editor satisfies Editor).destroy(target)'],+ ['editor!.unmount()', 'editor!.destroy()'],+ ['(editor).mount(target)', '(editor).destroy(target)'],+ ["editor?.['mount']?.(target)", "editor?.['destroy']?.(target)"],+ ])('lifecycle reference pair: %s', (bad, good) => {+ expect(+ editorLifecycleCalls(bad).filter((violation) =>+ violation.startsWith('editor-lifecycle-reference:'),+ ),+ ).toHaveLength(1);+ expect(editorLifecycleCalls(good)).toEqual([]);+ });+ test.each([+ ['const { unmount } = editor; unmount()', 'const { destroy } = editor; destroy()'],+ ["const { 'mount': m } = editor; m(target)", "const { 'destroy': m } = editor; m(target)"],+ ["const { ['mount']: m } = editor", "const { ['destroy']: m } = editor"],+ ['const { [key]: m } = editor', "const { ['destroy']: m } = editor"],+ ['const { ...rest } = editor', 'const { destroy: rest } = editor'],+ ['({ mount: m } = editor)', '({ destroy: m } = editor)'],+ ["({ ['unmount']: m } = editor)", "({ ['destroy']: m } = editor)"],+ ['({ [key]: m } = editor)', "({ ['destroy']: m } = editor)"],+ ['({ ...rest } = editor)', '({ destroy: rest } = editor)'],+ ])('lifecycle destructuring pair: %s', (bad, good) => {+ expect(+ editorLifecycleCalls(bad).filter((violation) =>+ violation.startsWith('editor-lifecycle-destructure:'),+ ),+ ).toHaveLength(1);+ expect(editorLifecycleCalls(good)).toEqual([]);+ });++ const validCacheSource = cacheFunctions.map((name) => `export function ${name}() {}`).join('\n');+ test.each(cacheFunctions)('requires the local exported implementation %s', (name) => {+ expect(editorCacheViolations(validCacheSource)).toEqual([]);+ expect(+ editorCacheViolations(validCacheSource.replace(`export function ${name}() {}`, '')),+ ).toEqual([`editor-cache implementation: ${name}`]);+ expect(+ editorCacheViolations(+ validCacheSource.replace(`export function ${name}`, `function ${name}`),+ ),+ ).toEqual([`editor-cache implementation: ${name}`]);+ });+ test.each(["export * from './impl';", "export { editor } from './impl';"])(+ 'refuses re-export %s',+ (forward) => {+ expect(editorCacheViolations(validCacheSource)).toEqual([]);+ expect(editorCacheViolations(`${validCacheSource}\n${forward}`)).toEqual([+ 'editor-cache re-export',+ ]);+ },+ );+ test('requires valid syntax in the actual implementation', () => {+ expect(editorCacheViolations(validCacheSource)).toEqual([]);+ expect(+ editorCacheViolations(`${validCacheSource} const broken = ;`).filter((value) =>+ value.startsWith('syntax:'),+ ),+ ).toHaveLength(1);+ });++ test('source contains no editor lifecycle calls on any branch', () => {+ expect(+ editorCacheViolations(readFileSync(new URL('./editor-cache.ts', import.meta.url), 'utf8')),+ ).toEqual([]);});});diff --git a/packages/app/tests/integration/attribution-sweep-coverage.test.ts b/packages/app/tests/integration/attribution-sweep-coverage.test.tsindex b3dc22616..82f5d8837 100644--- a/packages/app/tests/integration/attribution-sweep-coverage.test.ts+++ b/packages/app/tests/integration/attribution-sweep-coverage.test.ts@@ -16,11 +16,6 @@ const HANDLER_SOURCES = [readFileSync(join(SERVER_SRC, file), 'utf8'),),];-const ACTOR_HELPER_PATH = join(- import.meta.dirname,- '../../../server/src/extract-actor-identity.ts',-);-const actorHelperSource = readFileSync(ACTOR_HELPER_PATH, 'utf8');const REQUIRED_HANDLERS = ['handleAgentWrite',@@ -214,11 +209,6 @@ describe('attribution sweep coverage (FR-5, D42)', () => {expect(untracked).toEqual([]);});- test('extract-actor-identity.ts never reads body-supplied principalId (D-A11 trust boundary)', () => {- const code = actorHelperSource.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '');- expect(/body\s*[.[][^a-zA-Z0-9_]*['"]?principalId/.test(code)).toBe(false);- });-test('migrated mutating handlers extract identity before any semantic errorResponse', () => {const failures: string[] = [];for (const handler of REQUIRED_HANDLERS) {diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex a1b48a77f..dacd2ab01 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -610,8 +610,6 @@ function fanOutChromeColors(): void {const DEFAULT_WIN_OPTS: BrowserWindowConstructorOptions = {width: 1280,height: 800,- minWidth: WINDOW_MIN_SIZE.NAVIGATOR.width,- minHeight: WINDOW_MIN_SIZE.NAVIGATOR.height,show: false,...(process.platform === 'darwin'? {@@ -622,6 +620,8 @@ const DEFAULT_WIN_OPTS: BrowserWindowConstructorOptions = {transparent: true,}: buildNonDarwinChromeOpts(nativeTheme.shouldUseDarkColors)),+ minWidth: WINDOW_MIN_SIZE.NAVIGATOR.width,+ minHeight: WINDOW_MIN_SIZE.NAVIGATOR.height,webPreferences: {contextIsolation: true,nodeIntegration: false,diff --git a/packages/desktop/src/main/window-min-size.test.ts b/packages/desktop/src/main/window-min-size.test.tsindex 91ec697b9..eb465c393 100644--- a/packages/desktop/src/main/window-min-size.test.ts+++ b/packages/desktop/src/main/window-min-size.test.ts@@ -1,5 +1,14 @@import { readFileSync } from 'node:fs';import { join } from 'node:path';+import {+ Node,+ type ObjectLiteralElementLike,+ type ObjectLiteralExpression,+ Project,+ type SourceFile,+ SyntaxKind,+ VariableDeclarationKind,+} from 'ts-morph';import { describe, expect, test } from 'vitest';import { WINDOW_MIN_SIZE } from './window-min-size.ts';@@ -35,38 +44,422 @@ describe('WINDOW_MIN_SIZE constants', () => {});});+function isMember(node: Node | undefined, path: readonly string[]): boolean {+ if (node === undefined) return false;+ const [head, ...tail] = path;+ if (tail.length === 0) return Node.isIdentifier(node) && node.getText() === head;+ return (+ Node.isPropertyAccessExpression(node) &&+ !node.hasQuestionDotToken() &&+ node.getName() === path.at(-1) &&+ isMember(node.getExpression(), path.slice(0, -1))+ );+}++function optionName(property: ObjectLiteralElementLike): string | undefined {+ if (Node.isSpreadAssignment(property)) return undefined;+ const name = property.getNameNode();+ if (Node.isStringLiteral(name)) return name.getLiteralValue();+ if (Node.isComputedPropertyName(name)) {+ const expression = name.getExpression();+ return Node.isStringLiteral(expression) || Node.isNoSubstitutionTemplateLiteral(expression)+ ? expression.getLiteralValue()+ : '<computed>';+ }+ return name.getText();+}++const windowFactories = new Map([+ ['WindowManager', 'EDITOR'],+ ['createNavigatorWindow', 'NAVIGATOR'],+ ['createTerminalWindow', 'EDITOR'],+ ['openNoteWindow', 'EDITOR'],+ ['createSlidesWindow', 'EDITOR'],+]);++function namedBindings(file: SourceFile, name: string): Node[] {+ const bindings: Node[] = [];+ for (const declaration of file.getImportDeclarations()) {+ for (const node of [+ declaration.getDefaultImport(),+ declaration.getNamespaceImport(),+ ...declaration+ .getNamedImports()+ .map((specifier) => specifier.getAliasNode() ?? specifier.getNameNode()),+ ]) {+ if (node?.getText() === name) bindings.push(node);+ }+ }+ for (const node of file.getDescendants()) {+ if (+ (Node.isVariableDeclaration(node) ||+ Node.isBindingElement(node) ||+ Node.isParameterDeclaration(node) ||+ Node.isFunctionDeclaration(node) ||+ Node.isFunctionExpression(node) ||+ Node.isClassDeclaration(node) ||+ Node.isClassExpression(node) ||+ Node.isTypeAliasDeclaration(node) ||+ Node.isInterfaceDeclaration(node) ||+ Node.isEnumDeclaration(node) ||+ Node.isTypeParameterDeclaration(node) ||+ Node.isModuleDeclaration(node) ||+ Node.isImportEqualsDeclaration(node)) &&+ node.getNameNode()?.getText() === name+ )+ bindings.push(node);+ }+ return bindings;+}++function windowMinSizeViolations(source: string): string[] {+ const windowProject = new Project({+ useInMemoryFileSystem: true,+ skipAddingFilesFromTsConfig: true,+ skipFileDependencyResolution: true,+ skipLoadingLibFiles: true,+ compilerOptions: { noLib: true },+ });+ const file = windowProject.createSourceFile('/index.ts', source, { overwrite: true });+ try {+ const syntax = windowProject.getProgram().getSyntacticDiagnostics(file);+ if (syntax.length !== 0)+ return syntax.map((error) => `syntax: ${error.getCode()} at ${error.getStart()}`);+ const violations: string[] = [];+ const specifiers = file+ .getImportDeclarations()+ .filter(+ (declaration) =>+ declaration.getModuleSpecifierValue() === './window-min-size.ts' &&+ !declaration.isTypeOnly(),+ )+ .flatMap((declaration) => declaration.getNamedImports())+ .filter(+ (specifier) =>+ specifier.getName() === 'WINDOW_MIN_SIZE' &&+ !specifier.isTypeOnly() &&+ (specifier.getAliasNode()?.getText() ?? specifier.getName()) === 'WINDOW_MIN_SIZE',+ );+ if (specifiers.length !== 1) violations.push('WINDOW_MIN_SIZE import');+ const minimumBindings = namedBindings(file, 'WINDOW_MIN_SIZE');+ const importBinding = specifiers[0]?.getAliasNode() ?? specifiers[0]?.getNameNode();+ if (minimumBindings.length !== 1 || minimumBindings[0] !== importBinding) {+ violations.push('WINDOW_MIN_SIZE binding census');+ }+ const defaultsBindings = namedBindings(file, 'DEFAULT_WIN_OPTS');+ const defaultsDeclaration = file.getVariableDeclaration('DEFAULT_WIN_OPTS');+ const defaultsStatement = defaultsDeclaration?.getVariableStatement();+ const defaults = defaultsDeclaration?.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);+ if (+ defaultsBindings.length !== 1 ||+ defaultsBindings[0] !== defaultsDeclaration ||+ defaultsStatement?.getParent() !== file ||+ defaultsStatement?.getDeclarationKind() !== VariableDeclarationKind.Const ||+ !defaults+ ) {+ violations.push('DEFAULT_WIN_OPTS declaration census');+ }+ const checkMinimum = (+ options: ObjectLiteralExpression | undefined,+ label: string,+ expected: Record<'minWidth' | 'minHeight', readonly string[]>,+ inherit = false,+ ) => {+ const properties = options?.getProperties() ?? [];+ if (properties.some((property) => optionName(property) === '<computed>')) {+ violations.push(`${label} computed option`);+ }+ const omitBoth =+ inherit &&+ !properties.some((property) =>+ ['minWidth', 'minHeight'].includes(optionName(property) ?? ''),+ );+ for (const key of ['minWidth', 'minHeight'] as const) {+ if (omitBoth) continue;+ const matches = properties.filter((property) => optionName(property) === key);+ const property = matches[0];+ if (+ matches.length !== 1 ||+ !Node.isPropertyAssignment(property) ||+ !isMember(property.getInitializer(), expected[key])+ )+ violations.push(`${label}.${key}`);+ if (+ property &&+ properties.some(+ (spread) => Node.isSpreadAssignment(spread) && spread.getStart() > property.getStart(),+ )+ )+ violations.push(`${label} spread after ${key}`);+ }+ };+ const constantPaths = (member: string) => ({+ minWidth: ['WINDOW_MIN_SIZE', member, 'width'],+ minHeight: ['WINDOW_MIN_SIZE', member, 'height'],+ });+ checkMinimum(defaults, 'DEFAULT_WIN_OPTS', constantPaths('NAVIGATOR'));+ const counts = new Map<string, number>();+ const checkedOptions = new Set<ObjectLiteralExpression>();+ const constructors = file.getDescendantsOfKind(SyntaxKind.NewExpression).filter((node) => {+ const expression = node.getExpression();+ return (+ (Node.isIdentifier(expression) && expression.getText() === 'BrowserWindow') ||+ (Node.isPropertyAccessExpression(expression) && expression.getName() === 'BrowserWindow')+ );+ });+ for (const windowConstruction of constructors) {+ const factory = windowConstruction.getFirstAncestor(+ (ancestor) => Node.isPropertyAssignment(ancestor) && ancestor.getName() === 'createWindow',+ );+ const owner = factory?.getParent()?.getParent();+ const expression =+ owner && (Node.isCallExpression(owner) || Node.isNewExpression(owner))+ ? owner.getExpression()+ : undefined;+ const label =+ expression && Node.isIdentifier(expression)+ ? expression.getText()+ : windowConstruction.getFirstAncestorByKind(SyntaxKind.FunctionDeclaration)?.getName();+ const utility = label === 'createDesktopUninstallUtilityWindow' && !factory;+ const member = label === undefined ? undefined : windowFactories.get(label);+ if (label === undefined || (!utility && member === undefined)) {+ violations.push(`unaccounted BrowserWindow: ${label ?? '<unknown>'}`);+ continue;+ }+ counts.set(label, (counts.get(label) ?? 0) + 1);+ const options = windowConstruction.getArguments()[0];+ if (!Node.isObjectLiteralExpression(options)) {+ violations.push(`${label} options`);+ continue;+ }+ checkedOptions.add(options);+ if (utility) {+ checkMinimum(options, label, {+ minWidth: ['options', 'minWidth'],+ minHeight: ['options', 'minHeight'],+ });+ continue;+ }+ const spreads = options.getProperties().filter(Node.isSpreadAssignment);+ const defaultsSpreads = spreads.filter((spread) =>+ isMember(spread.getExpression(), ['DEFAULT_WIN_OPTS']),+ );+ if (defaultsSpreads.length !== 1) violations.push(`${label} DEFAULT_WIN_OPTS spread`);+ if (member === 'NAVIGATOR' && spreads.length !== defaultsSpreads.length) {+ violations.push(`${label} additional spread`);+ }+ checkMinimum(+ options,+ label,+ constantPaths(member ?? ''),+ member === 'NAVIGATOR' && defaultsSpreads.length === 1,+ );+ }+ for (const label of [...windowFactories.keys(), 'createDesktopUninstallUtilityWindow']) {+ if (counts.get(label) !== 1) violations.push(`${label} constructor count`);+ }+ for (const reference of defaultsDeclaration?.findReferencesAsNodes() ?? []) {+ const parent = reference.getParent();+ if (+ Node.isSpreadAssignment(parent) &&+ parent.getExpression() === reference &&+ Node.isObjectLiteralExpression(parent.getParent()) &&+ checkedOptions.has(parent.getParentIfKindOrThrow(SyntaxKind.ObjectLiteralExpression))+ )+ continue;+ if (+ Node.isPropertyAccessExpression(parent) &&+ parent.getExpression() === reference &&+ isMember(parent, ['DEFAULT_WIN_OPTS', 'webPreferences'])+ ) {+ const spread = parent.getParent();+ if (Node.isSpreadAssignment(spread) && spread.getExpression() === parent) continue;+ }+ violations.push(`DEFAULT_WIN_OPTS reference: ${parent.getText()}`);+ }+ return violations;+ } finally {+ windowProject.removeSourceFile(file);+ }+}+describe('main/index.ts wires BrowserWindow min-size at construction', () => {- const indexSource = readFileSync(join(__dirname, 'index.ts'), 'utf-8');+ const validSource = `+ import { WINDOW_MIN_SIZE } from './window-min-size.ts';+ const DEFAULT_WIN_OPTS = { minWidth: WINDOW_MIN_SIZE.NAVIGATOR.width, minHeight: WINDOW_MIN_SIZE.NAVIGATOR.height };+ new WindowManager({ createWindow: (opts) => new BrowserWindow({ ...DEFAULT_WIN_OPTS, minWidth: WINDOW_MIN_SIZE.EDITOR.width, minHeight: WINDOW_MIN_SIZE.EDITOR.height }) });+ createNavigatorWindow({ createWindow: (opts) => new BrowserWindow({ ...DEFAULT_WIN_OPTS }) });+ createTerminalWindow({ createWindow: (opts) => new BrowserWindow({ ...DEFAULT_WIN_OPTS, minWidth: WINDOW_MIN_SIZE.EDITOR.width, minHeight: WINDOW_MIN_SIZE.EDITOR.height }) });+ openNoteWindow({ createWindow: (opts) => new BrowserWindow({ ...DEFAULT_WIN_OPTS, minWidth: WINDOW_MIN_SIZE.EDITOR.width, minHeight: WINDOW_MIN_SIZE.EDITOR.height }) });+ createSlidesWindow({ createWindow: (opts) => new BrowserWindow({ ...DEFAULT_WIN_OPTS, minWidth: WINDOW_MIN_SIZE.EDITOR.width, minHeight: WINDOW_MIN_SIZE.EDITOR.height }) });+ function createDesktopUninstallUtilityWindow(options) { return new BrowserWindow({ minWidth: options.minWidth, minHeight: options.minHeight }); }+ `;++ test('accepts exact members and rejects a platform-dependent minimum', () => {+ expect(windowMinSizeViolations(validSource)).toEqual([]);+ expect(+ windowMinSizeViolations(+ validSource.replace(+ 'minWidth: WINDOW_MIN_SIZE.NAVIGATOR.width',+ "minWidth: process.platform === 'darwin' ? WINDOW_MIN_SIZE.NAVIGATOR.width : 320",+ ),+ ),+ ).toEqual(['DEFAULT_WIN_OPTS.minWidth']);+ });- test('imports WINDOW_MIN_SIZE from the sibling module', () => {- expect(indexSource).toMatch(- /import\s*\{[^}]*\bWINDOW_MIN_SIZE\b[^}]*\}\s*from\s*['"]\.\/window-min-size\.ts?['"]/,+ test('rejects an unaccounted constructor even with valid minima', () => {+ expect(+ windowMinSizeViolations(+ `${validSource}\nnew BrowserWindow({ minWidth: WINDOW_MIN_SIZE.NAVIGATOR.width, minHeight: WINDOW_MIN_SIZE.NAVIGATOR.height });`,+ ),+ ).toEqual(['unaccounted BrowserWindow: <unknown>']);+ });++ test.each(+ [...windowFactories].flatMap(([factory, member]) =>+ ['width', 'height'].map((dimension) => ({ factory, member, dimension })),+ ),+ )('rejects a wrong $dimension on $factory', ({ factory, member, dimension }) => {+ const key = dimension === 'width' ? 'minWidth' : 'minHeight';+ const changed = validSource+ .split('\n')+ .map((line) => {+ if (!line.includes(`${factory}({`)) return line;+ return member === 'NAVIGATOR'+ ? line.replace('...DEFAULT_WIN_OPTS', `...DEFAULT_WIN_OPTS, ${key}: 320`)+ : line.replace(`${key}: WINDOW_MIN_SIZE.${member}.${dimension}`, `${key}: 320`);+ })+ .join('\n');+ expect(windowMinSizeViolations(changed)).toEqual(+ member === 'NAVIGATOR'+ ? [`${factory}.minWidth`, `${factory}.minHeight`]+ : [`${factory}.${key}`],);});- test('DEFAULT_WIN_OPTS sets minWidth using WINDOW_MIN_SIZE.NAVIGATOR.width', () => {- const defaultsBlock = indexSource.match(/const DEFAULT_WIN_OPTS[\s\S]*?^};/m);- expect(defaultsBlock).not.toBeNull();- expect(defaultsBlock?.[0]).toMatch(/minWidth:\s*WINDOW_MIN_SIZE\.NAVIGATOR\.width/);+ test.each([+ ["'minWidth': 320", 'minWidth'],+ ['"minHeight": 240', 'minHeight'],+ ["['minWidth']: 320", 'minWidth'],+ ['["minHeight"]: 240', 'minHeight'],+ ['minWidth', 'minWidth'],+ ['minHeight', 'minHeight'],+ ['get minWidth() { return 320; }', 'minWidth'],+ ])('rejects a Navigator override %s', (override) => {+ const anchor = 'new BrowserWindow({ ...DEFAULT_WIN_OPTS })';+ expect(+ windowMinSizeViolations(+ validSource.replace(anchor, `new BrowserWindow({ ...DEFAULT_WIN_OPTS, ${override} })`),+ ),+ ).toEqual(['createNavigatorWindow.minWidth', 'createNavigatorWindow.minHeight']);});- test('DEFAULT_WIN_OPTS sets minHeight using WINDOW_MIN_SIZE.NAVIGATOR.height', () => {- const defaultsBlock = indexSource.match(/const DEFAULT_WIN_OPTS[\s\S]*?^};/m);- expect(defaultsBlock).not.toBeNull();- expect(defaultsBlock?.[0]).toMatch(/minHeight:\s*WINDOW_MIN_SIZE\.NAVIGATOR\.height/);+ test('accepts equivalent quoted and computed constant option names', () => {+ expect(+ windowMinSizeViolations(+ validSource.replace('minWidth:', "'minWidth':").replace('minHeight:', "['minHeight']:"),+ ),+ ).toEqual([]);});- const editorFactoryBlock = indexSource.match(- /createWindow:\s*\(opts\)[\s\S]*?page-title-updated[\s\S]*?^\s*\},/m,+ test.each([+ '...override',+ '...chrome()',+ '...(platform ? left : right)',+ '...{ ...{ minWidth: 1 } }',+ ])('requires minima after every opaque spread %s', (spread) => {+ const minimum =+ 'minWidth: WINDOW_MIN_SIZE.NAVIGATOR.width, minHeight: WINDOW_MIN_SIZE.NAVIGATOR.height';+ expect(windowMinSizeViolations(validSource.replace(minimum, `${spread}, ${minimum}`))).toEqual(+ [],+ );+ expect(windowMinSizeViolations(validSource.replace(minimum, `${minimum}, ${spread}`))).toEqual([+ 'DEFAULT_WIN_OPTS spread after minWidth',+ 'DEFAULT_WIN_OPTS spread after minHeight',+ ]);+ const utility = 'minWidth: options.minWidth, minHeight: options.minHeight';+ expect(windowMinSizeViolations(validSource.replace(utility, `${spread}, ${utility}`))).toEqual(+ [],+ );+ expect(windowMinSizeViolations(validSource.replace(utility, `${utility}, ${spread}`))).toEqual([+ 'createDesktopUninstallUtilityWindow spread after minWidth',+ 'createDesktopUninstallUtilityWindow spread after minHeight',+ ]);+ });+ test.each(['minWidth', "'minWidth'", "['minWidth']"])(+ 'counts duplicate utility properties %s',+ (key) => {+ expect(windowMinSizeViolations(validSource)).toEqual([]);+ expect(+ windowMinSizeViolations(+ validSource.replace(+ 'minHeight: options.minHeight',+ `minHeight: options.minHeight, ${key}: 1`,+ ),+ ),+ ).toEqual(['createDesktopUninstallUtilityWindow.minWidth']);+ },);-- test('Editor BrowserWindow constructor overrides minWidth to WINDOW_MIN_SIZE.EDITOR.width', () => {- expect(editorFactoryBlock).not.toBeNull();- expect(editorFactoryBlock?.[0]).toMatch(/minWidth:\s*WINDOW_MIN_SIZE\.EDITOR\.width/);+ test.each([+ 'DEFAULT_WIN_OPTS.minWidth = 1;',+ 'Object.assign(DEFAULT_WIN_OPTS, { minWidth: 1 });',+ 'const alias = DEFAULT_WIN_OPTS;',+ 'const elsewhere = { ...DEFAULT_WIN_OPTS };',+ 'void DEFAULT_WIN_OPTS.webPreferences;',+ ])('refuses the defaults reference %s', (statement) => {+ expect(windowMinSizeViolations(validSource)).toEqual([]);+ expect(+ windowMinSizeViolations(`${validSource} ${statement}`).filter((value) =>+ value.startsWith('DEFAULT_WIN_OPTS reference:'),+ ),+ ).toHaveLength(1);+ });+ test.each([+ 'function f() { const DEFAULT_WIN_OPTS = {}; }',+ 'function f(DEFAULT_WIN_OPTS) {}',+ 'function DEFAULT_WIN_OPTS() {}',+ 'class DEFAULT_WIN_OPTS {}',+ ])('refuses extra defaults binding %s', (statement) => {+ expect(windowMinSizeViolations(validSource)).toEqual([]);+ expect(+ windowMinSizeViolations(`${validSource} ${statement}`).filter(+ (value) => value === 'DEFAULT_WIN_OPTS declaration census',+ ),+ ).toHaveLength(1);+ });+ test.each([+ 'const WINDOW_MIN_SIZE = {};',+ 'function f(WINDOW_MIN_SIZE) {}',+ 'function WINDOW_MIN_SIZE() {}',+ 'class WINDOW_MIN_SIZE {}',+ ])('requires the sole WINDOW_MIN_SIZE import binding: %s', (statement) => {+ expect(windowMinSizeViolations(validSource)).toEqual([]);+ expect(windowMinSizeViolations(`${validSource} function scope() { ${statement} }`)).toEqual([+ 'WINDOW_MIN_SIZE binding census',+ ]);+ });+ test('requires module-level const defaults and valid syntax', () => {+ expect(windowMinSizeViolations(validSource)).toEqual([]);+ expect(+ windowMinSizeViolations(+ validSource.replace('const DEFAULT_WIN_OPTS', 'let DEFAULT_WIN_OPTS'),+ ),+ ).toContain('DEFAULT_WIN_OPTS declaration census');+ expect(+ windowMinSizeViolations(+ validSource+ .replace('const DEFAULT_WIN_OPTS', 'function scope() { const DEFAULT_WIN_OPTS')+ .replace(';\n new WindowManager', '; }\n new WindowManager'),+ ),+ ).toContain('DEFAULT_WIN_OPTS declaration census');+ expect(+ windowMinSizeViolations(`${validSource} const broken = ;`).filter((value) =>+ value.startsWith('syntax:'),+ ),+ ).toHaveLength(1);});- test('Editor BrowserWindow constructor overrides minHeight to WINDOW_MIN_SIZE.EDITOR.height', () => {- expect(editorFactoryBlock).not.toBeNull();- expect(editorFactoryBlock?.[0]).toMatch(/minHeight:\s*WINDOW_MIN_SIZE\.EDITOR\.height/);+ test('all constructors use their unconditional width and height members', () => {+ expect(windowMinSizeViolations(readFileSync(join(__dirname, 'index.ts'), 'utf-8'))).toEqual([]);});});diff --git a/packages/desktop/tests/integration/dock-visibility.test.ts b/packages/desktop/tests/integration/dock-visibility.test.tsindex b034abc99..863fa80a8 100644--- a/packages/desktop/tests/integration/dock-visibility.test.ts+++ b/packages/desktop/tests/integration/dock-visibility.test.ts@@ -1,6 +1,7 @@import { readFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';+import { Node, Project, type SourceFile, SyntaxKind, VariableDeclarationKind } from 'ts-morph';import { describe, expect, test } from 'vitest';import { resolveDetachedSpawnArgs } from '../../src/main/resolve-detached-spawn-args.ts';@@ -22,11 +23,337 @@ function innermostAppContainer(pathLike: string): string | null {return null;}+const spawnProject = new Project({+ useInMemoryFileSystem: true,+ skipAddingFilesFromTsConfig: true,+ skipFileDependencyResolution: true,+ skipLoadingLibFiles: true,+ compilerOptions: { noLib: true },+});++function unwrapSpawnNode(node: Node | undefined): Node | undefined {+ while (+ Node.isParenthesizedExpression(node) ||+ Node.isAsExpression(node) ||+ Node.isTypeAssertion(node) ||+ Node.isExpressionWithTypeArguments(node) ||+ Node.isSatisfiesExpression(node) ||+ Node.isNonNullExpression(node)+ )+ node = node.getExpression();+ return node;+}++function spawnCallee(node: Node): boolean {+ return (+ (Node.isIdentifier(node) && node.getText().endsWith('spawn')) ||+ (Node.isPropertyAccessExpression(node) && node.getName().endsWith('spawn'))+ );+}++function processIdentifier(node: Node | undefined): boolean {+ node = unwrapSpawnNode(node);+ return Node.isIdentifier(node) && node.getText() === 'process';+}++function execPathKey(node: Node | undefined): boolean {+ node = unwrapSpawnNode(node);+ if (Node.isComputedPropertyName(node)) return execPathKey(node.getExpression());+ return (+ (Node.isIdentifier(node) && node.getText() === 'execPath') ||+ ((Node.isStringLiteral(node) || Node.isNoSubstitutionTemplateLiteral(node)) &&+ node.getLiteralValue() === 'execPath')+ );+}++function parentSpawns(file: SourceFile): string[] {+ const assignments = file+ .getDescendantsOfKind(SyntaxKind.BinaryExpression)+ .filter((node) =>+ [+ SyntaxKind.EqualsToken,+ SyntaxKind.BarBarEqualsToken,+ SyntaxKind.AmpersandAmpersandEqualsToken,+ SyntaxKind.QuestionQuestionEqualsToken,+ ].includes(node.getOperatorToken().getKind()),+ );+ function isParentBinary(node: Node | undefined, seen = new Set<Node>()): boolean {+ node = unwrapSpawnNode(node);+ if (node === undefined || seen.has(node)) return false;+ seen.add(node);+ if (Node.isPropertyAccessExpression(node))+ return processIdentifier(node.getExpression()) && node.getName() === 'execPath';+ if (Node.isElementAccessExpression(node)) {+ const key = unwrapSpawnNode(node.getArgumentExpression());+ return (+ processIdentifier(node.getExpression()) &&+ (Node.isStringLiteral(key) || Node.isNoSubstitutionTemplateLiteral(key)) &&+ key.getLiteralValue() === 'execPath'+ );+ }+ if (Node.isConditionalExpression(node))+ return isParentBinary(node.getWhenTrue(), seen) || isParentBinary(node.getWhenFalse(), seen);+ if (+ Node.isBinaryExpression(node) &&+ [+ SyntaxKind.QuestionQuestionToken,+ SyntaxKind.BarBarToken,+ SyntaxKind.AmpersandAmpersandToken,+ ].includes(node.getOperatorToken().getKind())+ ) {+ return isParentBinary(node.getLeft(), seen) || isParentBinary(node.getRight(), seen);+ }+ if (!Node.isIdentifier(node)) return false;+ const declarations = node.getSymbol()?.getDeclarations() ?? [];+ const bindings = declarations.filter(+ (declaration) =>+ Node.isVariableDeclaration(declaration) || Node.isBindingElement(declaration),+ );+ for (const declaration of bindings) {+ if (+ Node.isVariableDeclaration(declaration) &&+ isParentBinary(declaration.getInitializer(), seen)+ )+ return true;+ if (+ Node.isBindingElement(declaration) &&+ !declaration.getDotDotDotToken() &&+ execPathKey(declaration.getPropertyNameNode() ?? declaration.getNameNode())+ ) {+ const pattern = declaration.getParent();+ const variable = pattern.getParent();+ if (+ Node.isObjectBindingPattern(pattern) &&+ Node.isVariableDeclaration(variable) &&+ processIdentifier(variable.getInitializer())+ )+ return true;+ }+ }+ return assignments.some((assignment) => {+ const target = unwrapSpawnNode(assignment.getLeft());+ return (+ Node.isIdentifier(target) &&+ (target.getSymbol()?.getDeclarations() ?? []).some((declaration) =>+ bindings.includes(declaration),+ ) &&+ isParentBinary(assignment.getRight(), seen)+ );+ });+ }+ return file+ .getDescendants()+ .filter((node) => Node.isCallExpression(node) || Node.isNewExpression(node))+ .filter((call) => spawnCallee(call.getExpression()) && isParentBinary(call.getArguments()[0]))+ .map((call) => `parent-binary-spawn: ${call.getText()}`);+}++function directParentSpawns(source: string): string[] {+ const file = spawnProject.createSourceFile('/index.ts', source, { overwrite: true });+ try {+ return parentSpawns(file);+ } finally {+ spawnProject.removeSourceFile(file);+ }+}++function detachedSpawnViolations(source: string): string[] {+ const file = spawnProject.createSourceFile('/index.ts', source, { overwrite: true });+ try {+ const violations = spawnProject+ .getProgram()+ .getSyntacticDiagnostics(file)+ .map((error) => `syntax: ${error.getCode()} at ${error.getStart()}`);+ const resolvers = file.getDescendantsOfKind(SyntaxKind.CallExpression).filter((call) => {+ const callee = call.getExpression();+ return Node.isIdentifier(callee) && callee.getText() === 'resolveDetachedSpawnArgs';+ });+ if (resolvers.length !== 1) violations.push('detached-resolver call census');+ const call = resolvers[0];+ const binding = call?.getParent();+ if (+ !Node.isVariableDeclaration(binding) ||+ binding.getInitializer() !== call ||+ binding.getVariableStatement()?.getDeclarationKind() !== VariableDeclarationKind.Const ||+ !Node.isIdentifier(binding.getNameNode())+ ) {+ violations.push('detached-resolver const binding');+ } else {+ const launch = file+ .getDescendants()+ .filter((node) => Node.isCallExpression(node) || Node.isNewExpression(node))+ .some((node) => {+ const first = node.getArguments()[0];+ if (+ !spawnCallee(node.getExpression()) ||+ !Node.isPropertyAccessExpression(first) ||+ first.getName() !== 'file'+ )+ return false;+ const receiver = first.getExpression();+ return (+ Node.isIdentifier(receiver) &&+ (receiver.getSymbol()?.getDeclarations() ?? []).includes(binding)+ );+ });+ if (!launch) violations.push('detached-resolver launch census');+ }+ return [...violations, ...parentSpawns(file)];+ } finally {+ spawnProject.removeSourceFile(file);+ }+}+describe('detached-server spawn: macOS Dock visibility regression guard', () => {+ test.each([+ 'spawn(process.execPath)',+ 'respawn(process.execPath, args)',+ 'cp.respawn(process.execPath, args)',+ 'new spawn(process.execPath, args)',+ 'new cp.spawn(process.execPath, args)',+ 'spawn ( process.execPath, args)',+ 'childProcess.spawn(process.execPath, args)',+ 'cp.spawn(process.execPath, args)',+ 'nested.cp.spawn(process.execPath, args)',+ 'const node = process.execPath; spawn(node, args)',+ 'const node = process.execPath; cp.spawn(node, args)',+ 'const node = process.execPath; const alias = node; spawn(alias, args)',+ ])('detects bypass %s', (source) => {+ expect(directParentSpawns(source)).toHaveLength(1);+ });++ test('allows the resolved binary and locally shadowed safe aliases', () => {+ expect(+ directParentSpawns(`+ spawn(resolved.file, args); cp.spawn(resolved.file, args);+ cp.execFile(process.execPath, args);+ const node = process.execPath;+ function launch() { const node = resolved.file; spawn(node, args); }+ function launchParameter(node) { cp.spawn(node, args); }+ /* spawn(process.execPath, args); */+ const example = 'spawn(process.execPath, args)';+ `),+ ).toEqual([]);+ });++ test.each([+ [+ 'let exe; exe = process.execPath; spawn(exe, args)',+ 'let exe; exe = resolved.file; spawn(exe, args)',+ ],+ [+ 'let exe; exe ||= process.execPath; spawn(exe, args)',+ 'let exe; exe ||= resolved.file; spawn(exe, args)',+ ],+ [+ 'let exe; exe &&= process.execPath; spawn(exe, args)',+ 'let exe; exe &&= resolved.file; spawn(exe, args)',+ ],+ [+ 'let exe; exe ??= process.execPath; spawn(exe, args)',+ 'let exe; exe ??= resolved.file; spawn(exe, args)',+ ],+ [+ 'const { execPath } = process; spawn(execPath, args)',+ 'const { execPath } = runtime; spawn(execPath, args)',+ ],+ [+ 'const { execPath: exe } = process; spawn(exe, args)',+ 'const { execPath: exe } = runtime; spawn(exe, args)',+ ],+ ["spawn(process['execPath'], args)", "spawn(process['other'], args)"],+ ['spawn(process?.execPath, args)', 'spawn(process?.other, args)'],+ ['spawn(process?.[`execPath`], args)', 'spawn(process?.[`other`], args)'],+ [+ 'spawn(isDev ? process.execPath : resolved.file, args)',+ 'spawn(isDev ? resolved.file : other.file, args)',+ ],+ [+ 'spawn(isDev ? resolved.file : process.execPath, args)',+ 'spawn(isDev ? resolved.file : other.file, args)',+ ],+ ['spawn((process.execPath as string), args)', 'spawn((resolved.file as string), args)'],+ ['spawn(<string>process.execPath, args)', 'spawn(<string>resolved.file, args)'],+ ['spawn(process.execPath<string>, args)', 'spawn(resolved.file<string>, args)'],+ [+ 'spawn((process.execPath satisfies string), args)',+ 'spawn((resolved.file satisfies string), args)',+ ],+ ['spawn(process.execPath!, args)', 'spawn(resolved.file!, args)'],+ [+ 'let exe = process.execPath; exe = resolved.file; spawn(exe, args)',+ 'let exe = other.file; exe = resolved.file; spawn(exe, args)',+ ],+ [+ 'let one = two; let two = one; two = process.execPath; spawn(one, args)',+ 'let one = two; let two = one; spawn(one, args)',+ ],+ [+ 'let exe; function later() { exe = process.execPath; } spawn(exe, args)',+ 'let exe; function later() { let exe = process.execPath; } spawn(exe, args)',+ ],+ ['spawn(process.execPath ?? resolved.file, args)', 'spawn(resolved.file ?? other.file, args)'],+ ['spawn(resolved.file ?? process.execPath, args)', 'spawn(resolved.file ?? other.file, args)'],+ ['spawn(process.execPath || resolved.file, args)', 'spawn(resolved.file || other.file, args)'],+ ['spawn(resolved.file || process.execPath, args)', 'spawn(resolved.file || other.file, args)'],+ ['spawn(process.execPath && resolved.file, args)', 'spawn(resolved.file && other.file, args)'],+ ['spawn(resolved.file && process.execPath, args)', 'spawn(resolved.file && other.file, args)'],+ ])('parent-binary pair: %s', (bad, good) => {+ expect(+ directParentSpawns(bad).filter((violation) => violation.startsWith('parent-binary-spawn:')),+ ).toHaveLength(1);+ expect(directParentSpawns(good)).toEqual([]);+ });++ test('bounds parameters and object-held paths outside local binding analysis', () => {+ expect(directParentSpawns('function launchWith(file) { spawn(file, args); }')).toEqual([]);+ expect(+ directParentSpawns(+ 'function launchWith(file) { file = process.execPath; spawn(file, args); }',+ ),+ ).toEqual([]);+ expect(directParentSpawns('const o = { exe: process.execPath }; spawn(o.exe, args);')).toEqual(+ [],+ );+ });+ const validLaunchSource =+ 'const args = resolveDetachedSpawnArgs({}); spawn(args.file, args.args);';+ test.each([+ ['', 'detached-resolver call census'],+ ['const args = {}; spawn(args.file, args.args);', 'detached-resolver call census'],+ [+ 'const args = resolveDetachedSpawnArgs({}); const more = resolveDetachedSpawnArgs({}); spawn(args.file, args.args);',+ 'detached-resolver call census',+ ],+ [+ 'let args = resolveDetachedSpawnArgs({}); spawn(args.file, args.args);',+ 'detached-resolver const binding',+ ],+ ['resolveDetachedSpawnArgs({});', 'detached-resolver const binding'],+ [+ 'const args = resolveDetachedSpawnArgs({}); launch(args.file);',+ 'detached-resolver launch census',+ ],+ [+ 'const args = resolveDetachedSpawnArgs({}); function launch() { const args = {}; spawn(args.file); }',+ 'detached-resolver launch census',+ ],+ ])('requires the launch census: %s', (source, violation) => {+ expect(detachedSpawnViolations(validLaunchSource)).toEqual([]);+ expect(detachedSpawnViolations(source).filter((value) => value === violation)).toHaveLength(1);+ });+ test('requires syntactically valid launch source', () => {+ expect(detachedSpawnViolations(validLaunchSource)).toEqual([]);+ expect(+ detachedSpawnViolations(`${validLaunchSource} const broken = ;`).filter((value) =>+ value.startsWith('syntax:'),+ ),+ ).toHaveLength(1);+ });+test('bypass-pin — index.ts must not call spawn(process.execPath, ...) directly', () => {const src = readFileSync(indexTsPath, 'utf-8');- const bypass = /spawn\s*\(\s*process\.execPath\s*[,)]/;- const match = bypass.exec(src);+ const match = detachedSpawnViolations(src);expect(match,`\n[dock-visibility] index.ts contains a direct \`spawn(process.execPath, ...)\` ` +@@ -41,7 +368,7 @@ describe('detached-server spawn: macOS Dock visibility regression guard', () =>`If you intentionally need to spawn the parent binary directly (e.g. for non-detached ` +`cases not subject to LaunchServices), document the reason inline and update this test ` +`to scope the bypass-pin to the spawnDetachedServer callback specifically.\n`,- ).toBeNull();+ ).toEqual([]);});test('runtime pin — resolveDetachedSpawnArgs() returns a structurally safe shape on darwin packaged', () => {diff --git a/packages/server/src/extract-actor-identity.test.ts b/packages/server/src/extract-actor-identity.test.tsindex 44abda008..303b7afe9 100644--- a/packages/server/src/extract-actor-identity.test.ts+++ b/packages/server/src/extract-actor-identity.test.ts@@ -1,4 +1,6 @@+import { readFileSync } from 'node:fs';import type { Principal } from '@inkeep/open-knowledge-core';+import { Node, Project, type SourceFile, SyntaxKind } from 'ts-morph';import { describe, expect, test } from 'vitest';import { extractActorIdentity } from './extract-actor-identity.ts';@@ -187,3 +189,318 @@ describe('extractActorIdentity — summary validation', () => {expect(result.summary.kind).toBe('absent');});});++function isPrincipalKeyText(value: string): boolean {+ return value.replace(/^[^a-zA-Z0-9_]*/, '').startsWith('principalId');+}++function unwrapBodyNode(node: Node | undefined): Node | undefined {+ while (+ Node.isParenthesizedExpression(node) ||+ Node.isAsExpression(node) ||+ Node.isTypeAssertion(node) ||+ Node.isExpressionWithTypeArguments(node) ||+ Node.isSatisfiesExpression(node) ||+ Node.isNonNullExpression(node)+ )+ node = node.getExpression();+ return node;+}++function isBodyReceiver(node: Node | undefined): boolean {+ node = unwrapBodyNode(node);+ return (+ (Node.isIdentifier(node) && node.getText().endsWith('body')) ||+ (Node.isPropertyAccessExpression(node) && node.getName().endsWith('body'))+ );+}++function principalKey(node: Node | undefined, computed: boolean): boolean {+ node = unwrapBodyNode(node);+ if (Node.isComputedPropertyName(node)) return principalKey(node.getExpression(), true);+ if (Node.isStringLiteral(node) || Node.isNoSubstitutionTemplateLiteral(node))+ return isPrincipalKeyText(node.getLiteralValue());+ if (Node.isNumericLiteral(node)) return isPrincipalKeyText(String(node.getLiteralValue()));+ if (!computed && Node.isIdentifier(node)) return isPrincipalKeyText(node.getText());+ return true;+}++function principalReads(file: SourceFile): string[] {+ const violations: string[] = [];+ for (const node of file.getDescendants()) {+ if (+ (Node.isPropertyAccessExpression(node) &&+ isBodyReceiver(node.getExpression()) &&+ isPrincipalKeyText(node.getName())) ||+ (Node.isElementAccessExpression(node) &&+ isBodyReceiver(node.getExpression()) &&+ principalKey(node.getArgumentExpression(), true))+ ) {+ violations.push(`body-principal-access: ${node.getText()}`);+ }+ if (Node.isVariableDeclaration(node) && isBodyReceiver(node.getInitializer())) {+ const pattern = node.getNameNode();+ if (Node.isObjectBindingPattern(pattern)) {+ for (const element of pattern.getElements()) {+ if (+ element.getDotDotDotToken() ||+ principalKey(element.getPropertyNameNode() ?? element.getNameNode(), false)+ ) {+ violations.push(`body-principal-destructure: ${element.getText()}`);+ }+ }+ }+ }+ if (+ Node.isBinaryExpression(node) &&+ node.getOperatorToken().getKind() === SyntaxKind.EqualsToken &&+ isBodyReceiver(node.getRight())+ ) {+ const pattern = unwrapBodyNode(node.getLeft());+ if (Node.isObjectLiteralExpression(pattern)) {+ for (const property of pattern.getProperties()) {+ if (Node.isSpreadAssignment(property) || principalKey(property.getNameNode(), false)) {+ violations.push(`body-principal-destructure: ${property.getText()}`);+ }+ }+ }+ }+ }+ return violations;+}++function createIdentityProject(): Project {+ return new Project({+ useInMemoryFileSystem: true,+ skipAddingFilesFromTsConfig: true,+ skipFileDependencyResolution: true,+ skipLoadingLibFiles: true,+ compilerOptions: { noLib: true },+ });+}++function bodyPrincipalReads(source: string): string[] {+ const identityProject = createIdentityProject();+ const file = identityProject.createSourceFile('/extract-actor-identity.ts', source, {+ overwrite: true,+ });+ try {+ return principalReads(file);+ } finally {+ identityProject.removeSourceFile(file);+ }+}++function actorIdentityViolations(source: string): string[] {+ const identityProject = createIdentityProject();+ const file = identityProject.createSourceFile('/extract-actor-identity.ts', source, {+ overwrite: true,+ });+ try {+ const violations = identityProject+ .getProgram()+ .getSyntacticDiagnostics(file)+ .map((error) => `syntax: ${error.getCode()} at ${error.getStart()}`);+ if (file.getExportDeclarations().some((declaration) => declaration.getModuleSpecifier())) {+ violations.push('actor-identity re-export');+ }+ const functions = file.getFunctions().filter((declaration) => declaration.isExported());+ const declaration = functions[0];+ const parameter = declaration?.getParameters()[0];+ const name = parameter?.getNameNode();+ if (+ functions.length !== 1 ||+ declaration?.getName() !== 'extractActorIdentity' ||+ !declaration.getBody() ||+ !Node.isIdentifier(name) ||+ name.getText() !== 'body'+ ) {+ violations.push('actor-identity implementation census');+ }+ if (parameter && Node.isIdentifier(name) && name.getText() === 'body') {+ for (const reference of parameter.findReferencesAsNodes()) {+ const parent = reference.getParent();+ if (+ (Node.isPropertyAccessExpression(parent) || Node.isElementAccessExpression(parent)) &&+ parent.getExpression() === reference+ )+ continue;+ if (+ Node.isVariableDeclaration(parent) &&+ parent.getInitializer() === reference &&+ Node.isObjectBindingPattern(parent.getNameNode())+ )+ continue;+ if (+ Node.isBinaryExpression(parent) &&+ parent.getOperatorToken().getKind() === SyntaxKind.EqualsToken &&+ parent.getRight() === reference &&+ Node.isObjectLiteralExpression(unwrapBodyNode(parent.getLeft()))+ )+ continue;+ if (+ Node.isCallExpression(parent) &&+ parent.getArguments().length === 1 &&+ parent.getArguments()[0] === reference+ ) {+ const callee = parent.getExpression();+ if (Node.isIdentifier(callee) && callee.getText() === 'parseAgentBodyFields') continue;+ }+ violations.push(`body-parameter-use: ${parent.getText()}`);+ }+ }+ return [...violations, ...principalReads(file)];+ } finally {+ identityProject.removeSourceFile(file);+ }+}++describe('extractActorIdentity — structural D-A11 trust boundary', () => {+ test.each([+ 'body.principalId',+ "body['principalId']",+ 'body["principalId"]',+ 'body[principalId]',+ 'body[/principalId/.source]',+ 'body[$principalId]',+ 'body[πprincipalId]',+ 'body.$principalId',+ "body['$principalId']",+ "body[('principalId')]",+ "body['principalId' as const]",+ 'body[principalId + suffix]',+ `body[\`principalId\${suffix}\`]`,+ 'body[`principalId`]',+ 'body?.principalId',+ "body?.['principalId']",+ 'body?.["principalId"]',+ 'request.body.principalId',+ 'body.principalIdFallback',+ 'const { principalId } = body;',+ 'const { principalId: claimed } = body;',+ "const { ['principalId']: claimed } = body;",+ "const { 'principalId': claimed } = body;",+ '({ principalId } = body);',+ ])('detects a body principal read in %s', (source) => {+ expect(bodyPrincipalReads(source)).toHaveLength(1);+ });++ test('allows server identity and adjacent body fields, including destructuring', () => {+ expect(+ bodyPrincipalReads(`+ principal.id; actor.principalId; body.agentId;+ const { principalId } = actor;+ const { agentId: principalId } = body;+ body['agentId']; body?.agentId;+ /* body.principalId */+ const example = "body['principalId']";+ `),+ ).toEqual([]);+ });++ test.each([+ [`body[\`\${''}principalId\`]`, "body['agentId']"],+ [`body[\`\${''}principalId\${''}\`]`, 'body[`agentId`]'],+ ['body[key]', "body['agentId']"],+ ['body[key()]', "body['agentId']"],+ ["body['agent' + 'Id']", "body['agentId']"],+ ['body[/principalId/.source]', "body['agentId']"],+ ["body[('principalId' as string)]", "body[('agentId' as string)]"],+ ["body['principalId' satisfies string]", "body['agentId' satisfies string]"],+ ["body['principalId'!]", "body['agentId'!]"],+ ['body[selector]', 'body[0]'],+ ['(body as Record<string, unknown>).principalId', '(body as Record<string, unknown>).agentId'],+ ['(<Record<string, unknown>>body).principalId', '(<Record<string, unknown>>body).agentId'],+ [+ "(body<Record<string, unknown>>)['principalId']",+ "(body<Record<string, unknown>>)['agentId']",+ ],+ [+ '(body satisfies Record<string, unknown>).principalId',+ '(body satisfies Record<string, unknown>).agentId',+ ],+ ['body!.principalId', 'body!.agentId'],+ ['(request.body).principalId', '(request.body).agentId'],+ ])('principal access pair: %s', (bad, good) => {+ expect(+ bodyPrincipalReads(bad).filter((violation) => violation.startsWith('body-principal-access:')),+ ).toHaveLength(1);+ expect(bodyPrincipalReads(good)).toEqual([]);+ });+ test.each([+ ['const { ...rest } = body', 'const { agentId: rest } = body'],+ ['const { [key]: claim } = body', "const { ['agentId']: claim } = body"],+ ["const { ['principalId']: claim } = body", "const { ['agentId']: claim } = body"],+ ['({ ...rest } = body)', '({ agentId: rest } = body)'],+ ['({ [key]: claim } = body)', "({ ['agentId']: claim } = body)"],+ ["({ ['principalId']: claim } = body)", "({ ['agentId']: claim } = body)"],+ ['const { principalId } = body', 'const { agentId } = body'],+ ])('principal destructuring pair: %s', (bad, good) => {+ expect(+ bodyPrincipalReads(bad).filter((violation) =>+ violation.startsWith('body-principal-destructure:'),+ ),+ ).toHaveLength(1);+ expect(bodyPrincipalReads(good)).toEqual([]);+ });++ const validIdentitySource =+ 'export function extractActorIdentity(body) { parseAgentBodyFields(body); return body.agentId; }';+ test.each([+ 'const payload = body;',+ 'void (body as Record<string, unknown>).agentId;',+ 'void (body satisfies Record<string, unknown>).agentId;',+ 'void body!.agentId;',+ 'const copy = { ...body };',+ 'void readClaim(body);',+ 'return body;',+ 'void { body };',+ 'parseAgentBodyFields(body, other);',+ ])('refuses unaccounted parameter reference %s', (statement) => {+ expect(actorIdentityViolations(validIdentitySource)).toEqual([]);+ expect(+ actorIdentityViolations(`export function extractActorIdentity(body) { ${statement} }`),+ ).toHaveLength(1);+ expect(+ actorIdentityViolations(`export function extractActorIdentity(body) { ${statement} }`)[0],+ ).toContain('body-parameter-use:');+ });+ test.each(["export * from './impl';", "export { extractActorIdentity } from './impl';"])(+ 'refuses identity re-export %s',+ (forward) => {+ expect(actorIdentityViolations(validIdentitySource)).toEqual([]);+ expect(actorIdentityViolations(`${validIdentitySource}\n${forward}`)).toEqual([+ 'actor-identity re-export',+ ]);+ },+ );+ test.each([+ '',+ 'export function different(body) {}',+ 'function extractActorIdentity(body) {}',+ 'export function extractActorIdentity(payload) {}',+ 'export declare function extractActorIdentity(body);',+ 'export function extractActorIdentity(body) {} export function other() {}',+ ])('requires the identity implementation census: %s', (source) => {+ expect(actorIdentityViolations(validIdentitySource)).toEqual([]);+ expect(actorIdentityViolations(source)).toEqual(['actor-identity implementation census']);+ });+ test('checks syntax and resolves body references by symbol', () => {+ expect(+ actorIdentityViolations(`${validIdentitySource} function other(body) { return body; }`),+ ).toEqual([]);+ expect(+ actorIdentityViolations(`${validIdentitySource} const broken = ;`).filter((value) =>+ value.startsWith('syntax:'),+ ),+ ).toHaveLength(1);+ });++ test('extract-actor-identity.ts never reads body-supplied principalId (D-A11 trust boundary)', () => {+ expect(+ actorIdentityViolations(+ readFileSync(new URL('./extract-actor-identity.ts', import.meta.url), 'utf8'),+ ),+ ).toEqual([]);+ });+});