fix: harden Cursor hooks
This commit is contained in:
1 parent
d5a2dcbe53
commit
6d36f557b1
7 files changed
+1109
-126
No files matched your search
@@ -0,0 +1,329 @@
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
parse,
|
||||
parseTree,
|
||||
printParseErrorCode,
|
||||
type Node,
|
||||
type ParseError,
|
||||
} from 'jsonc-parser';
|
||||
|
||||
export const AGENT_KEY = 'cursor';
|
||||
export const CONFIG_FILE = 'hooks.json';
|
||||
export const GUARD_SCRIPT = 'guard.js';
|
||||
export const AUDIT_SCRIPT = 'hook.js';
|
||||
export const HOOK_TIMEOUT_SECONDS = 10;
|
||||
|
||||
export type JsonObject = Record<string, unknown>;
|
||||
export type CursorHooks = Record<string, JsonObject[]>;
|
||||
|
||||
export interface CursorDocument {
|
||||
readonly exists: boolean;
|
||||
readonly filePath: string;
|
||||
readonly root: JsonObject;
|
||||
readonly hooks: CursorHooks;
|
||||
readonly raw?: string;
|
||||
}
|
||||
|
||||
export interface RenderedDocument {
|
||||
readonly document: CursorDocument;
|
||||
readonly changed: boolean;
|
||||
readonly next?: string;
|
||||
}
|
||||
|
||||
export interface RuntimeContract {
|
||||
readonly agentId: string;
|
||||
readonly guardPath: string;
|
||||
readonly auditPath: string;
|
||||
}
|
||||
|
||||
interface ParsedArgument {
|
||||
readonly value: string;
|
||||
readonly next: number;
|
||||
}
|
||||
|
||||
export function isObject(value: unknown): value is JsonObject {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
export function samePath(left: string, right: string): boolean {
|
||||
const normalizedLeft = path.resolve(left);
|
||||
const normalizedRight = path.resolve(right);
|
||||
return process.platform === 'win32'
|
||||
? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
|
||||
: normalizedLeft === normalizedRight;
|
||||
}
|
||||
|
||||
function sameAgentId(left: string, right: string): boolean {
|
||||
return process.platform === 'win32'
|
||||
? left.toLowerCase() === right.toLowerCase()
|
||||
: left === right;
|
||||
}
|
||||
|
||||
function quotePosix(value: string): string {
|
||||
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
||||
}
|
||||
|
||||
function quotePowerShell(value: string): string {
|
||||
return `'${value.replaceAll("'", "''")}'`;
|
||||
}
|
||||
|
||||
export function buildHandler(scriptPath: string): JsonObject {
|
||||
const command = process.platform === 'win32'
|
||||
? `& ${quotePowerShell(process.execPath)} ${quotePowerShell(scriptPath)}; exit $LASTEXITCODE`
|
||||
: `${quotePosix(process.execPath)} ${quotePosix(scriptPath)}`;
|
||||
return {
|
||||
command,
|
||||
timeout: HOOK_TIMEOUT_SECONDS,
|
||||
failClosed: true,
|
||||
};
|
||||
}
|
||||
|
||||
function readPosixArgument(command: string, start: number): ParsedArgument | undefined {
|
||||
if (command[start] !== "'") return undefined;
|
||||
const apostrophe = `'"'"'`;
|
||||
let value = '';
|
||||
for (let index = start + 1; index < command.length;) {
|
||||
if (command.startsWith(apostrophe, index)) {
|
||||
value += "'";
|
||||
index += apostrophe.length;
|
||||
continue;
|
||||
}
|
||||
if (command[index] === "'") return { value, next: index + 1 };
|
||||
value += command[index];
|
||||
index += 1;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function parsePosixCommand(command: string): readonly [string, string] | undefined {
|
||||
const executable = readPosixArgument(command, 0);
|
||||
if (!executable || command[executable.next] !== ' ') return undefined;
|
||||
const script = readPosixArgument(command, executable.next + 1);
|
||||
if (!script || script.next !== command.length) return undefined;
|
||||
return [executable.value, script.value];
|
||||
}
|
||||
|
||||
function readPowerShellArgument(command: string, start: number): ParsedArgument | undefined {
|
||||
if (command[start] !== "'") return undefined;
|
||||
let value = '';
|
||||
for (let index = start + 1; index < command.length; index += 1) {
|
||||
if (command[index] !== "'") {
|
||||
value += command[index];
|
||||
continue;
|
||||
}
|
||||
if (command[index + 1] === "'") {
|
||||
value += "'";
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
return { value, next: index + 1 };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function parsePowerShellCommand(command: string): readonly [string, string] | undefined {
|
||||
if (!command.startsWith('& ')) return undefined;
|
||||
const executable = readPowerShellArgument(command, 2);
|
||||
if (!executable || command[executable.next] !== ' ') return undefined;
|
||||
const script = readPowerShellArgument(command, executable.next + 1);
|
||||
if (!script || command.slice(script.next) !== '; exit $LASTEXITCODE') return undefined;
|
||||
return [executable.value, script.value];
|
||||
}
|
||||
|
||||
function parseLegacyCommand(command: string): readonly [string, string] | undefined {
|
||||
const match = /^(node(?:\.exe)?)\s+"([^"\r\n]+)"$/i.exec(command);
|
||||
return match ? [match[1], match[2]] : undefined;
|
||||
}
|
||||
|
||||
function isNodeExecutable(filePath: string): boolean {
|
||||
const basename = path.basename(filePath);
|
||||
return basename === 'node' || basename.toLowerCase() === 'node.exe';
|
||||
}
|
||||
|
||||
function managedScriptPath(handler: JsonObject): string | undefined {
|
||||
const keys = Object.keys(handler);
|
||||
if (keys.length === 3
|
||||
&& typeof handler.command === 'string'
|
||||
&& handler.timeout === HOOK_TIMEOUT_SECONDS
|
||||
&& handler.failClosed === true) {
|
||||
const parsed = process.platform === 'win32'
|
||||
? parsePowerShellCommand(handler.command)
|
||||
: parsePosixCommand(handler.command);
|
||||
if (parsed
|
||||
&& path.isAbsolute(parsed[0])
|
||||
&& path.isAbsolute(parsed[1])
|
||||
&& isNodeExecutable(parsed[0])) return parsed[1];
|
||||
}
|
||||
if (keys.length !== 1 || typeof handler.command !== 'string') return undefined;
|
||||
const legacy = parseLegacyCommand(handler.command);
|
||||
return legacy && isNodeExecutable(legacy[0]) && path.isAbsolute(legacy[1])
|
||||
? legacy[1]
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function managedAgentId(handler: JsonObject, scriptName: string): string | undefined {
|
||||
const scriptPath = managedScriptPath(handler);
|
||||
if (!scriptPath || path.basename(scriptPath) !== scriptName) return undefined;
|
||||
const agentDirectory = path.dirname(scriptPath);
|
||||
if (!samePath(path.dirname(agentDirectory), path.join(os.homedir(), '.elydora'))) {
|
||||
return undefined;
|
||||
}
|
||||
const agentId = path.basename(agentDirectory);
|
||||
return agentId && agentId !== '.' && agentId !== '..' ? agentId : undefined;
|
||||
}
|
||||
|
||||
function rejectDuplicateKeys(node: Node | undefined, label: string, location: string[] = []): void {
|
||||
if (!node) return;
|
||||
if (node.type === 'object') {
|
||||
const keys = new Set<string>();
|
||||
for (const property of node.children ?? []) {
|
||||
const key = String(property.children?.[0]?.value);
|
||||
const childLocation = [...location, key];
|
||||
if (keys.has(key)) {
|
||||
throw new Error(`${label} contains duplicate field "${childLocation.join('.')}"`);
|
||||
}
|
||||
keys.add(key);
|
||||
rejectDuplicateKeys(property.children?.[1], label, childLocation);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (node.type === 'array') {
|
||||
for (const child of node.children ?? []) rejectDuplicateKeys(child, label, location);
|
||||
}
|
||||
}
|
||||
|
||||
function parseJsonObject(raw: string, label: string): JsonObject {
|
||||
const errors: ParseError[] = [];
|
||||
const value: unknown = parse(raw, errors, {
|
||||
allowTrailingComma: false,
|
||||
disallowComments: true,
|
||||
});
|
||||
if (errors.length > 0) {
|
||||
const details = errors
|
||||
.map((error) => `${printParseErrorCode(error.error)} at offset ${error.offset}`)
|
||||
.join(', ');
|
||||
throw new Error(`Failed to parse ${label}: ${details}`);
|
||||
}
|
||||
if (!isObject(value)) throw new Error(`${label} must contain a JSON object`);
|
||||
rejectDuplicateKeys(parseTree(raw, [], {
|
||||
allowTrailingComma: false,
|
||||
disallowComments: true,
|
||||
}), label);
|
||||
return value;
|
||||
}
|
||||
|
||||
function readHooks(value: unknown, label: string): CursorHooks {
|
||||
if (value === undefined) return {};
|
||||
if (!isObject(value)) throw new Error(`${label} field "hooks" must be an object`);
|
||||
const hooks: CursorHooks = {};
|
||||
for (const [event, candidate] of Object.entries(value)) {
|
||||
if (!Array.isArray(candidate)) {
|
||||
throw new Error(`${label} field "hooks.${event}" must be an array`);
|
||||
}
|
||||
hooks[event] = candidate.map((handler, index) => {
|
||||
if (!isObject(handler)) {
|
||||
throw new Error(`${label} handler hooks.${event}[${index}] must be an object`);
|
||||
}
|
||||
return handler;
|
||||
});
|
||||
}
|
||||
return hooks;
|
||||
}
|
||||
|
||||
export function parseDocument(filePath: string, raw: string): CursorDocument {
|
||||
const label = `Cursor user hooks at ${filePath}`;
|
||||
const root = parseJsonObject(raw, label);
|
||||
if (root.version !== 1) throw new Error(`${label} must declare version 1`);
|
||||
return {
|
||||
exists: true,
|
||||
filePath,
|
||||
root,
|
||||
hooks: readHooks(root.hooks, label),
|
||||
raw,
|
||||
};
|
||||
}
|
||||
|
||||
export function createDocument(filePath: string): CursorDocument {
|
||||
return { exists: false, filePath, root: {}, hooks: {} };
|
||||
}
|
||||
|
||||
export function removeManagedHooks(hooks: CursorHooks, agentId?: string): CursorHooks {
|
||||
const next: CursorHooks = Object.fromEntries(
|
||||
Object.entries(hooks).map(([event, handlers]) => [event, [...handlers]]),
|
||||
);
|
||||
for (const [event, scriptName] of [
|
||||
['preToolUse', GUARD_SCRIPT],
|
||||
['postToolUse', AUDIT_SCRIPT],
|
||||
] as const) {
|
||||
const handlers = (next[event] ?? []).filter((handler) => {
|
||||
const managedId = managedAgentId(handler, scriptName);
|
||||
return !managedId || (agentId !== undefined && !sameAgentId(managedId, agentId));
|
||||
});
|
||||
if (handlers.length > 0) next[event] = handlers;
|
||||
else delete next[event];
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
function entirelyManaged(document: CursorDocument): boolean {
|
||||
if (!document.exists
|
||||
|| !Object.keys(document.root).every((key) => key === 'version' || key === 'hooks')) {
|
||||
return false;
|
||||
}
|
||||
const events = Object.entries(document.hooks);
|
||||
if (events.length === 0) return false;
|
||||
let handlerCount = 0;
|
||||
for (const [event, handlers] of events) {
|
||||
const scriptName = event === 'preToolUse'
|
||||
? GUARD_SCRIPT
|
||||
: event === 'postToolUse'
|
||||
? AUDIT_SCRIPT
|
||||
: undefined;
|
||||
if (!scriptName || handlers.length === 0) return false;
|
||||
handlerCount += handlers.length;
|
||||
if (handlers.some((handler) => !managedAgentId(handler, scriptName))) return false;
|
||||
}
|
||||
return handlerCount > 0;
|
||||
}
|
||||
|
||||
export function renderDocument(
|
||||
document: CursorDocument,
|
||||
hooks: CursorHooks,
|
||||
): RenderedDocument {
|
||||
if (!document.exists && Object.keys(hooks).length === 0) {
|
||||
return { document, changed: false };
|
||||
}
|
||||
if (Object.keys(hooks).length === 0 && entirelyManaged(document)) {
|
||||
return { document, changed: true };
|
||||
}
|
||||
const root: JsonObject = { ...document.root, version: 1 };
|
||||
if (Object.keys(hooks).length > 0) root.hooks = hooks;
|
||||
else delete root.hooks;
|
||||
const next = `${JSON.stringify(root, null, 2)}\n`;
|
||||
return { document, changed: next !== document.raw, next };
|
||||
}
|
||||
|
||||
function managedIds(handlers: JsonObject[], scriptName: string): Map<string, string> {
|
||||
const result = new Map<string, string>();
|
||||
for (const handler of handlers) {
|
||||
const agentId = managedAgentId(handler, scriptName);
|
||||
if (!agentId) continue;
|
||||
const key = process.platform === 'win32' ? agentId.toLowerCase() : agentId;
|
||||
result.set(key, agentId);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function runtimeContracts(hooks: CursorHooks): RuntimeContract[] {
|
||||
const guards = managedIds(hooks.preToolUse ?? [], GUARD_SCRIPT);
|
||||
const audits = managedIds(hooks.postToolUse ?? [], AUDIT_SCRIPT);
|
||||
const root = path.join(os.homedir(), '.elydora');
|
||||
return [...guards]
|
||||
.filter(([key]) => audits.has(key))
|
||||
.map(([, agentId]) => ({
|
||||
agentId,
|
||||
guardPath: path.join(root, agentId, GUARD_SCRIPT),
|
||||
auditPath: path.join(root, agentId, AUDIT_SCRIPT),
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import fsp from 'node:fs/promises';
|
||||
import type { FileHandle } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
AGENT_KEY,
|
||||
CONFIG_FILE,
|
||||
type CursorDocument,
|
||||
type JsonObject,
|
||||
type RenderedDocument,
|
||||
type RuntimeContract,
|
||||
createDocument,
|
||||
isObject,
|
||||
parseDocument,
|
||||
} from './cursor-contract.js';
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function asError(error: unknown): Error {
|
||||
return error instanceof Error ? error : new Error(String(error));
|
||||
}
|
||||
|
||||
function hasErrorCode(error: unknown, code: string): boolean {
|
||||
return isObject(error) && error.code === code;
|
||||
}
|
||||
|
||||
export function cursorConfigPath(): string {
|
||||
return path.join(os.homedir(), '.cursor', CONFIG_FILE);
|
||||
}
|
||||
|
||||
async function readOptionalPhysical(filePath: string, label: string): Promise<string | undefined> {
|
||||
let metadata;
|
||||
try {
|
||||
metadata = await fsp.lstat(filePath);
|
||||
} catch (error) {
|
||||
if (hasErrorCode(error, 'ENOENT') || hasErrorCode(error, 'ENOTDIR')) return undefined;
|
||||
throw new Error(`Inspect ${label} at ${filePath}: ${errorMessage(error)}`, {
|
||||
cause: asError(error),
|
||||
});
|
||||
}
|
||||
if (!metadata.isFile() || metadata.isSymbolicLink()) {
|
||||
throw new Error(`${label} path is not a physical file: ${filePath}`);
|
||||
}
|
||||
try {
|
||||
return await fsp.readFile(filePath, 'utf-8');
|
||||
} catch (error) {
|
||||
throw new Error(`Read ${label} at ${filePath}: ${errorMessage(error)}`, {
|
||||
cause: asError(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function readDocument(): Promise<CursorDocument> {
|
||||
const filePath = cursorConfigPath();
|
||||
const raw = await readOptionalPhysical(filePath, 'Cursor user hooks');
|
||||
return raw === undefined ? createDocument(filePath) : parseDocument(filePath, raw);
|
||||
}
|
||||
|
||||
async function ensurePhysicalDirectory(directory: string): Promise<void> {
|
||||
try {
|
||||
await fsp.mkdir(directory, { recursive: true, mode: 0o700 });
|
||||
} catch (error) {
|
||||
throw new Error(`Create Cursor hooks directory at ${directory}: ${errorMessage(error)}`, {
|
||||
cause: asError(error),
|
||||
});
|
||||
}
|
||||
let metadata;
|
||||
try {
|
||||
metadata = await fsp.lstat(directory);
|
||||
} catch (error) {
|
||||
throw new Error(`Inspect Cursor hooks directory at ${directory}: ${errorMessage(error)}`, {
|
||||
cause: asError(error),
|
||||
});
|
||||
}
|
||||
if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
|
||||
throw new Error(`Cursor hooks directory is not a physical directory: ${directory}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function unlinkOptional(filePath: string): Promise<void> {
|
||||
try {
|
||||
await fsp.unlink(filePath);
|
||||
} catch (error) {
|
||||
if (!hasErrorCode(error, 'ENOENT')) throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function writeExclusive(filePath: string, contents: string): Promise<void> {
|
||||
let handle: FileHandle | undefined;
|
||||
try {
|
||||
handle = await fsp.open(filePath, 'wx', 0o600);
|
||||
await handle.writeFile(contents, 'utf-8');
|
||||
await handle.sync();
|
||||
await handle.close();
|
||||
handle = undefined;
|
||||
} catch (error) {
|
||||
const failures = [asError(error)];
|
||||
if (handle) {
|
||||
try {
|
||||
await handle.close();
|
||||
} catch (closeError) {
|
||||
failures.push(asError(closeError));
|
||||
}
|
||||
}
|
||||
try {
|
||||
await unlinkOptional(filePath);
|
||||
} catch (cleanupError) {
|
||||
failures.push(asError(cleanupError));
|
||||
}
|
||||
if (failures.length > 1) {
|
||||
throw new AggregateError(failures, 'Stage Cursor user hooks');
|
||||
}
|
||||
throw new Error(`Stage Cursor user hooks: ${errorMessage(error)}`, { cause: failures[0] });
|
||||
}
|
||||
}
|
||||
|
||||
async function assertUnchanged(document: CursorDocument): Promise<void> {
|
||||
const current = await readOptionalPhysical(document.filePath, 'Cursor user hooks');
|
||||
if (current !== document.raw) {
|
||||
throw new Error(`Cursor user hooks changed during update: ${document.filePath}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeDocument(rendered: RenderedDocument): Promise<void> {
|
||||
if (!rendered.changed) return;
|
||||
await assertUnchanged(rendered.document);
|
||||
if (rendered.next === undefined) {
|
||||
try {
|
||||
await fsp.unlink(rendered.document.filePath);
|
||||
} catch (error) {
|
||||
if (!hasErrorCode(error, 'ENOENT')) {
|
||||
throw new Error(
|
||||
`Remove Cursor user hooks at ${rendered.document.filePath}: ${errorMessage(error)}`,
|
||||
{ cause: asError(error) },
|
||||
);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const directory = path.dirname(rendered.document.filePath);
|
||||
await ensurePhysicalDirectory(directory);
|
||||
const temporaryPath = path.join(
|
||||
directory,
|
||||
`.${path.basename(rendered.document.filePath)}.${randomUUID()}.tmp`,
|
||||
);
|
||||
let committed = false;
|
||||
let failure: Error | undefined;
|
||||
try {
|
||||
await writeExclusive(temporaryPath, rendered.next);
|
||||
await assertUnchanged(rendered.document);
|
||||
await fsp.rename(temporaryPath, rendered.document.filePath);
|
||||
committed = true;
|
||||
} catch (error) {
|
||||
failure = new Error(
|
||||
`Write Cursor user hooks at ${rendered.document.filePath}: ${errorMessage(error)}`,
|
||||
{ cause: asError(error) },
|
||||
);
|
||||
}
|
||||
let cleanupFailure: Error | undefined;
|
||||
if (!committed) {
|
||||
try {
|
||||
await unlinkOptional(temporaryPath);
|
||||
} catch (error) {
|
||||
cleanupFailure = new Error(
|
||||
`Clean Cursor hook staging file at ${temporaryPath}: ${errorMessage(error)}`,
|
||||
{ cause: asError(error) },
|
||||
);
|
||||
}
|
||||
}
|
||||
if (failure && cleanupFailure) {
|
||||
throw new AggregateError([failure, cleanupFailure], 'Write Cursor user hooks');
|
||||
}
|
||||
if (failure) throw failure;
|
||||
if (cleanupFailure) throw cleanupFailure;
|
||||
}
|
||||
|
||||
export async function physicalFileExists(filePath: string, label: string): Promise<boolean> {
|
||||
let metadata;
|
||||
try {
|
||||
metadata = await fsp.lstat(filePath);
|
||||
} catch (error) {
|
||||
if (hasErrorCode(error, 'ENOENT') || hasErrorCode(error, 'ENOTDIR')) return false;
|
||||
throw new Error(`Inspect ${label} at ${filePath}: ${errorMessage(error)}`, {
|
||||
cause: asError(error),
|
||||
});
|
||||
}
|
||||
if (!metadata.isFile() || metadata.isSymbolicLink()) {
|
||||
throw new Error(`${label} path is not a physical file: ${filePath}`);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function requireRuntime(filePath: string, label: string): Promise<void> {
|
||||
if (!filePath) throw new Error(`${label} path is required`);
|
||||
if (!await physicalFileExists(filePath, label)) {
|
||||
throw new Error(`${label} is missing: ${filePath}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function readRuntimeConfig(filePath: string): Promise<JsonObject | undefined> {
|
||||
const raw = await readOptionalPhysical(filePath, 'Elydora runtime config');
|
||||
if (raw === undefined) return undefined;
|
||||
let value: unknown;
|
||||
try {
|
||||
value = JSON.parse(raw);
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to parse Elydora runtime config at ${filePath}: ${errorMessage(error)}`, {
|
||||
cause: asError(error),
|
||||
});
|
||||
}
|
||||
if (!isObject(value)) {
|
||||
throw new Error(`Elydora runtime config at ${filePath} must contain a JSON object`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function sameAgentId(left: unknown, right: string): boolean {
|
||||
if (typeof left !== 'string') return false;
|
||||
return process.platform === 'win32'
|
||||
? left.toLowerCase() === right.toLowerCase()
|
||||
: left === right;
|
||||
}
|
||||
|
||||
export async function runtimeFilesExist(contracts: RuntimeContract[]): Promise<boolean> {
|
||||
for (const contract of contracts) {
|
||||
const runtimeConfig = await readRuntimeConfig(
|
||||
path.join(path.dirname(contract.guardPath), 'config.json'),
|
||||
);
|
||||
if (!runtimeConfig
|
||||
|| runtimeConfig.agent_name !== AGENT_KEY
|
||||
|| !sameAgentId(runtimeConfig.agent_id, contract.agentId)) continue;
|
||||
const files = await Promise.all([
|
||||
physicalFileExists(contract.guardPath, 'Elydora guard runtime'),
|
||||
physicalFileExists(contract.auditPath, 'Elydora audit runtime'),
|
||||
]);
|
||||
if (files.every(Boolean)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
+43
-125
@@ -1,151 +1,69 @@
|
||||
import fsp from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { resolvePrivateChildDirectory } from '../runtime-paths.js';
|
||||
import type { AgentPlugin, InstallConfig, PluginStatus } from './base.js';
|
||||
import {
|
||||
AGENT_KEY,
|
||||
AUDIT_SCRIPT,
|
||||
GUARD_SCRIPT,
|
||||
buildHandler,
|
||||
removeManagedHooks,
|
||||
renderDocument,
|
||||
runtimeContracts,
|
||||
samePath,
|
||||
} from './cursor-contract.js';
|
||||
import {
|
||||
readDocument,
|
||||
requireRuntime,
|
||||
runtimeFilesExist,
|
||||
writeDocument,
|
||||
} from './cursor-io.js';
|
||||
import { SUPPORTED_AGENTS } from './registry.js';
|
||||
|
||||
const AGENT_KEY = 'cursor';
|
||||
const entry = SUPPORTED_AGENTS.get(AGENT_KEY)!;
|
||||
|
||||
function resolveConfigDir(): string {
|
||||
// .cursor is project-relative, but for global install use home dir
|
||||
return path.join(os.homedir(), entry.configDir);
|
||||
}
|
||||
|
||||
function resolveConfigPath(): string {
|
||||
return path.join(resolveConfigDir(), entry.configFile);
|
||||
}
|
||||
|
||||
function buildHookCommand(scriptPath: string): string {
|
||||
return `node "${scriptPath}"`;
|
||||
}
|
||||
|
||||
function isElydoraCommand(cmd: string, agentId?: string): boolean {
|
||||
if (!cmd.includes('elydora')) return false;
|
||||
if (agentId) {
|
||||
return cmd.includes(agentId);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function filterElydoraEntries(arr: Array<Record<string, unknown>>, agentId?: string): Array<Record<string, unknown>> {
|
||||
return arr.filter(
|
||||
(h) => typeof h.command === 'string' && !isElydoraCommand(h.command, agentId),
|
||||
);
|
||||
}
|
||||
|
||||
export const cursorPlugin: AgentPlugin = {
|
||||
async install(config: InstallConfig): Promise<void> {
|
||||
const configDir = resolveConfigDir();
|
||||
await fsp.mkdir(configDir, { recursive: true });
|
||||
|
||||
const configPath = resolveConfigPath();
|
||||
let settings: Record<string, unknown> = {};
|
||||
|
||||
try {
|
||||
const raw = await fsp.readFile(configPath, 'utf-8');
|
||||
settings = JSON.parse(raw);
|
||||
} catch {
|
||||
// Start fresh
|
||||
if (!config.agentId) throw new Error('agentId is required');
|
||||
const document = await readDocument();
|
||||
const runtimeRoot = path.join(os.homedir(), '.elydora');
|
||||
const agentDirectory = resolvePrivateChildDirectory(runtimeRoot, config.agentId);
|
||||
const expectedGuard = path.join(agentDirectory, GUARD_SCRIPT);
|
||||
const expectedAudit = path.join(agentDirectory, AUDIT_SCRIPT);
|
||||
if (!samePath(config.guardScriptPath, expectedGuard)) {
|
||||
throw new Error(`Elydora guard runtime must use the managed agent directory: ${expectedGuard}`);
|
||||
}
|
||||
|
||||
if (!settings.hooks || typeof settings.hooks !== 'object') {
|
||||
settings.hooks = {};
|
||||
if (!samePath(config.hookScriptPath, expectedAudit)) {
|
||||
throw new Error(`Elydora audit runtime must use the managed agent directory: ${expectedAudit}`);
|
||||
}
|
||||
const hooks = settings.hooks as Record<string, unknown>;
|
||||
await requireRuntime(expectedGuard, 'Elydora guard runtime');
|
||||
await requireRuntime(expectedAudit, 'Elydora audit runtime');
|
||||
|
||||
// --- preToolUse (guard — freeze enforcement) ---
|
||||
if (!Array.isArray(hooks.preToolUse)) {
|
||||
hooks.preToolUse = [];
|
||||
}
|
||||
const preFiltered = filterElydoraEntries(hooks.preToolUse as Array<Record<string, unknown>>);
|
||||
preFiltered.push({ command: buildHookCommand(config.guardScriptPath) });
|
||||
hooks.preToolUse = preFiltered;
|
||||
|
||||
// --- postToolUse (audit logging) ---
|
||||
if (!Array.isArray(hooks.postToolUse)) {
|
||||
hooks.postToolUse = [];
|
||||
}
|
||||
const postFiltered = filterElydoraEntries(hooks.postToolUse as Array<Record<string, unknown>>);
|
||||
postFiltered.push({ command: buildHookCommand(config.hookScriptPath) });
|
||||
hooks.postToolUse = postFiltered;
|
||||
|
||||
settings.hooks = hooks;
|
||||
settings.version = 1;
|
||||
await fsp.writeFile(configPath, JSON.stringify(settings, null, 2) + '\n', 'utf-8');
|
||||
const hooks = removeManagedHooks(document.hooks);
|
||||
hooks.preToolUse = [...(hooks.preToolUse ?? []), buildHandler(expectedGuard)];
|
||||
hooks.postToolUse = [...(hooks.postToolUse ?? []), buildHandler(expectedAudit)];
|
||||
await writeDocument(renderDocument(document, hooks));
|
||||
console.log(` Cursor hooks: ${document.filePath}`);
|
||||
},
|
||||
|
||||
async uninstall(agentId?: string): Promise<void> {
|
||||
const configPath = resolveConfigPath();
|
||||
|
||||
let settings: Record<string, unknown>;
|
||||
try {
|
||||
const raw = await fsp.readFile(configPath, 'utf-8');
|
||||
settings = JSON.parse(raw);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
const hooks = settings.hooks as Record<string, unknown> | undefined;
|
||||
if (!hooks) return;
|
||||
|
||||
if (Array.isArray(hooks.preToolUse)) {
|
||||
hooks.preToolUse = filterElydoraEntries(hooks.preToolUse as Array<Record<string, unknown>>, agentId);
|
||||
}
|
||||
if (Array.isArray(hooks.postToolUse)) {
|
||||
hooks.postToolUse = filterElydoraEntries(hooks.postToolUse as Array<Record<string, unknown>>, agentId);
|
||||
}
|
||||
|
||||
await fsp.writeFile(configPath, JSON.stringify(settings, null, 2) + '\n', 'utf-8');
|
||||
const document = await readDocument();
|
||||
const hooks = removeManagedHooks(document.hooks, agentId);
|
||||
await writeDocument(renderDocument(document, hooks));
|
||||
},
|
||||
|
||||
async status(): Promise<PluginStatus> {
|
||||
const configPath = resolveConfigPath();
|
||||
|
||||
let hookConfigured = false;
|
||||
let hookScriptPath = '';
|
||||
try {
|
||||
const raw = await fsp.readFile(configPath, 'utf-8');
|
||||
const settings = JSON.parse(raw);
|
||||
const hooks = settings.hooks as Record<string, unknown> | undefined;
|
||||
if (hooks) {
|
||||
const check = (arr: unknown) =>
|
||||
Array.isArray(arr) && (arr as Array<Record<string, unknown>>).some(
|
||||
(h) => typeof h.command === 'string' && h.command.includes('elydora'),
|
||||
);
|
||||
hookConfigured = check(hooks.preToolUse) && check(hooks.postToolUse);
|
||||
|
||||
// Extract hook script path from postToolUse command
|
||||
if (hookConfigured && Array.isArray(hooks.postToolUse)) {
|
||||
for (const h of hooks.postToolUse as Array<Record<string, unknown>>) {
|
||||
const cmd = h.command as string;
|
||||
if (cmd && cmd.includes('elydora')) {
|
||||
hookScriptPath = cmd.replace(/^node\s+"?/, '').replace(/"?\s*$/, '');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Config not readable
|
||||
}
|
||||
|
||||
let hookScriptExists = false;
|
||||
if (hookScriptPath) {
|
||||
try {
|
||||
await fsp.access(hookScriptPath);
|
||||
hookScriptExists = true;
|
||||
} catch {
|
||||
// File doesn't exist
|
||||
}
|
||||
}
|
||||
|
||||
const document = await readDocument();
|
||||
const contracts = runtimeContracts(document.hooks);
|
||||
const hookConfigured = contracts.length > 0;
|
||||
const hookScriptExists = hookConfigured && await runtimeFilesExist(contracts);
|
||||
return {
|
||||
installed: hookConfigured && hookScriptExists,
|
||||
agentName: AGENT_KEY,
|
||||
displayName: entry.name,
|
||||
hookConfigured,
|
||||
hookScriptExists,
|
||||
configPath,
|
||||
configPath: document.filePath,
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -7,7 +7,7 @@ export interface AgentRegistryEntry {
|
||||
export const SUPPORTED_AGENTS: ReadonlyMap<string, AgentRegistryEntry> = new Map([
|
||||
['augment', { name: 'Augment Code CLI', configDir: '~/.augment', configFile: 'settings.json' }],
|
||||
['claudecode', { name: 'Claude Code', configDir: '~/.claude', configFile: 'settings.json' }],
|
||||
['cursor', { name: 'Cursor', configDir: '.cursor', configFile: 'hooks.json' }],
|
||||
['cursor', { name: 'Cursor', configDir: '~/.cursor', configFile: 'hooks.json' }],
|
||||
['gemini', { name: 'Gemini CLI', configDir: '~/.gemini', configFile: 'settings.json' }],
|
||||
['kirocli', { name: 'Kiro CLI', configDir: '~/.kiro/hooks', configFile: 'elydora-audit.json' }],
|
||||
['kiroide', { name: 'Kiro IDE', configDir: '.kiro/hooks', configFile: 'elydora-audit.kiro.hook' }],
|
||||
|
||||
Reference in new issue
Block a user