4 Commits
Author SHA1 Message Date
雷电芽衣 db4a6ffb62 chore(node-sdk): audit providers copilot droid augment cline
Providers use plugins/common.ts, shell-command.ts, and managed-runtime-status; isNodeExecutable recognizes the running executable or a node-named binary.

Claude-Session: https://claude.ai/code/session_01Agoc9bRVE9KL7mmWtey9Vq
2026-09-02 22:00:34 -04:00
雷电芽衣 81ecb372ba chore(node-sdk): audit providers claudecode codex cursor gemini
Add plugins/shell-command.ts for the shared quoting and command parsers; runtime status checks go through managed-runtime-status; Codex and Cursor write through managed-transaction.

Claude-Session: https://claude.ai/code/session_01Agoc9bRVE9KL7mmWtey9Vq
2026-09-02 21:41:26 -04:00
雷电芽衣 b7f14ba34b chore(node-sdk): audit plugins shared
Add plugins/common.ts for the helpers and size limits copied across plugin files; managed-transaction compares snapshots in one place; guard template imported directly.

Claude-Session: https://claude.ai/code/session_01Agoc9bRVE9KL7mmWtey9Vq
2026-09-02 21:23:57 -04:00
雷电芽衣 07f32a48d7 chore(node-sdk): audit src core
Align response types with the Backend (webhooks, me, health, operation payload, error codes, admin actions), shorten comments, drop section banners.

Claude-Session: https://claude.ai/code/session_01Agoc9bRVE9KL7mmWtey9Vq
2026-09-02 21:19:01 -04:00
41 changed files with 468 additions and 1920 deletions

No files matched your search

+2 -19
View File
@@ -13,7 +13,8 @@ import {
import { writePrivateFile } from './secure-files.js'; import { writePrivateFile } from './secure-files.js';
import { SUPPORTED_AGENTS } from './plugins/registry.js'; import { SUPPORTED_AGENTS } from './plugins/registry.js';
import type { AgentPlugin, InstallConfig } from './plugins/base.js'; import type { AgentPlugin, InstallConfig } from './plugins/base.js';
import { generateHookScript, generateGuardScript } from './plugins/hook-template.js'; import { generateGuardScript } from './plugins/guard-template.js';
import { generateHookScript } from './plugins/hook-template.js';
import { augmentPlugin } from './plugins/augment.js'; import { augmentPlugin } from './plugins/augment.js';
import { claudecodePlugin } from './plugins/claudecode.js'; import { claudecodePlugin } from './plugins/claudecode.js';
import { cursorPlugin } from './plugins/cursor.js'; import { cursorPlugin } from './plugins/cursor.js';
@@ -50,10 +51,6 @@ const PLUGINS: ReadonlyMap<string, AgentPlugin> = new Map([
['qwen', qwenPlugin], ['qwen', qwenPlugin],
]); ]);
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function die(message: string): never { function die(message: string): never {
console.error(`Error: ${message}`); console.error(`Error: ${message}`);
process.exit(1); process.exit(1);
@@ -137,10 +134,6 @@ Supported agents: ${Array.from(SUPPORTED_AGENTS.keys()).join(', ')}
`); `);
} }
// ---------------------------------------------------------------------------
// Commands
// ---------------------------------------------------------------------------
async function cmdInstall(args: string[]): Promise<void> { async function cmdInstall(args: string[]): Promise<void> {
const { values } = parseArgs({ const { values } = parseArgs({
args, args,
@@ -178,7 +171,6 @@ async function cmdInstall(args: string[]): Promise<void> {
}); });
const baseUrl = values.base_url ?? 'https://api.elydora.com'; const baseUrl = values.base_url ?? 'https://api.elydora.com';
// Validate private key by deriving public key
let publicKey: string; let publicKey: string;
try { try {
publicKey = derivePublicKey(privateKey); publicKey = derivePublicKey(privateKey);
@@ -255,7 +247,6 @@ async function cmdUninstall(args: string[]): Promise<void> {
let agentDir: string; let agentDir: string;
let agentDirectoryExists: boolean; let agentDirectoryExists: boolean;
// If --agent_id not provided, scan ~/.elydora/*/config.json for matching agent_name
if (agentId) { if (agentId) {
agentDir = resolvePrivateChildDirectory(ELYDORA_DIR, agentId); agentDir = resolvePrivateChildDirectory(ELYDORA_DIR, agentId);
const runtimeRootExists = await requirePhysicalDirectory(ELYDORA_DIR); const runtimeRootExists = await requirePhysicalDirectory(ELYDORA_DIR);
@@ -287,10 +278,8 @@ async function cmdUninstall(args: string[]): Promise<void> {
const plugin = PLUGINS.get(agentName)!; const plugin = PLUGINS.get(agentName)!;
const registryEntry = SUPPORTED_AGENTS.get(agentName)!; const registryEntry = SUPPORTED_AGENTS.get(agentName)!;
// Uninstall agent-specific config
await plugin.uninstall(agentId); await plugin.uninstall(agentId);
// Remove entire agent directory
if (agentDirectoryExists) { if (agentDirectoryExists) {
await fsp.rm(agentDir, { recursive: true }); await fsp.rm(agentDir, { recursive: true });
} }
@@ -303,14 +292,12 @@ async function cmdStatus(): Promise<void> {
let anyInstalled = false; let anyInstalled = false;
// Scan ~/.elydora/*/config.json to discover installed agents
const installedAgents = await discoverInstalledAgents(); const installedAgents = await discoverInstalledAgents();
for (const [name, plugin] of PLUGINS) { for (const [name, plugin] of PLUGINS) {
const st = await plugin.status(); const st = await plugin.status();
const statusIcon = st.installed ? '[installed]' : '[not installed]'; const statusIcon = st.installed ? '[installed]' : '[not installed]';
// Find matching installed agent(s) for this plugin
const matching = installedAgents.filter((a) => a.agentName === name); const matching = installedAgents.filter((a) => a.agentName === name);
console.log(` ${st.displayName} (${name}) ${statusIcon}`); console.log(` ${st.displayName} (${name}) ${statusIcon}`);
@@ -339,10 +326,6 @@ function cmdAgents(): void {
console.log('\nUse "elydora install --agent <name>" to install an audit hook.'); console.log('\nUse "elydora install --agent <name>" to install an audit hook.');
} }
// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------
async function main(): Promise<void> { async function main(): Promise<void> {
const args = process.argv.slice(2); const args = process.argv.slice(2);
+4 -91
View File
@@ -74,34 +74,19 @@ export class ElydoraClient {
this.prevChainHash = ZERO_CHAIN_HASH; this.prevChainHash = ZERO_CHAIN_HASH;
} }
/**
* Set the API token used for authenticated API calls.
*/
setToken(token: string): void { setToken(token: string): void {
this.token = token; this.token = token;
} }
/**
* Get the current chain hash (useful for debugging/inspection).
*/
getChainHash(): string { getChainHash(): string {
return this.prevChainHash; return this.prevChainHash;
} }
/**
* Get the public key derived from the configured private key.
*/
getPublicKey(): string { getPublicKey(): string {
return derivePublicKey(this.privateKey); return derivePublicKey(this.privateKey);
} }
// ------------------------------------------------------------------------- /** @deprecated Password auth for the SDK CLI path; Console users sign in through Better Auth. */
// Auth (static methods — no instance needed)
// -------------------------------------------------------------------------
/**
* @deprecated Use Better Auth endpoints directly. See docs.
*/
static async register( static async register(
baseUrl: string, baseUrl: string,
email: string, email: string,
@@ -123,9 +108,7 @@ export class ElydoraClient {
return handleResponse<AuthRegisterResponse>(res); return handleResponse<AuthRegisterResponse>(res);
} }
/** /** @deprecated Password auth for the SDK CLI path; Console users sign in through Better Auth. */
* @deprecated Use Better Auth endpoints directly. See docs.
*/
static async login( static async login(
baseUrl: string, baseUrl: string,
email: string, email: string,
@@ -141,10 +124,6 @@ export class ElydoraClient {
return handleResponse<AuthLoginResponse>(res); return handleResponse<AuthLoginResponse>(res);
} }
// -------------------------------------------------------------------------
// Auth (instance methods — require token)
// -------------------------------------------------------------------------
async getMe(): Promise<GetMeResponse> { async getMe(): Promise<GetMeResponse> {
return this.request<GetMeResponse>('GET', '/v1/auth/me'); return this.request<GetMeResponse>('GET', '/v1/auth/me');
} }
@@ -157,10 +136,6 @@ export class ElydoraClient {
return this.request<RotateApiTokenResponse>('POST', '/v1/auth/rotate', {}); return this.request<RotateApiTokenResponse>('POST', '/v1/auth/rotate', {});
} }
// -------------------------------------------------------------------------
// Agent management
// -------------------------------------------------------------------------
async registerAgent(request: RegisterAgentRequest): Promise<RegisterAgentResponse> { async registerAgent(request: RegisterAgentRequest): Promise<RegisterAgentResponse> {
assertIntegrationType(request?.integration_type); assertIntegrationType(request?.integration_type);
return this.request<RegisterAgentResponse>('POST', '/v1/agents/register', request); return this.request<RegisterAgentResponse>('POST', '/v1/agents/register', request);
@@ -195,31 +170,15 @@ export class ElydoraClient {
await this.request<unknown>('POST', `/v1/agents/${encodeURIComponent(agentId)}/revoke`, { kid, reason }); await this.request<unknown>('POST', `/v1/agents/${encodeURIComponent(agentId)}/revoke`, { kid, reason });
} }
// ------------------------------------------------------------------------- // Builds, hashes, chains, and signs an EOR locally, then advances prev_chain_hash.
// Operations (core)
// -------------------------------------------------------------------------
/**
* Construct and sign an Elydora Operation Record (EOR) locally.
*
* 1. Generate UUIDv7 for operation_id
* 2. Generate random nonce (16 bytes, base64url)
* 3. Compute payload_hash (SHA-256 of JCS-canonicalized payload)
* 4. Compute chain_hash from prev_chain_hash
* 5. Construct canonical EOR (minus signature)
* 6. Sign JCS-canonicalized EOR with Ed25519
* 7. Update internal prev_chain_hash
*/
createOperation(params: CreateOperationParams): EOR { createOperation(params: CreateOperationParams): EOR {
const operationId = uuidv7(); const operationId = uuidv7();
const issuedAt = Date.now(); const issuedAt = Date.now();
const nonce = generateNonce(); const nonce = generateNonce();
const payload = params.payload ?? null; const payload = params.payload ?? null;
// Compute payload hash
const payloadHash = computePayloadHash(payload); const payloadHash = computePayloadHash(payload);
// Compute chain hash
const chainHash = computeChainHash( const chainHash = computeChainHash(
this.prevChainHash, this.prevChainHash,
payloadHash, payloadHash,
@@ -227,7 +186,6 @@ export class ElydoraClient {
issuedAt, issuedAt,
); );
// Construct the EOR without signature for signing
const eorWithoutSig: Omit<EOR, 'signature'> = { const eorWithoutSig: Omit<EOR, 'signature'> = {
op_version: '1.0', op_version: '1.0',
operation_id: operationId, operation_id: operationId,
@@ -245,11 +203,9 @@ export class ElydoraClient {
agent_pubkey_kid: this.kid, agent_pubkey_kid: this.kid,
}; };
// Sign the JCS-canonicalized EOR (without signature field)
const canonical = jcsCanonicalise(eorWithoutSig); const canonical = jcsCanonicalise(eorWithoutSig);
const signature = signEd25519(this.privateKey, Buffer.from(canonical, 'utf-8')); const signature = signEd25519(this.privateKey, Buffer.from(canonical, 'utf-8'));
// Update internal chain state
this.prevChainHash = chainHash; this.prevChainHash = chainHash;
return { return {
@@ -270,18 +226,10 @@ export class ElydoraClient {
return this.request<VerifyOperationResponse>('POST', `/v1/operations/${encodeURIComponent(operationId)}/verify`, {}); return this.request<VerifyOperationResponse>('POST', `/v1/operations/${encodeURIComponent(operationId)}/verify`, {});
} }
// -------------------------------------------------------------------------
// Audit
// -------------------------------------------------------------------------
async queryAudit(params: AuditQueryRequest): Promise<AuditQueryResponse> { async queryAudit(params: AuditQueryRequest): Promise<AuditQueryResponse> {
return this.request<AuditQueryResponse>('POST', '/v1/audit/query', params); return this.request<AuditQueryResponse>('POST', '/v1/audit/query', params);
} }
// -------------------------------------------------------------------------
// Epochs
// -------------------------------------------------------------------------
async listEpochs(): Promise<ListEpochsResponse> { async listEpochs(): Promise<ListEpochsResponse> {
return this.request<ListEpochsResponse>('GET', '/v1/epochs'); return this.request<ListEpochsResponse>('GET', '/v1/epochs');
} }
@@ -290,10 +238,6 @@ export class ElydoraClient {
return this.request<GetEpochResponse>('GET', `/v1/epochs/${encodeURIComponent(epochId)}`); return this.request<GetEpochResponse>('GET', `/v1/epochs/${encodeURIComponent(epochId)}`);
} }
// -------------------------------------------------------------------------
// Exports
// -------------------------------------------------------------------------
async createExport(params: CreateExportRequest): Promise<CreateExportResponse> { async createExport(params: CreateExportRequest): Promise<CreateExportResponse> {
return this.request<CreateExportResponse>('POST', '/v1/exports', params); return this.request<CreateExportResponse>('POST', '/v1/exports', params);
} }
@@ -323,10 +267,6 @@ export class ElydoraClient {
return res.arrayBuffer(); return res.arrayBuffer();
} }
// -------------------------------------------------------------------------
// JWKS
// -------------------------------------------------------------------------
async getJWKS(): Promise<JWKSResponse> { async getJWKS(): Promise<JWKSResponse> {
const url = `${this.baseUrl}/.well-known/elydora/jwks.json`; const url = `${this.baseUrl}/.well-known/elydora/jwks.json`;
const res = await fetch(url, { const res = await fetch(url, {
@@ -336,10 +276,6 @@ export class ElydoraClient {
return handleResponse<JWKSResponse>(res); return handleResponse<JWKSResponse>(res);
} }
// -------------------------------------------------------------------------
// Health
// -------------------------------------------------------------------------
async health(): Promise<HealthResponse> { async health(): Promise<HealthResponse> {
const url = `${this.baseUrl}/v1/health`; const url = `${this.baseUrl}/v1/health`;
const res = await fetch(url, { const res = await fetch(url, {
@@ -355,10 +291,6 @@ export class ElydoraClient {
return handleResponse<DeepHealthResponse>(res); return handleResponse<DeepHealthResponse>(res);
} }
// -------------------------------------------------------------------------
// Webhooks
// -------------------------------------------------------------------------
async listWebhooks(): Promise<ListWebhooksResponse> { async listWebhooks(): Promise<ListWebhooksResponse> {
return this.request<ListWebhooksResponse>('GET', '/v1/webhooks'); return this.request<ListWebhooksResponse>('GET', '/v1/webhooks');
} }
@@ -371,27 +303,15 @@ export class ElydoraClient {
await this.request<unknown>('DELETE', `/v1/webhooks/${encodeURIComponent(webhookId)}`); await this.request<unknown>('DELETE', `/v1/webhooks/${encodeURIComponent(webhookId)}`);
} }
// -------------------------------------------------------------------------
// Members
// -------------------------------------------------------------------------
async listMembers(): Promise<ListMembersResponse> { async listMembers(): Promise<ListMembersResponse> {
return this.request<ListMembersResponse>('GET', '/v1/members'); return this.request<ListMembersResponse>('GET', '/v1/members');
} }
// -------------------------------------------------------------------------
// Admin events
// -------------------------------------------------------------------------
async listAdminEvents(limit?: number): Promise<ListAdminEventsResponse> { async listAdminEvents(limit?: number): Promise<ListAdminEventsResponse> {
const query = limit ? `?limit=${limit}` : ''; const query = limit ? `?limit=${limit}` : '';
return this.request<ListAdminEventsResponse>('GET', `/v1/admin/events${query}`); return this.request<ListAdminEventsResponse>('GET', `/v1/admin/events${query}`);
} }
// -------------------------------------------------------------------------
// Internal HTTP helpers
// -------------------------------------------------------------------------
private async request<T>( private async request<T>(
method: string, method: string,
path: string, path: string,
@@ -420,7 +340,6 @@ export class ElydoraClient {
body: body !== undefined ? JSON.stringify(body) : undefined, body: body !== undefined ? JSON.stringify(body) : undefined,
}); });
// Only retry on 429 or 5xx
if (attempt < this.maxRetries && (res.status === 429 || res.status >= 500)) { if (attempt < this.maxRetries && (res.status === 429 || res.status >= 500)) {
const retryAfter = res.headers.get('Retry-After'); const retryAfter = res.headers.get('Retry-After');
const delayMs = retryAfter const delayMs = retryAfter
@@ -434,7 +353,6 @@ export class ElydoraClient {
} catch (err) { } catch (err) {
lastError = err instanceof Error ? err : new Error(String(err)); lastError = err instanceof Error ? err : new Error(String(err));
// Only retry on network errors, not API errors
if (err instanceof ElydoraError) { if (err instanceof ElydoraError) {
throw err; throw err;
} }
@@ -450,13 +368,8 @@ export class ElydoraClient {
} }
} }
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
async function handleResponse<T>(res: Response): Promise<T> { async function handleResponse<T>(res: Response): Promise<T> {
if (res.ok) { if (res.ok) {
// 204 No Content
if (res.status === 204) { if (res.status === 204) {
return undefined as T; return undefined as T;
} }
@@ -467,7 +380,7 @@ async function handleResponse<T>(res: Response): Promise<T> {
try { try {
errorBody = (await res.json()) as ErrorResponse; errorBody = (await res.json()) as ErrorResponse;
} catch { } catch {
// Response body was not valid JSON // non-JSON error body: fall through to the status-only error
} }
if (errorBody?.error) { if (errorBody?.error) {
+6 -70
View File
@@ -1,18 +1,7 @@
import crypto from 'node:crypto'; import crypto from 'node:crypto';
import { base64urlEncode } from './utils.js'; import { base64urlEncode } from './utils.js';
// --------------------------------------------------------------------------- // RFC 8785 JSON Canonicalization Scheme
// JCS Canonicalization (RFC 8785)
// ---------------------------------------------------------------------------
/**
* Canonicalize a JSON value according to JCS (RFC 8785).
*
* - Object keys sorted lexicographically by UTF-16 code units
* - No whitespace
* - Numbers serialized using ES2015 Number serialization
* - Strings serialized with minimal escaping per JSON spec
*/
export function jcsCanonicalise(value: unknown): string { export function jcsCanonicalise(value: unknown): string {
if (value === null || value === undefined) { if (value === null || value === undefined) {
return 'null'; return 'null';
@@ -46,30 +35,13 @@ export function jcsCanonicalise(value: unknown): string {
return JSON.stringify(value); return JSON.stringify(value);
} }
// ---------------------------------------------------------------------------
// SHA-256
// ---------------------------------------------------------------------------
/**
* Compute SHA-256 of a UTF-8 string or buffer and return base64url.
*/
export function sha256Base64url(data: string | Buffer): string { export function sha256Base64url(data: string | Buffer): string {
const input = typeof data === 'string' ? Buffer.from(data, 'utf-8') : data; const input = typeof data === 'string' ? Buffer.from(data, 'utf-8') : data;
const hash = crypto.createHash('sha256').update(input).digest(); const hash = crypto.createHash('sha256').update(input).digest();
return base64urlEncode(hash); return base64urlEncode(hash);
} }
// --------------------------------------------------------------------------- // chain_hash = SHA-256("prev|payload_hash|operation_id|issued_at")
// Chain hash computation
// ---------------------------------------------------------------------------
/**
* Compute the chain hash for an operation.
*
* chain_hash = SHA-256(prev_chain_hash + "|" + payload_hash + "|" + operation_id + "|" + issued_at)
*
* All inputs concatenated as UTF-8 strings separated by '|'.
*/
export function computeChainHash( export function computeChainHash(
prevChainHash: string, prevChainHash: string,
payloadHash: string, payloadHash: string,
@@ -80,13 +52,6 @@ export function computeChainHash(
return sha256Base64url(input); return sha256Base64url(input);
} }
// ---------------------------------------------------------------------------
// Payload hash
// ---------------------------------------------------------------------------
/**
* Compute SHA-256 hash of JCS-canonicalized payload, returned as base64url.
*/
export function computePayloadHash( export function computePayloadHash(
payload: Record<string, unknown> | string | null, payload: Record<string, unknown> | string | null,
): string { ): string {
@@ -94,23 +59,11 @@ export function computePayloadHash(
return sha256Base64url(canonical); return sha256Base64url(canonical);
} }
// --------------------------------------------------------------------------- // PKCS8 envelope: SEQUENCE { INTEGER 0, SEQUENCE { OID 1.3.101.112 }, OCTET STRING { OCTET STRING seed } }
// Ed25519 signing
// ---------------------------------------------------------------------------
// PKCS8 prefix for wrapping a 32-byte Ed25519 seed
const PKCS8_ED25519_PREFIX = Buffer.from([ const PKCS8_ED25519_PREFIX = Buffer.from([
0x30, 0x2e, // SEQUENCE (46 bytes) 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20,
0x02, 0x01, 0x00, // INTEGER 0
0x30, 0x05, // SEQUENCE (5 bytes)
0x06, 0x03, 0x2b, 0x65, 0x70, // OID 1.3.101.112 (Ed25519)
0x04, 0x22, // OCTET STRING (34 bytes)
0x04, 0x20, // OCTET STRING (32 bytes)
]); ]);
/**
* Import a base64url-encoded 32-byte Ed25519 seed as a Node.js KeyObject.
*/
function importPrivateKey(privateKeyBase64url: string): crypto.KeyObject { function importPrivateKey(privateKeyBase64url: string): crypto.KeyObject {
const seed = Buffer.from(privateKeyBase64url, 'base64url'); const seed = Buffer.from(privateKeyBase64url, 'base64url');
const pkcs8 = Buffer.concat([PKCS8_ED25519_PREFIX, seed]); const pkcs8 = Buffer.concat([PKCS8_ED25519_PREFIX, seed]);
@@ -121,37 +74,20 @@ function importPrivateKey(privateKeyBase64url: string): crypto.KeyObject {
}); });
} }
/**
* Sign data with Ed25519 using a base64url-encoded 32-byte seed.
*
* @returns base64url-encoded 64-byte signature
*/
export function signEd25519(privateKeyBase64url: string, data: Buffer): string { export function signEd25519(privateKeyBase64url: string, data: Buffer): string {
const keyObject = importPrivateKey(privateKeyBase64url); const keyObject = importPrivateKey(privateKeyBase64url);
const signature = crypto.sign(null, data, keyObject); const signature = crypto.sign(null, data, keyObject);
return base64urlEncode(signature); return base64urlEncode(signature);
} }
/**
* Derive the Ed25519 public key from a base64url-encoded 32-byte seed.
*
* @returns base64url-encoded 32-byte public key
*/
export function derivePublicKey(privateKeyBase64url: string): string { export function derivePublicKey(privateKeyBase64url: string): string {
const keyObject = importPrivateKey(privateKeyBase64url); const keyObject = importPrivateKey(privateKeyBase64url);
const publicKeyObject = crypto.createPublicKey(keyObject); const publicKeyObject = crypto.createPublicKey(keyObject);
const rawPublicKey = publicKeyObject.export({ type: 'spki', format: 'der' }); const rawPublicKey = publicKeyObject.export({ type: 'spki', format: 'der' });
// The raw 32-byte public key is the last 32 bytes of the SPKI DER encoding // The raw key is the last 32 bytes of the SPKI DER encoding.
const publicKeyBytes = rawPublicKey.subarray(rawPublicKey.length - 32); const publicKeyBytes = rawPublicKey.subarray(rawPublicKey.length - 32);
return base64urlEncode(publicKeyBytes); return base64urlEncode(publicKeyBytes);
} }
// --------------------------------------------------------------------------- // 32 zero bytes; equals the Backend GENESIS_CHAIN_HASH.
// Zero chain hash (initial prev_chain_hash for the first operation)
// ---------------------------------------------------------------------------
/**
* The initial chain hash value: base64url encoding of 32 zero bytes.
* Must match the backend's GENESIS_CHAIN_HASH constant exactly.
*/
export const ZERO_CHAIN_HASH: string = base64urlEncode(Buffer.alloc(32, 0)); export const ZERO_CHAIN_HASH: string = base64urlEncode(Buffer.alloc(32, 0));
+1 -4
View File
@@ -20,7 +20,6 @@ export {
} from './utils.js'; } from './utils.js';
export type { export type {
// Enums
AgentStatus, AgentStatus,
KeyStatus, KeyStatus,
ExportStatus, ExportStatus,
@@ -29,7 +28,6 @@ export type {
AdminAction, AdminAction,
ErrorCode, ErrorCode,
// Entities
Agent, Agent,
AgentKey, AgentKey,
Operation, Operation,
@@ -41,11 +39,9 @@ export type {
User, User,
Export, Export,
// Protocol
EOR, EOR,
EAR, EAR,
// API request/response
ElydoraClientConfig, ElydoraClientConfig,
CreateOperationParams, CreateOperationParams,
RegisterAgentRequest, RegisterAgentRequest,
@@ -75,6 +71,7 @@ export type {
JWKSResponse, JWKSResponse,
HealthResponse, HealthResponse,
DeepHealthResponse, DeepHealthResponse,
Webhook,
ListWebhooksResponse, ListWebhooksResponse,
RegisterWebhookResponse, RegisterWebhookResponse,
ListMembersResponse, ListMembersResponse,
+3 -46
View File
@@ -1,6 +1,8 @@
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { parseStrictJsonObject } from './strict-json.js'; import { sameAgentId, samePath } from './common.js';
import { quotePosix, readPosixArgument, type ParsedArgument } from './shell-command.js';
import { isObject, parseStrictJsonObject, type JsonObject } from './strict-json.js';
export const AGENT_KEY = 'augment'; export const AGENT_KEY = 'augment';
export const GUARD_SCRIPT = 'guard.js'; export const GUARD_SCRIPT = 'guard.js';
@@ -20,8 +22,6 @@ const SESSION_EVENTS = new Set([
'PromptSubmit', 'PromptSubmit',
]); ]);
export type JsonObject = Record<string, unknown>;
export interface AugmentHandler extends JsonObject { export interface AugmentHandler extends JsonObject {
readonly type: 'command'; readonly type: 'command';
readonly command: string; readonly command: string;
@@ -58,23 +58,10 @@ export interface RuntimeContract {
readonly auditWrapperPath: string; readonly auditWrapperPath: 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);
}
function hasOwn(value: JsonObject, key: string): boolean { function hasOwn(value: JsonObject, key: string): boolean {
return Object.prototype.hasOwnProperty.call(value, key); return Object.prototype.hasOwnProperty.call(value, key);
} }
function quotePosix(value: string): string {
return `'${value.replaceAll("'", `'"'"'`)}'`;
}
function quoteWindows(value: string): string { function quoteWindows(value: string): string {
return `"${value.replaceAll('"', '\\"')}"`; return `"${value.replaceAll('"', '\\"')}"`;
} }
@@ -98,42 +85,12 @@ function readWindowsArgument(command: string, start: number): ParsedArgument | u
return undefined; return undefined;
} }
const POSIX_APOSTROPHE = `'"'"'`;
function readPosixArgument(command: string, start: number): ParsedArgument | undefined {
if (command[start] !== "'") return undefined;
let value = '';
for (let index = start + 1; index < command.length;) {
if (command.startsWith(POSIX_APOSTROPHE, index)) {
value += "'";
index += POSIX_APOSTROPHE.length;
continue;
}
if (command[index] === "'") return { value, next: index + 1 };
value += command[index];
index += 1;
}
return undefined;
}
function parseWrapperCommand(command: string): string | undefined { function parseWrapperCommand(command: string): string | undefined {
const readArgument = process.platform === 'win32' ? readWindowsArgument : readPosixArgument; const readArgument = process.platform === 'win32' ? readWindowsArgument : readPosixArgument;
const parsed = readArgument(command, 0); const parsed = readArgument(command, 0);
return parsed?.next === command.length && parsed.value ? parsed.value : undefined; return parsed?.next === command.length && parsed.value ? parsed.value : undefined;
} }
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;
}
export function wrapperPaths(agentDirectory: string): { export function wrapperPaths(agentDirectory: string): {
readonly guardPath: string; readonly guardPath: string;
readonly auditPath: string; readonly auditPath: string;
+4 -12
View File
@@ -22,18 +22,10 @@ const DISPLAY_NAME = 'Augment Code CLI';
const SETTINGS_DIRECTORY_LABEL = 'Auggie configuration directory'; const SETTINGS_DIRECTORY_LABEL = 'Auggie configuration directory';
const SETTINGS_LABEL = 'Auggie user settings'; const SETTINGS_LABEL = 'Auggie user settings';
export type AugmentRuntimePaths = ManagedRuntimePaths;
export type PreparedAugmentInstallation = PreparedManagedInstallation;
export type { RenameFile };
export function augmentRuntimePaths(config: InstallConfig): AugmentRuntimePaths {
return managedRuntimePaths(config, AGENT_KEY, GUARD_SCRIPT, AUDIT_SCRIPT);
}
export async function preflightAugmentInstallation( export async function preflightAugmentInstallation(
config: InstallConfig, config: InstallConfig,
settingsPath: string, settingsPath: string,
): Promise<AugmentRuntimePaths> { ): Promise<ManagedRuntimePaths> {
return preflightManagedInstallation({ return preflightManagedInstallation({
agentKey: AGENT_KEY, agentKey: AGENT_KEY,
hookLocations: [{ directoryLabel: SETTINGS_DIRECTORY_LABEL, filePath: settingsPath }], hookLocations: [{ directoryLabel: SETTINGS_DIRECTORY_LABEL, filePath: settingsPath }],
@@ -44,13 +36,13 @@ export async function preflightAugmentInstallation(
export async function prepareAugmentInstallation( export async function prepareAugmentInstallation(
config: InstallConfig, config: InstallConfig,
rendered: RenderedAugmentDocument, rendered: RenderedAugmentDocument,
): Promise<PreparedAugmentInstallation> { ): Promise<PreparedManagedInstallation> {
if (!rendered.changed && rendered.document.raw === undefined) { if (!rendered.changed && rendered.document.raw === undefined) {
throw new Error('Auggie hook installation did not produce a settings document'); throw new Error('Auggie hook installation did not produce a settings document');
} }
const settingsSource = rendered.next ?? rendered.document.raw; const settingsSource = rendered.next ?? rendered.document.raw;
if (settingsSource === undefined) throw new Error('Auggie hook settings are missing'); if (settingsSource === undefined) throw new Error('Auggie hook settings are missing');
const paths = augmentRuntimePaths(config); const paths = managedRuntimePaths(config, AGENT_KEY, GUARD_SCRIPT, AUDIT_SCRIPT);
return prepareManagedInstallation({ return prepareManagedInstallation({
agentKey: AGENT_KEY, agentKey: AGENT_KEY,
displayName: DISPLAY_NAME, displayName: DISPLAY_NAME,
@@ -78,7 +70,7 @@ export async function prepareAugmentInstallation(
} }
export async function commitAugmentInstallation( export async function commitAugmentInstallation(
prepared: PreparedAugmentInstallation, prepared: PreparedManagedInstallation,
renameFile?: RenameFile, renameFile?: RenameFile,
): Promise<void> { ): Promise<void> {
await commitManagedInstallation(prepared, renameFile); await commitManagedInstallation(prepared, renameFile);
+10 -95
View File
@@ -2,9 +2,7 @@ import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { import {
AGENT_KEY, AGENT_KEY,
AUDIT_SCRIPT,
AUDIT_WRAPPER, AUDIT_WRAPPER,
GUARD_SCRIPT,
GUARD_WRAPPER, GUARD_WRAPPER,
buildWrapper, buildWrapper,
createAugmentDocument, createAugmentDocument,
@@ -13,15 +11,13 @@ import {
type RenderedAugmentDocument, type RenderedAugmentDocument,
type RuntimeContract, type RuntimeContract,
} from './augment-contract.js'; } from './augment-contract.js';
import { MAX_CONFIG_BYTES, samePath } from './common.js';
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js'; import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
import { managedRuntimeFilesExist } from './managed-runtime-status.js';
import { import {
commitManagedTransaction, commitManagedTransaction,
prepareManagedFileChange, prepareManagedFileChange,
} from './managed-transaction.js'; } from './managed-transaction.js';
import { parseStrictJsonObject, type JsonObject } from './strict-json.js';
const MAX_SECRET_BYTES = 64 * 1024;
const MAX_CONFIG_BYTES = 512 * 1024;
export function resolveConfigPath(): string { export function resolveConfigPath(): string {
return path.join(os.homedir(), '.augment', 'settings.json'); return path.join(os.homedir(), '.augment', 'settings.json');
@@ -59,102 +55,21 @@ export async function writeAugmentDocument(rendered: RenderedAugmentDocument): P
}); });
} }
function sameAgentId(left: string, right: string): boolean { function wrappersValid(contract: RuntimeContract): boolean {
return process.platform === 'win32' const agentDirectory = path.dirname(contract.guardPath);
? left.toLowerCase() === right.toLowerCase() return samePath(contract.guardWrapperPath, path.join(agentDirectory, GUARD_WRAPPER))
: left === right;
}
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 requireNonEmptyString(value: unknown, field: string, configPath: string): string {
if (typeof value !== 'string' || value.trim().length === 0) {
throw new Error(`Elydora runtime config ${field} is invalid: ${configPath}`);
}
return value;
}
function validateRuntimeConfig(
config: JsonObject,
contract: RuntimeContract,
configPath: string,
): void {
const supported = new Set(['org_id', 'agent_id', 'kid', 'base_url', 'token', 'agent_name']);
const extra = Object.keys(config).find((key) => !supported.has(key));
if (extra) throw new Error(`Elydora runtime config has unsupported field "${extra}": ${configPath}`);
requireNonEmptyString(config.org_id, 'org_id', configPath);
requireNonEmptyString(config.kid, 'kid', configPath);
const agentId = requireNonEmptyString(config.agent_id, 'agent_id', configPath);
if (!sameAgentId(agentId, contract.agentId) || config.agent_name !== AGENT_KEY) {
throw new Error(`Elydora runtime identity does not match Auggie hooks: ${configPath}`);
}
if (config.token !== undefined) requireNonEmptyString(config.token, 'token', configPath);
const rawBaseUrl = requireNonEmptyString(config.base_url, 'base_url', configPath);
let baseUrl: URL;
try {
baseUrl = new URL(rawBaseUrl);
} catch (error) {
throw new Error(`Elydora runtime config base_url is invalid: ${configPath}`, {
cause: error instanceof Error ? error : new Error(String(error)),
});
}
if (!['http:', 'https:'].includes(baseUrl.protocol)
|| !baseUrl.hostname
|| baseUrl.username
|| baseUrl.password
|| baseUrl.search
|| baseUrl.hash) {
throw new Error(`Elydora runtime config base_url is invalid: ${configPath}`);
}
}
function validatePrivateKey(contents: string, keyPath: string): void {
const bytes = Buffer.from(contents, 'base64url');
if (bytes.length !== 32 || bytes.toString('base64url') !== contents) {
throw new Error(`Elydora private key is invalid: ${keyPath}`);
}
}
function validContractPaths(contract: RuntimeContract, agentDirectory: string): boolean {
return samePath(path.dirname(agentDirectory), path.join(os.homedir(), '.elydora'))
&& samePath(contract.guardPath, path.join(agentDirectory, GUARD_SCRIPT))
&& samePath(contract.auditPath, path.join(agentDirectory, AUDIT_SCRIPT))
&& samePath(contract.guardWrapperPath, path.join(agentDirectory, GUARD_WRAPPER))
&& samePath(contract.auditWrapperPath, path.join(agentDirectory, AUDIT_WRAPPER)); && samePath(contract.auditWrapperPath, path.join(agentDirectory, AUDIT_WRAPPER));
} }
async function runtimeContractExists(contract: RuntimeContract): Promise<boolean> { async function runtimeContractExists(contract: RuntimeContract): Promise<boolean> {
const runtimeRoot = path.join(os.homedir(), '.elydora'); if (!wrappersValid(contract)) return false;
const agentDirectory = path.dirname(contract.guardPath); if (!await managedRuntimeFilesExist(contract, AGENT_KEY)) return false;
if (!validContractPaths(contract, agentDirectory)) return false; const [guardWrapper, auditWrapper] = await Promise.all([
if (!await inspectPhysicalDirectory(runtimeRoot, 'Elydora runtime directory')) return false;
if (!await inspectPhysicalDirectory(agentDirectory, 'Elydora agent runtime directory')) {
return false;
}
const configPath = path.join(agentDirectory, 'config.json');
const keyPath = path.join(agentDirectory, 'private.key');
const [config, key, guard, audit, guardWrapper, auditWrapper] = await Promise.all([
readPhysicalFile(configPath, 'Elydora runtime config', MAX_CONFIG_BYTES),
readPhysicalFile(keyPath, 'Elydora private key', MAX_SECRET_BYTES),
readPhysicalFile(contract.guardPath, 'Elydora guard runtime'),
readPhysicalFile(contract.auditPath, 'Elydora audit runtime'),
readPhysicalFile(contract.guardWrapperPath, 'Auggie guard wrapper'), readPhysicalFile(contract.guardWrapperPath, 'Auggie guard wrapper'),
readPhysicalFile(contract.auditWrapperPath, 'Auggie audit wrapper'), readPhysicalFile(contract.auditWrapperPath, 'Auggie audit wrapper'),
]); ]);
if (!config || !key || !guard || !audit || !guardWrapper || !auditWrapper) return false; return guardWrapper?.contents === buildWrapper(contract.guardPath)
const parsed = parseStrictJsonObject(config.contents, `Elydora runtime config at ${configPath}`); && auditWrapper?.contents === buildWrapper(contract.auditPath);
validateRuntimeConfig(parsed, contract, configPath);
validatePrivateKey(key.contents, keyPath);
return guard.contents.length > 0
&& audit.contents.length > 0
&& guardWrapper.contents === buildWrapper(contract.guardPath)
&& auditWrapper.contents === buildWrapper(contract.auditPath);
} }
export async function augmentRuntimeFilesExist( export async function augmentRuntimeFilesExist(
+1 -14
View File
@@ -1,5 +1,6 @@
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { sameAgentId, samePath } from './common.js';
import { isObject, parseStrictJsonObject, type JsonObject } from './strict-json.js'; import { isObject, parseStrictJsonObject, type JsonObject } from './strict-json.js';
export const AGENT_KEY = 'claudecode'; export const AGENT_KEY = 'claudecode';
@@ -76,20 +77,6 @@ interface RuntimeReference {
readonly scriptPath: string; readonly scriptPath: string;
} }
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 requireKnownKeys(value: JsonObject, allowed: readonly string[], label: string): void { function requireKnownKeys(value: JsonObject, allowed: readonly string[], label: string): void {
const keys = new Set(allowed); const keys = new Set(allowed);
const extra = Object.keys(value).find((key) => !keys.has(key)); const extra = Object.keys(value).find((key) => !keys.has(key));
+3 -12
View File
@@ -7,7 +7,6 @@ import {
} from './claudecode-contract.js'; } from './claudecode-contract.js';
import { import {
commitManagedInstallation, commitManagedInstallation,
managedRuntimePaths,
preflightManagedInstallation, preflightManagedInstallation,
prepareManagedInstallation, prepareManagedInstallation,
type ManagedRuntimePaths, type ManagedRuntimePaths,
@@ -19,18 +18,10 @@ const DISPLAY_NAME = 'Claude Code';
const SETTINGS_DIRECTORY_LABEL = 'Claude Code configuration directory'; const SETTINGS_DIRECTORY_LABEL = 'Claude Code configuration directory';
const SETTINGS_LABEL = 'Claude Code user settings'; const SETTINGS_LABEL = 'Claude Code user settings';
export type ClaudeRuntimePaths = ManagedRuntimePaths;
export type PreparedClaudeInstallation = PreparedManagedInstallation;
export type { RenameFile };
export function claudeRuntimePaths(config: InstallConfig): ClaudeRuntimePaths {
return managedRuntimePaths(config, AGENT_KEY, GUARD_SCRIPT, AUDIT_SCRIPT);
}
export async function preflightClaudeInstallation( export async function preflightClaudeInstallation(
config: InstallConfig, config: InstallConfig,
settingsPath: string, settingsPath: string,
): Promise<ClaudeRuntimePaths> { ): Promise<ManagedRuntimePaths> {
return preflightManagedInstallation({ return preflightManagedInstallation({
agentKey: AGENT_KEY, agentKey: AGENT_KEY,
hookLocations: [{ directoryLabel: SETTINGS_DIRECTORY_LABEL, filePath: settingsPath }], hookLocations: [{ directoryLabel: SETTINGS_DIRECTORY_LABEL, filePath: settingsPath }],
@@ -41,7 +32,7 @@ export async function preflightClaudeInstallation(
export async function prepareClaudeInstallation( export async function prepareClaudeInstallation(
config: InstallConfig, config: InstallConfig,
rendered: RenderedClaudeDocument, rendered: RenderedClaudeDocument,
): Promise<PreparedClaudeInstallation> { ): Promise<PreparedManagedInstallation> {
if (!rendered.changed && rendered.document.raw === undefined) { if (!rendered.changed && rendered.document.raw === undefined) {
throw new Error('Claude Code hook installation did not produce a settings document'); throw new Error('Claude Code hook installation did not produce a settings document');
} }
@@ -63,7 +54,7 @@ export async function prepareClaudeInstallation(
} }
export async function commitClaudeInstallation( export async function commitClaudeInstallation(
prepared: PreparedClaudeInstallation, prepared: PreparedManagedInstallation,
renameFile?: RenameFile, renameFile?: RenameFile,
): Promise<void> { ): Promise<void> {
await commitManagedInstallation(prepared, renameFile); await commitManagedInstallation(prepared, renameFile);
+2 -87
View File
@@ -10,11 +10,11 @@ import {
type RenderedClaudeDocument, type RenderedClaudeDocument,
} from './claudecode-contract.js'; } from './claudecode-contract.js';
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js'; import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
import { managedRuntimeFilesExist } from './managed-runtime-status.js';
import { import {
commitManagedTransaction, commitManagedTransaction,
prepareManagedFileChange, prepareManagedFileChange,
} from './managed-transaction.js'; } from './managed-transaction.js';
import { parseStrictJsonObject, type JsonObject } from './strict-json.js';
export function claudeConfigDirectory(): string { export function claudeConfigDirectory(): string {
const configured = process.env.CLAUDE_CONFIG_DIR; const configured = process.env.CLAUDE_CONFIG_DIR;
@@ -58,96 +58,11 @@ export async function writeClaudeDocument(rendered: RenderedClaudeDocument): Pro
}); });
} }
function requireNonEmptyString(value: unknown, field: string, configPath: string): string {
if (typeof value !== 'string' || value.trim().length === 0) {
throw new Error(`Elydora runtime config ${field} is invalid: ${configPath}`);
}
return value;
}
function sameAgentId(left: string, right: string): boolean {
return process.platform === 'win32'
? left.toLowerCase() === right.toLowerCase()
: left === right;
}
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 validateRuntimeConfig(
config: JsonObject,
contract: ClaudeRuntimeContract,
configPath: string,
): void {
const supported = new Set(['org_id', 'agent_id', 'kid', 'base_url', 'token', 'agent_name']);
const extra = Object.keys(config).find((key) => !supported.has(key));
if (extra) throw new Error(`Elydora runtime config has unsupported field "${extra}": ${configPath}`);
requireNonEmptyString(config.org_id, 'org_id', configPath);
requireNonEmptyString(config.kid, 'kid', configPath);
const agentId = requireNonEmptyString(config.agent_id, 'agent_id', configPath);
if (!sameAgentId(agentId, contract.agentId) || config.agent_name !== AGENT_KEY) {
throw new Error(`Elydora runtime identity does not match Claude Code hooks: ${configPath}`);
}
if (config.token !== undefined) requireNonEmptyString(config.token, 'token', configPath);
const rawBaseUrl = requireNonEmptyString(config.base_url, 'base_url', configPath);
let baseUrl: URL;
try {
baseUrl = new URL(rawBaseUrl);
} catch (error) {
throw new Error(`Elydora runtime config base_url is invalid: ${configPath}`, {
cause: error instanceof Error ? error : new Error(String(error)),
});
}
if (!['http:', 'https:'].includes(baseUrl.protocol)
|| !baseUrl.hostname
|| baseUrl.username
|| baseUrl.password
|| baseUrl.search
|| baseUrl.hash) {
throw new Error(`Elydora runtime config base_url is invalid: ${configPath}`);
}
}
function validatePrivateKey(contents: string, keyPath: string): void {
const bytes = Buffer.from(contents, 'base64url');
if (bytes.length !== 32 || bytes.toString('base64url') !== contents) {
throw new Error(`Elydora private key is invalid: ${keyPath}`);
}
}
async function runtimeContractExists(contract: ClaudeRuntimeContract): Promise<boolean> {
const runtimeRoot = path.join(os.homedir(), '.elydora');
const agentDirectory = path.dirname(contract.guardPath);
if (!samePath(path.dirname(agentDirectory), runtimeRoot)
|| !samePath(contract.auditPath, path.join(agentDirectory, 'hook.js'))) return false;
if (!await inspectPhysicalDirectory(runtimeRoot, 'Elydora runtime directory')) return false;
if (!await inspectPhysicalDirectory(agentDirectory, 'Elydora agent runtime directory')) return false;
const configPath = path.join(agentDirectory, 'config.json');
const keyPath = path.join(agentDirectory, 'private.key');
const [config, key, guard, audit] = await Promise.all([
readPhysicalFile(configPath, 'Elydora runtime config'),
readPhysicalFile(keyPath, 'Elydora private key'),
readPhysicalFile(contract.guardPath, 'Elydora guard runtime'),
readPhysicalFile(contract.auditPath, 'Elydora audit runtime'),
]);
if (!config || !key || !guard || !audit) return false;
const parsed = parseStrictJsonObject(config.contents, `Elydora runtime config at ${configPath}`);
validateRuntimeConfig(parsed, contract, configPath);
validatePrivateKey(key.contents, keyPath);
return guard.contents.length > 0 && audit.contents.length > 0;
}
export async function claudeRuntimeFilesExist( export async function claudeRuntimeFilesExist(
contracts: readonly ClaudeRuntimeContract[], contracts: readonly ClaudeRuntimeContract[],
): Promise<boolean> { ): Promise<boolean> {
for (const contract of contracts) { for (const contract of contracts) {
if (await runtimeContractExists(contract)) return true; if (await managedRuntimeFilesExist(contract, AGENT_KEY)) return true;
} }
return false; return false;
} }
+2 -26
View File
@@ -1,5 +1,7 @@
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { asError, errorMessage, sameAgentId, samePath } from './common.js';
import { isObject } from './strict-json.js';
export const AGENT_KEY = 'cline'; export const AGENT_KEY = 'cline';
export const GUARD_SCRIPT = 'guard.js'; export const GUARD_SCRIPT = 'guard.js';
@@ -33,32 +35,6 @@ export interface ClineRuntimeContract {
readonly auditPath: string; readonly auditPath: string;
} }
type JsonObject = Record<string, unknown>;
function isObject(value: unknown): value is JsonObject {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
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 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;
}
export function sameAgentId(left: string, right: string): boolean {
return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right;
}
export function resolveHooksDirectory(): string { export function resolveHooksDirectory(): string {
const configuredDirectory = process.env.CLINE_DIR?.trim(); const configuredDirectory = process.env.CLINE_DIR?.trim();
const clineDirectory = configuredDirectory const clineDirectory = configuredDirectory
+4 -8
View File
@@ -9,8 +9,8 @@ import {
buildWrapper, buildWrapper,
type ClineHookFile, type ClineHookFile,
runtimeContract, runtimeContract,
sameAgentId,
} from './cline-contract.js'; } from './cline-contract.js';
import { sameAgentId } from './common.js';
import { import {
commitManagedInstallation, commitManagedInstallation,
preflightManagedInstallation, preflightManagedInstallation,
@@ -28,10 +28,6 @@ import {
const DISPLAY_NAME = 'Cline'; const DISPLAY_NAME = 'Cline';
const DIRECTORY_LABEL = 'Cline hooks directory'; const DIRECTORY_LABEL = 'Cline hooks directory';
export type ClineRuntimePaths = ManagedRuntimePaths;
export type PreparedClineInstallation = PreparedManagedInstallation;
export type { RenameFile };
function hookLocations(files: readonly ClineHookFile[]) { function hookLocations(files: readonly ClineHookFile[]) {
return files.map((file) => ({ return files.map((file) => ({
directoryLabel: DIRECTORY_LABEL, directoryLabel: DIRECTORY_LABEL,
@@ -42,7 +38,7 @@ function hookLocations(files: readonly ClineHookFile[]) {
export async function preflightClineInstallation( export async function preflightClineInstallation(
config: InstallConfig, config: InstallConfig,
files: readonly ClineHookFile[], files: readonly ClineHookFile[],
): Promise<ClineRuntimePaths> { ): Promise<ManagedRuntimePaths> {
return preflightManagedInstallation({ return preflightManagedInstallation({
agentKey: AGENT_KEY, agentKey: AGENT_KEY,
hookLocations: hookLocations(files), hookLocations: hookLocations(files),
@@ -54,7 +50,7 @@ export async function prepareClineInstallation(
config: InstallConfig, config: InstallConfig,
guardFile: ClineHookFile, guardFile: ClineHookFile,
auditFile: ClineHookFile, auditFile: ClineHookFile,
): Promise<PreparedClineInstallation> { ): Promise<PreparedManagedInstallation> {
const paths = await preflightClineInstallation(config, [guardFile, auditFile]); const paths = await preflightClineInstallation(config, [guardFile, auditFile]);
const guardMetadata = buildMetadata('guard', config.agentId, paths.guardPath); const guardMetadata = buildMetadata('guard', config.agentId, paths.guardPath);
const auditMetadata = buildMetadata('audit', config.agentId, paths.auditPath); const auditMetadata = buildMetadata('audit', config.agentId, paths.auditPath);
@@ -86,7 +82,7 @@ export async function prepareClineInstallation(
} }
export async function commitClineInstallation( export async function commitClineInstallation(
prepared: PreparedClineInstallation, prepared: PreparedManagedInstallation,
renameFile?: RenameFile, renameFile?: RenameFile,
): Promise<void> { ): Promise<void> {
await commitManagedInstallation(prepared, renameFile); await commitManagedInstallation(prepared, renameFile);
+2 -96
View File
@@ -1,21 +1,12 @@
import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { import {
AGENT_KEY, AGENT_KEY,
AUDIT_SCRIPT,
GUARD_SCRIPT,
type ClineHookFile, type ClineHookFile,
type ClineRuntimeContract, type ClineRuntimeContract,
parseMetadata, parseMetadata,
sameAgentId,
} from './cline-contract.js'; } from './cline-contract.js';
import { generateGuardScript } from './guard-template.js';
import { generateHookScript } from './hook-template.js';
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js'; import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
import { parseStrictJsonObject, type JsonObject } from './strict-json.js'; import { managedRuntimeFilesExist } from './managed-runtime-status.js';
const MAX_SECRET_BYTES = 64 * 1024;
const MAX_CONFIG_BYTES = 512 * 1024;
export async function readHookFile(filePath: string): Promise<ClineHookFile> { export async function readHookFile(filePath: string): Promise<ClineHookFile> {
const directory = path.dirname(filePath); const directory = path.dirname(filePath);
@@ -38,91 +29,6 @@ export function requireAvailableHookFile(file: ClineHookFile): void {
} }
} }
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 requireString(value: unknown, field: string, configPath: string): string {
if (typeof value !== 'string' || value.trim().length === 0) {
throw new Error(`Elydora runtime config ${field} is invalid: ${configPath}`);
}
return value;
}
function validateRuntimeConfig(
config: JsonObject,
contract: ClineRuntimeContract,
configPath: string,
): void {
const supported = new Set(['org_id', 'agent_id', 'kid', 'base_url', 'token', 'agent_name']);
const extra = Object.keys(config).find((key) => !supported.has(key));
if (extra) throw new Error(`Elydora runtime config has unsupported field "${extra}": ${configPath}`);
requireString(config.org_id, 'org_id', configPath);
requireString(config.kid, 'kid', configPath);
const agentId = requireString(config.agent_id, 'agent_id', configPath);
if (!sameAgentId(agentId, contract.agentId) || config.agent_name !== AGENT_KEY) {
throw new Error(`Elydora runtime identity does not match Cline hooks: ${configPath}`);
}
if (config.token !== undefined) requireString(config.token, 'token', configPath);
const rawBaseUrl = requireString(config.base_url, 'base_url', configPath);
let baseUrl: URL;
try {
baseUrl = new URL(rawBaseUrl);
} catch (error) {
throw new Error(`Elydora runtime config base_url is invalid: ${configPath}`, {
cause: error instanceof Error ? error : new Error(String(error)),
});
}
if (!['http:', 'https:'].includes(baseUrl.protocol)
|| !baseUrl.hostname
|| baseUrl.username
|| baseUrl.password
|| baseUrl.search
|| baseUrl.hash) {
throw new Error(`Elydora runtime config base_url is invalid: ${configPath}`);
}
}
function validatePrivateKey(contents: string, keyPath: string): void {
const bytes = Buffer.from(contents, 'base64url');
if (bytes.length !== 32 || bytes.toString('base64url') !== contents) {
throw new Error(`Elydora private key is invalid: ${keyPath}`);
}
}
function validContractPaths(contract: ClineRuntimeContract): boolean {
return samePath(path.dirname(contract.agentDirectory), path.join(os.homedir(), '.elydora'))
&& samePath(contract.guardPath, path.join(contract.agentDirectory, GUARD_SCRIPT))
&& samePath(contract.auditPath, path.join(contract.agentDirectory, AUDIT_SCRIPT));
}
export async function runtimeFilesExist(contract: ClineRuntimeContract): Promise<boolean> { export async function runtimeFilesExist(contract: ClineRuntimeContract): Promise<boolean> {
if (!validContractPaths(contract)) return false; return managedRuntimeFilesExist(contract, AGENT_KEY);
const runtimeRoot = path.join(os.homedir(), '.elydora');
if (!await inspectPhysicalDirectory(runtimeRoot, 'Elydora runtime directory')) return false;
if (!await inspectPhysicalDirectory(contract.agentDirectory, 'Elydora agent runtime directory')) {
return false;
}
const configPath = path.join(contract.agentDirectory, 'config.json');
const keyPath = path.join(contract.agentDirectory, 'private.key');
const [config, key, guard, audit] = await Promise.all([
readPhysicalFile(configPath, 'Elydora runtime config', MAX_CONFIG_BYTES),
readPhysicalFile(keyPath, 'Elydora private key', MAX_SECRET_BYTES),
readPhysicalFile(contract.guardPath, 'Elydora guard runtime'),
readPhysicalFile(contract.auditPath, 'Elydora audit runtime'),
]);
if (!config || !key || !guard || !audit) return false;
const parsed = parseStrictJsonObject(config.contents, `Elydora runtime config at ${configPath}`);
validateRuntimeConfig(parsed, contract, configPath);
validatePrivateKey(key.contents, keyPath);
return guard.contents === generateGuardScript(AGENT_KEY, contract.agentId)
&& audit.contents === generateHookScript(
AGENT_KEY,
contract.agentId,
{ nativePayload: true },
);
} }
+15 -129
View File
@@ -1,5 +1,14 @@
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { sameAgentId, samePath } from './common.js';
import {
encodedWindowsCommand,
isNodeExecutable,
parseEncodedWindowsCommand,
parseLegacyWindowsCommand,
parsePosixCommand,
posixSource,
} from './shell-command.js';
import { isObject, parseStrictJsonObject, type JsonObject } from './strict-json.js'; import { isObject, parseStrictJsonObject, type JsonObject } from './strict-json.js';
export const AGENT_KEY = 'codex'; export const AGENT_KEY = 'codex';
@@ -33,142 +42,16 @@ export interface RuntimeContract {
readonly auditPath: string; readonly auditPath: string;
} }
interface ParsedArgument {
readonly value: string;
readonly next: number;
}
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("'", "''")}'`;
}
function windowsPowerShellPath(): string {
const configuredRoot = process.platform === 'win32' ? process.env.SystemRoot : undefined;
const systemRoot = configuredRoot
&& path.win32.isAbsolute(configuredRoot)
&& !/["%\r\n]/.test(configuredRoot)
? configuredRoot
: 'C:\\Windows';
return path.win32.join(
systemRoot,
'System32',
'WindowsPowerShell',
'v1.0',
'powershell.exe',
);
}
function windowsCommand(scriptPath: string): string {
const source = `& ${quotePowerShell(process.execPath)} ${quotePowerShell(scriptPath)}; exit $LASTEXITCODE`;
const encoded = Buffer.from(source, 'utf16le').toString('base64');
return `"${windowsPowerShellPath()}" -NoLogo -NoProfile -NonInteractive -EncodedCommand ${encoded}`;
}
export function buildHandler(scriptPath: string, statusMessage: string): JsonObject { export function buildHandler(scriptPath: string, statusMessage: string): JsonObject {
return { return {
type: 'command', type: 'command',
command: `${quotePosix(process.execPath)} ${quotePosix(scriptPath)}`, command: posixSource(scriptPath),
commandWindows: windowsCommand(scriptPath), commandWindows: encodedWindowsCommand(scriptPath),
timeout: HOOK_TIMEOUT_SECONDS, timeout: HOOK_TIMEOUT_SECONDS,
statusMessage, statusMessage,
}; };
} }
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: unknown): readonly [string, string] | undefined {
if (typeof command !== 'string') return 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 parsePowerShellSource(source: string): readonly [string, string] | undefined {
if (!source.startsWith('& ')) return undefined;
const executable = readPowerShellArgument(source, 2);
if (!executable || source[executable.next] !== ' ') return undefined;
const script = readPowerShellArgument(source, executable.next + 1);
if (!script || source.slice(script.next) !== '; exit $LASTEXITCODE') return undefined;
return [executable.value, script.value];
}
function parseWindowsCommand(command: unknown): readonly [string, string] | undefined {
if (typeof command !== 'string') return undefined;
const match = /^"([^"\r\n]+)" -NoLogo -NoProfile -NonInteractive -EncodedCommand ([A-Za-z0-9+/]+={0,2})$/.exec(command);
if (!match
|| !path.win32.isAbsolute(match[1])
|| path.win32.basename(match[1]).toLowerCase() !== 'powershell.exe') return undefined;
const encoded = match[2];
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) return undefined;
const buffer = Buffer.from(encoded, 'base64');
if (buffer.toString('base64') !== encoded || buffer.length % 2 !== 0) return undefined;
return parsePowerShellSource(buffer.toString('utf16le'));
}
function parseLegacyWindowsCommand(command: unknown): readonly [string, string] | undefined {
if (typeof command !== 'string') return undefined;
const match = /^"([^"\r\n]+)" "([^"\r\n]+)"$/.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 exactHandlerKeys(handler: JsonObject): boolean { function exactHandlerKeys(handler: JsonObject): boolean {
return Object.keys(handler).sort().join('|') return Object.keys(handler).sort().join('|')
=== 'command|commandWindows|statusMessage|timeout|type'; === 'command|commandWindows|statusMessage|timeout|type';
@@ -179,8 +62,11 @@ function managedScriptPath(handler: JsonObject, statusMessage: string): string |
|| handler.type !== 'command' || handler.type !== 'command'
|| handler.timeout !== HOOK_TIMEOUT_SECONDS || handler.timeout !== HOOK_TIMEOUT_SECONDS
|| handler.statusMessage !== statusMessage) return undefined; || handler.statusMessage !== statusMessage) return undefined;
if (typeof handler.command !== 'string' || typeof handler.commandWindows !== 'string') {
return undefined;
}
const posix = parsePosixCommand(handler.command); const posix = parsePosixCommand(handler.command);
const windows = parseWindowsCommand(handler.commandWindows) const windows = parseEncodedWindowsCommand(handler.commandWindows)
?? parseLegacyWindowsCommand(handler.commandWindows); ?? parseLegacyWindowsCommand(handler.commandWindows);
if (!posix || !windows if (!posix || !windows
|| !path.isAbsolute(posix[0]) || !path.isAbsolute(posix[0])
+3 -12
View File
@@ -7,7 +7,6 @@ import {
} from './codex-contract.js'; } from './codex-contract.js';
import { import {
commitManagedInstallation, commitManagedInstallation,
managedRuntimePaths,
preflightManagedInstallation, preflightManagedInstallation,
prepareManagedInstallation, prepareManagedInstallation,
type ManagedRuntimePaths, type ManagedRuntimePaths,
@@ -19,18 +18,10 @@ const DISPLAY_NAME = 'Codex';
const HOOKS_DIRECTORY_LABEL = 'Codex hooks directory'; const HOOKS_DIRECTORY_LABEL = 'Codex hooks directory';
const HOOKS_LABEL = 'Codex user hooks'; const HOOKS_LABEL = 'Codex user hooks';
export type CodexRuntimePaths = ManagedRuntimePaths;
export type PreparedCodexInstallation = PreparedManagedInstallation;
export type { RenameFile };
export function codexRuntimePaths(config: InstallConfig): CodexRuntimePaths {
return managedRuntimePaths(config, AGENT_KEY, GUARD_SCRIPT, AUDIT_SCRIPT);
}
export async function preflightCodexInstallation( export async function preflightCodexInstallation(
config: InstallConfig, config: InstallConfig,
hooksPath: string, hooksPath: string,
): Promise<CodexRuntimePaths> { ): Promise<ManagedRuntimePaths> {
return preflightManagedInstallation({ return preflightManagedInstallation({
agentKey: AGENT_KEY, agentKey: AGENT_KEY,
hookLocations: [{ directoryLabel: HOOKS_DIRECTORY_LABEL, filePath: hooksPath }], hookLocations: [{ directoryLabel: HOOKS_DIRECTORY_LABEL, filePath: hooksPath }],
@@ -41,7 +32,7 @@ export async function preflightCodexInstallation(
export async function prepareCodexInstallation( export async function prepareCodexInstallation(
config: InstallConfig, config: InstallConfig,
rendered: RenderedDocument, rendered: RenderedDocument,
): Promise<PreparedCodexInstallation> { ): Promise<PreparedManagedInstallation> {
if (!rendered.changed && rendered.document.raw === undefined) { if (!rendered.changed && rendered.document.raw === undefined) {
throw new Error('Codex hook installation did not produce a configuration document'); throw new Error('Codex hook installation did not produce a configuration document');
} }
@@ -63,7 +54,7 @@ export async function prepareCodexInstallation(
} }
export async function commitCodexInstallation( export async function commitCodexInstallation(
prepared: PreparedCodexInstallation, prepared: PreparedManagedInstallation,
renameFile?: RenameFile, renameFile?: RenameFile,
): Promise<void> { ): Promise<void> {
await commitManagedInstallation(prepared, renameFile); await commitManagedInstallation(prepared, renameFile);
+25 -138
View File
@@ -1,6 +1,4 @@
import { randomUUID } from 'node:crypto';
import fsp from 'node:fs/promises'; import fsp from 'node:fs/promises';
import type { FileHandle } from 'node:fs/promises';
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { import {
@@ -12,20 +10,13 @@ import {
createDocument, createDocument,
parseDocument, parseDocument,
} from './codex-contract.js'; } from './codex-contract.js';
import { asError, errorMessage } from './common.js';
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js'; import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
import { parseStrictJsonObject } from './strict-json.js'; import { managedRuntimePresent } from './managed-runtime-status.js';
import {
function asError(error: unknown): Error { commitManagedTransaction,
return error instanceof Error ? error : new Error(String(error)); prepareManagedFileChange,
} } from './managed-transaction.js';
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function hasCode(error: unknown, code: string): boolean {
return typeof error === 'object' && error !== null && 'code' in error && error.code === code;
}
async function codexHomePath(): Promise<string> { async function codexHomePath(): Promise<string> {
const configured = process.env.CODEX_HOME; const configured = process.env.CODEX_HOME;
@@ -63,135 +54,31 @@ export async function readDocument(): Promise<CodexDocument> {
return snapshot ? parseDocument(filePath, snapshot.contents) : createDocument(filePath); return snapshot ? parseDocument(filePath, snapshot.contents) : createDocument(filePath);
} }
async function unlinkOptional(filePath: string): Promise<void> {
try {
await fsp.unlink(filePath);
} catch (error) {
if (!hasCode(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;
if (process.platform !== 'win32') await fsp.chmod(filePath, 0o600);
} 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 Codex user hooks');
throw new Error(`Stage Codex user hooks: ${errorMessage(error)}`, { cause: failures[0] });
}
}
async function assertUnchanged(document: CodexDocument): Promise<void> {
const current = await readPhysicalFile(document.filePath, 'Codex user hooks');
if (current?.contents !== document.raw) {
throw new Error(`Codex user hooks changed during update: ${document.filePath}`);
}
}
async function ensureHooksDirectory(directory: string): Promise<void> {
try {
await fsp.mkdir(directory, { recursive: true, mode: 0o700 });
} catch (error) {
throw new Error(`Create Codex hooks directory at ${directory}: ${errorMessage(error)}`, {
cause: asError(error),
});
}
if (!await inspectPhysicalDirectory(directory, 'Codex hooks directory')) {
throw new Error(`Codex hooks directory is missing: ${directory}`);
}
}
export async function writeDocument(rendered: RenderedDocument): Promise<void> { export async function writeDocument(rendered: RenderedDocument): Promise<void> {
if (!rendered.changed) return; if (!rendered.changed) return;
await assertUnchanged(rendered.document); const change = await prepareManagedFileChange({
const directory = path.dirname(rendered.document.filePath); filePath: rendered.document.filePath,
await ensureHooksDirectory(directory); label: 'Codex user hooks',
if (rendered.next === undefined) { next: rendered.next,
try { mode: 0o600,
await fsp.unlink(rendered.document.filePath); expectedSource: rendered.document.raw,
} catch (error) { verifyExpectedSource: true,
if (!hasCode(error, 'ENOENT')) { });
throw new Error( if (!change) return;
`Remove Codex user hooks at ${rendered.document.filePath}: ${errorMessage(error)}`, await commitManagedTransaction({
{ cause: asError(error) }, displayName: 'Codex',
); operation: 'uninstall',
} directories: [{
} path: path.dirname(rendered.document.filePath),
return; label: 'Codex hooks directory',
} }],
changes: [change],
const temporaryPath = path.join( });
directory,
`.${path.basename(rendered.document.filePath)}.${randomUUID()}.tmp`,
);
let failure: Error | undefined;
try {
await writeExclusive(temporaryPath, rendered.next);
await assertUnchanged(rendered.document);
await fsp.rename(temporaryPath, rendered.document.filePath);
} catch (error) {
failure = new Error(
`Write Codex user hooks at ${rendered.document.filePath}: ${errorMessage(error)}`,
{ cause: asError(error) },
);
}
let cleanupFailure: Error | undefined;
try {
await unlinkOptional(temporaryPath);
} catch (error) {
cleanupFailure = new Error(
`Clean Codex hook staging file at ${temporaryPath}: ${errorMessage(error)}`,
{ cause: asError(error) },
);
}
if (failure && cleanupFailure) {
throw new AggregateError([failure, cleanupFailure], 'Write Codex user hooks');
}
if (failure) throw failure;
if (cleanupFailure) throw cleanupFailure;
}
async function physicalFileExists(filePath: string, label: string): Promise<boolean> {
return Boolean(await readPhysicalFile(filePath, label));
}
function sameAgentId(left: unknown, right: string): boolean {
return typeof left === 'string' && (process.platform === 'win32'
? left.toLowerCase() === right.toLowerCase()
: left === right);
} }
export async function runtimeFilesExist(contracts: RuntimeContract[]): Promise<boolean> { export async function runtimeFilesExist(contracts: RuntimeContract[]): Promise<boolean> {
for (const contract of contracts) { for (const contract of contracts) {
const directory = path.dirname(contract.guardPath); if (await managedRuntimePresent(contract, AGENT_KEY)) return true;
const configPath = path.join(directory, 'config.json');
const snapshot = await readPhysicalFile(configPath, 'Elydora runtime config');
if (!snapshot) continue;
const config = parseStrictJsonObject(
snapshot.contents,
`Elydora runtime config at ${configPath}`,
);
if (config.agent_name !== AGENT_KEY || !sameAgentId(config.agent_id, contract.agentId)) {
continue;
}
const files = await Promise.all([
physicalFileExists(contract.guardPath, 'Elydora guard runtime'),
physicalFileExists(contract.auditPath, 'Elydora audit runtime'),
physicalFileExists(path.join(directory, 'private.key'), 'Elydora private key'),
]);
if (files.every(Boolean)) return true;
} }
return false; return false;
} }
+31
View File
@@ -0,0 +1,31 @@
import path from 'node:path';
export const MAX_SECRET_BYTES = 64 * 1024;
export const MAX_CONFIG_BYTES = 512 * 1024;
export const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
export function asError(error: unknown): Error {
return error instanceof Error ? error : new Error(String(error));
}
export function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
export function hasCode(error: unknown, code: string): boolean {
return typeof error === 'object' && error !== null && 'code' in error && error.code === code;
}
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;
}
export function sameAgentId(left: unknown, right: string): boolean {
return typeof left === 'string' && (process.platform === 'win32'
? left.toLowerCase() === right.toLowerCase()
: left === right);
}
+15 -91
View File
@@ -1,6 +1,14 @@
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { sameAgentId, samePath } from './common.js';
import type { FileSnapshot } from './managed-files.js'; import type { FileSnapshot } from './managed-files.js';
import {
isNodeExecutable,
parsePosixCommand,
parsePowerShellSource,
posixSource,
powerShellSource,
} from './shell-command.js';
import { validateHooks, type CopilotHooks } from './copilot-schema.js'; import { validateHooks, type CopilotHooks } from './copilot-schema.js';
import { parseStrictJsonObject, type JsonObject } from './strict-json.js'; import { parseStrictJsonObject, type JsonObject } from './strict-json.js';
@@ -51,122 +59,38 @@ export interface RuntimeContract {
readonly auditPath: string; readonly auditPath: string;
} }
interface ParsedArgument {
readonly value: string;
readonly next: number;
}
interface ManagedEntry { interface ManagedEntry {
readonly agentId: string; readonly agentId: string;
readonly scriptPath: string; readonly scriptPath: string;
} }
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;
}
export function sameAgentId(left: string, right: string): boolean {
return process.platform === 'win32'
? left.toLowerCase() === right.toLowerCase()
: left === right;
}
function agentKey(agentId: string): string { function agentKey(agentId: string): string {
return process.platform === 'win32' ? agentId.toLowerCase() : agentId; return process.platform === 'win32' ? agentId.toLowerCase() : agentId;
} }
function quotePosix(value: string): string {
return `'${value.replaceAll("'", `'"'"'`)}'`;
}
function quotePowerShell(value: string): string {
return `'${value.replaceAll("'", "''")}'`;
}
export function buildHandler(scriptPath: string): JsonObject { export function buildHandler(scriptPath: string): JsonObject {
return { return {
type: 'command', type: 'command',
bash: `${quotePosix(process.execPath)} ${quotePosix(scriptPath)}`, bash: posixSource(scriptPath),
powershell: `& ${quotePowerShell(process.execPath)} ${quotePowerShell(scriptPath)}; exit $LASTEXITCODE`, powershell: powerShellSource(scriptPath),
timeoutSec: HOOK_TIMEOUT_SECONDS, timeoutSec: HOOK_TIMEOUT_SECONDS,
}; };
} }
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 parseGeneratedBash(command: unknown): readonly [string, string] | undefined {
if (typeof command !== 'string') return 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 parseGeneratedPowerShell(command: unknown): readonly [string, string] | undefined {
if (typeof command !== 'string' || !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 exactHandlerKeys(handler: JsonObject): boolean { function exactHandlerKeys(handler: JsonObject): boolean {
return Object.keys(handler).sort().join(',') === 'bash,powershell,timeoutSec,type'; return Object.keys(handler).sort().join(',') === 'bash,powershell,timeoutSec,type';
} }
function nodeExecutable(filePath: string): boolean {
if (!path.isAbsolute(filePath)) return false;
const name = path.basename(filePath).toLowerCase();
return name === 'node' || name === 'node.exe';
}
function currentManagedScriptPath(handler: JsonObject): string | undefined { function currentManagedScriptPath(handler: JsonObject): string | undefined {
if (!exactHandlerKeys(handler) if (!exactHandlerKeys(handler)
|| handler.type !== 'command' || handler.type !== 'command'
|| handler.timeoutSec !== HOOK_TIMEOUT_SECONDS) return undefined; || handler.timeoutSec !== HOOK_TIMEOUT_SECONDS) return undefined;
const bash = parseGeneratedBash(handler.bash); if (typeof handler.bash !== 'string' || typeof handler.powershell !== 'string') return undefined;
const powershell = parseGeneratedPowerShell(handler.powershell); const bash = parsePosixCommand(handler.bash);
const powershell = parsePowerShellSource(handler.powershell);
if (!bash || !powershell if (!bash || !powershell
|| !nodeExecutable(bash[0]) || !path.isAbsolute(bash[0])
|| !isNodeExecutable(bash[0])
|| !samePath(bash[0], powershell[0]) || !samePath(bash[0], powershell[0])
|| !samePath(bash[1], powershell[1])) return undefined; || !samePath(bash[1], powershell[1])) return undefined;
return bash[1]; return bash[1];
+4 -9
View File
@@ -6,8 +6,8 @@ import {
GUARD_SCRIPT, GUARD_SCRIPT,
type CopilotSources, type CopilotSources,
type RenderedDocument, type RenderedDocument,
samePath,
} from './copilot-contract.js'; } from './copilot-contract.js';
import { MAX_SOURCE_BYTES, samePath } from './common.js';
import { requireHooksEnabled } from './copilot-io.js'; import { requireHooksEnabled } from './copilot-io.js';
import { import {
commitManagedInstallation, commitManagedInstallation,
@@ -26,11 +26,6 @@ import {
const DISPLAY_NAME = 'GitHub Copilot CLI'; const DISPLAY_NAME = 'GitHub Copilot CLI';
const DIRECTORY_LABEL = 'GitHub Copilot hooks directory'; const DIRECTORY_LABEL = 'GitHub Copilot hooks directory';
const SOURCE_LABEL = 'GitHub Copilot hook source'; const SOURCE_LABEL = 'GitHub Copilot hook source';
const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
export type CopilotRuntimePaths = ManagedRuntimePaths;
export type PreparedCopilotInstallation = PreparedManagedInstallation;
export type { RenameFile };
function hookLocations(sources: CopilotSources) { function hookLocations(sources: CopilotSources) {
return [sources.user, ...(sources.legacy ? [sources.legacy] : [])].map((document) => ({ return [sources.user, ...(sources.legacy ? [sources.legacy] : [])].map((document) => ({
@@ -42,7 +37,7 @@ function hookLocations(sources: CopilotSources) {
export async function preflightCopilotInstallation( export async function preflightCopilotInstallation(
config: InstallConfig, config: InstallConfig,
sources: CopilotSources, sources: CopilotSources,
): Promise<CopilotRuntimePaths> { ): Promise<ManagedRuntimePaths> {
requireHooksEnabled(sources); requireHooksEnabled(sources);
return preflightManagedInstallation({ return preflightManagedInstallation({
agentKey: AGENT_KEY, agentKey: AGENT_KEY,
@@ -63,7 +58,7 @@ export async function prepareCopilotInstallation(
config: InstallConfig, config: InstallConfig,
sources: CopilotSources, sources: CopilotSources,
rendered: readonly RenderedDocument[], rendered: readonly RenderedDocument[],
): Promise<PreparedCopilotInstallation> { ): Promise<PreparedManagedInstallation> {
await preflightCopilotInstallation(config, sources); await preflightCopilotInstallation(config, sources);
const documents = installationDocuments(sources, rendered); const documents = installationDocuments(sources, rendered);
const prepared = await prepareManagedInstallation({ const prepared = await prepareManagedInstallation({
@@ -107,7 +102,7 @@ export async function prepareCopilotInstallation(
} }
export async function commitCopilotInstallation( export async function commitCopilotInstallation(
prepared: PreparedCopilotInstallation, prepared: PreparedManagedInstallation,
renameFile?: RenameFile, renameFile?: RenameFile,
): Promise<void> { ): Promise<void> {
await commitManagedInstallation(prepared, renameFile); await commitManagedInstallation(prepared, renameFile);
+5 -90
View File
@@ -2,34 +2,26 @@ import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { import {
AGENT_KEY, AGENT_KEY,
AUDIT_SCRIPT,
CONFIG_FILE, CONFIG_FILE,
GUARD_SCRIPT,
type CopilotDocument, type CopilotDocument,
type CopilotSources, type CopilotSources,
type RuntimeContract, type RuntimeContract,
createDocument, createDocument,
parseDocument, parseDocument,
sameAgentId,
samePath,
} from './copilot-contract.js'; } from './copilot-contract.js';
import { generateGuardScript } from './guard-template.js'; import { MAX_SOURCE_BYTES } from './common.js';
import { generateHookScript } from './hook-template.js';
import { import {
inspectPhysicalDirectory, inspectPhysicalDirectory,
readPhysicalFile, readPhysicalFile,
type FileSnapshot, type FileSnapshot,
} from './managed-files.js'; } from './managed-files.js';
import { managedRuntimeFilesExist } from './managed-runtime-status.js';
import { import {
parseStrictJsonObject, parseStrictJsonObject,
parseStrictJsoncObject, parseStrictJsoncObject,
type JsonObject, type JsonObject,
} from './strict-json.js'; } from './strict-json.js';
const MAX_SECRET_BYTES = 64 * 1024;
const MAX_CONFIG_BYTES = 512 * 1024;
const MAX_SETTINGS_BYTES = 2 * 1024 * 1024;
export interface CopilotPaths { export interface CopilotPaths {
readonly copilotHome: string; readonly copilotHome: string;
readonly userHooksDirectory: string; readonly userHooksDirectory: string;
@@ -98,7 +90,7 @@ async function readHookDocument(
filePath: string, filePath: string,
label: string, label: string,
): Promise<CopilotDocument | undefined> { ): Promise<CopilotDocument | undefined> {
const snapshot = await readPhysicalFile(filePath, label, MAX_SETTINGS_BYTES); const snapshot = await readPhysicalFile(filePath, label, MAX_SOURCE_BYTES);
return snapshot ? parseDocument(filePath, snapshot, label) : undefined; return snapshot ? parseDocument(filePath, snapshot, label) : undefined;
} }
@@ -111,7 +103,7 @@ function parseSettings(raw: string, layer: SettingsLayer): JsonObject {
} }
async function readSettingsLayer(layer: SettingsLayer): Promise<ParsedSettingsLayer> { async function readSettingsLayer(layer: SettingsLayer): Promise<ParsedSettingsLayer> {
const snapshot = await readPhysicalFile(layer.filePath, layer.label, MAX_SETTINGS_BYTES); const snapshot = await readPhysicalFile(layer.filePath, layer.label, MAX_SOURCE_BYTES);
if (!snapshot) return layer; if (!snapshot) return layer;
const root = parseSettings(snapshot.contents, layer); const root = parseSettings(snapshot.contents, layer);
if (root.disableAllHooks !== undefined && typeof root.disableAllHooks !== 'boolean') { if (root.disableAllHooks !== undefined && typeof root.disableAllHooks !== 'boolean') {
@@ -167,86 +159,9 @@ export function requireHooksEnabled(sources: CopilotSources): void {
} }
} }
function requireString(value: unknown, field: string, configPath: string): string {
if (typeof value !== 'string' || value.trim().length === 0) {
throw new Error(`Elydora runtime config ${field} is invalid: ${configPath}`);
}
return value;
}
function validateRuntimeConfig(
config: JsonObject,
contract: RuntimeContract,
configPath: string,
): void {
const supported = new Set(['org_id', 'agent_id', 'kid', 'base_url', 'token', 'agent_name']);
const extra = Object.keys(config).find((key) => !supported.has(key));
if (extra) throw new Error(`Elydora runtime config has unsupported field "${extra}": ${configPath}`);
requireString(config.org_id, 'org_id', configPath);
requireString(config.kid, 'kid', configPath);
const agentId = requireString(config.agent_id, 'agent_id', configPath);
if (!sameAgentId(agentId, contract.agentId) || config.agent_name !== AGENT_KEY) {
throw new Error(`Elydora runtime identity does not match Copilot hooks: ${configPath}`);
}
if (config.token !== undefined) requireString(config.token, 'token', configPath);
const rawBaseUrl = requireString(config.base_url, 'base_url', configPath);
let baseUrl: URL;
try {
baseUrl = new URL(rawBaseUrl);
} catch (error) {
throw new Error(`Elydora runtime config base_url is invalid: ${configPath}`, {
cause: error instanceof Error ? error : new Error(String(error)),
});
}
if (!['http:', 'https:'].includes(baseUrl.protocol)
|| !baseUrl.hostname
|| baseUrl.username
|| baseUrl.password
|| baseUrl.search
|| baseUrl.hash) {
throw new Error(`Elydora runtime config base_url is invalid: ${configPath}`);
}
}
function validatePrivateKey(contents: string, keyPath: string): void {
const bytes = Buffer.from(contents, 'base64url');
if (bytes.length !== 32 || bytes.toString('base64url') !== contents) {
throw new Error(`Elydora private key is invalid: ${keyPath}`);
}
}
function validContractPaths(contract: RuntimeContract): boolean {
const agentDirectory = path.dirname(contract.guardPath);
return samePath(path.dirname(agentDirectory), path.join(os.homedir(), '.elydora'))
&& samePath(contract.guardPath, path.join(agentDirectory, GUARD_SCRIPT))
&& samePath(contract.auditPath, path.join(agentDirectory, AUDIT_SCRIPT));
}
export async function runtimeFilesExist(contracts: RuntimeContract[]): Promise<boolean> { export async function runtimeFilesExist(contracts: RuntimeContract[]): Promise<boolean> {
for (const contract of contracts) { for (const contract of contracts) {
if (!validContractPaths(contract)) continue; if (await managedRuntimeFilesExist(contract, AGENT_KEY)) return true;
const runtimeRoot = path.join(os.homedir(), '.elydora');
const agentDirectory = path.dirname(contract.guardPath);
if (!await inspectPhysicalDirectory(runtimeRoot, 'Elydora runtime directory')) continue;
if (!await inspectPhysicalDirectory(agentDirectory, 'Elydora agent runtime directory')) continue;
const configPath = path.join(agentDirectory, 'config.json');
const keyPath = path.join(agentDirectory, 'private.key');
const [config, key, guard, audit] = await Promise.all([
readPhysicalFile(configPath, 'Elydora runtime config', MAX_CONFIG_BYTES),
readPhysicalFile(keyPath, 'Elydora private key', MAX_SECRET_BYTES),
readPhysicalFile(contract.guardPath, 'Elydora guard runtime'),
readPhysicalFile(contract.auditPath, 'Elydora audit runtime'),
]);
if (!config || !key || !guard || !audit) continue;
const parsed = parseStrictJsonObject(config.contents, `Elydora runtime config at ${configPath}`);
validateRuntimeConfig(parsed, contract, configPath);
validatePrivateKey(key.contents, keyPath);
if (guard.contents === generateGuardScript(AGENT_KEY, contract.agentId)
&& audit.contents === generateHookScript(
AGENT_KEY,
contract.agentId,
{ nativePayload: true },
)) return true;
} }
return false; return false;
} }
+23 -90
View File
@@ -1,15 +1,32 @@
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { sameAgentId, samePath } from './common.js';
import type { GuardScriptOptions } from './guard-template.js';
import type { HookScriptOptions } from './hook-template.js';
import {
isNodeExecutable,
parsePosixCommand,
parsePowerShellSource,
posixSource,
powerShellSource,
} from './shell-command.js';
import { isObject, parseStrictJsonObject, type JsonObject } from './strict-json.js'; import { isObject, parseStrictJsonObject, type JsonObject } from './strict-json.js';
export { isObject, parseStrictJsonObject };
export type { JsonObject };
export const AGENT_KEY = 'cursor'; export const AGENT_KEY = 'cursor';
export const CONFIG_FILE = 'hooks.json'; export const CONFIG_FILE = 'hooks.json';
export const GUARD_SCRIPT = 'guard.js'; export const GUARD_SCRIPT = 'guard.js';
export const AUDIT_SCRIPT = 'hook.js'; export const AUDIT_SCRIPT = 'hook.js';
export const HOOK_TIMEOUT_SECONDS = 10; export const HOOK_TIMEOUT_SECONDS = 10;
export const GUARD_OPTIONS: GuardScriptOptions = {
failClosed: true,
successOutput: '{"permission":"allow"}\n',
denyProtocol: 'cursor',
};
export const AUDIT_OPTIONS: HookScriptOptions = {
failClosed: true,
nativePayload: true,
successOutput: '{}\n',
};
export type CursorHooks = Record<string, JsonObject[]>; export type CursorHooks = Record<string, JsonObject[]>;
@@ -33,37 +50,10 @@ export interface RuntimeContract {
readonly auditPath: string; readonly auditPath: string;
} }
interface ParsedArgument {
readonly value: string;
readonly next: number;
}
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 { export function buildHandler(scriptPath: string): JsonObject {
const command = process.platform === 'win32' const command = process.platform === 'win32'
? `& ${quotePowerShell(process.execPath)} ${quotePowerShell(scriptPath)}; exit $LASTEXITCODE` ? powerShellSource(scriptPath)
: `${quotePosix(process.execPath)} ${quotePosix(scriptPath)}`; : posixSource(scriptPath);
return { return {
command, command,
timeout: HOOK_TIMEOUT_SECONDS, timeout: HOOK_TIMEOUT_SECONDS,
@@ -71,68 +61,11 @@ export function buildHandler(scriptPath: string): JsonObject {
}; };
} }
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 { function parseLegacyCommand(command: string): readonly [string, string] | undefined {
const match = /^(node(?:\.exe)?)\s+"([^"\r\n]+)"$/i.exec(command); const match = /^(node(?:\.exe)?)\s+"([^"\r\n]+)"$/i.exec(command);
return match ? [match[1], match[2]] : undefined; 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 { function managedScriptPath(handler: JsonObject): string | undefined {
const keys = Object.keys(handler); const keys = Object.keys(handler);
if (keys.length === 3 if (keys.length === 3
@@ -140,7 +73,7 @@ function managedScriptPath(handler: JsonObject): string | undefined {
&& handler.timeout === HOOK_TIMEOUT_SECONDS && handler.timeout === HOOK_TIMEOUT_SECONDS
&& handler.failClosed === true) { && handler.failClosed === true) {
const parsed = process.platform === 'win32' const parsed = process.platform === 'win32'
? parsePowerShellCommand(handler.command) ? parsePowerShellSource(handler.command)
: parsePosixCommand(handler.command); : parsePosixCommand(handler.command);
if (parsed if (parsed
&& path.isAbsolute(parsed[0]) && path.isAbsolute(parsed[0])
+7 -22
View File
@@ -1,7 +1,6 @@
import type { InstallConfig } from './base.js'; import type { InstallConfig } from './base.js';
import { import {
commitManagedInstallation, commitManagedInstallation,
managedRuntimePaths,
preflightManagedInstallation, preflightManagedInstallation,
prepareManagedInstallation, prepareManagedInstallation,
type ManagedRuntimePaths, type ManagedRuntimePaths,
@@ -10,7 +9,9 @@ import {
} from './managed-installation.js'; } from './managed-installation.js';
import { import {
AGENT_KEY, AGENT_KEY,
AUDIT_OPTIONS,
AUDIT_SCRIPT, AUDIT_SCRIPT,
GUARD_OPTIONS,
GUARD_SCRIPT, GUARD_SCRIPT,
type RenderedDocument, type RenderedDocument,
} from './cursor-contract.js'; } from './cursor-contract.js';
@@ -20,17 +21,9 @@ const DISPLAY_NAME = 'Cursor';
const HOOKS_DIRECTORY_LABEL = 'Cursor hooks directory'; const HOOKS_DIRECTORY_LABEL = 'Cursor hooks directory';
const HOOKS_LABEL = 'Cursor user hooks'; const HOOKS_LABEL = 'Cursor user hooks';
export type CursorRuntimePaths = ManagedRuntimePaths;
export type PreparedCursorInstallation = PreparedManagedInstallation;
export type { RenameFile };
export function cursorRuntimePaths(config: InstallConfig): CursorRuntimePaths {
return managedRuntimePaths(config, AGENT_KEY, GUARD_SCRIPT, AUDIT_SCRIPT);
}
export async function preflightCursorInstallation( export async function preflightCursorInstallation(
config: InstallConfig, config: InstallConfig,
): Promise<CursorRuntimePaths> { ): Promise<ManagedRuntimePaths> {
return preflightManagedInstallation({ return preflightManagedInstallation({
agentKey: AGENT_KEY, agentKey: AGENT_KEY,
hookLocations: [{ hookLocations: [{
@@ -44,7 +37,7 @@ export async function preflightCursorInstallation(
export async function prepareCursorInstallation( export async function prepareCursorInstallation(
config: InstallConfig, config: InstallConfig,
rendered: RenderedDocument, rendered: RenderedDocument,
): Promise<PreparedCursorInstallation> { ): Promise<PreparedManagedInstallation> {
if (!rendered.changed && rendered.document.raw === undefined) { if (!rendered.changed && rendered.document.raw === undefined) {
throw new Error('Cursor hook installation did not produce a configuration document'); throw new Error('Cursor hook installation did not produce a configuration document');
} }
@@ -61,21 +54,13 @@ export async function prepareCursorInstallation(
source: hooksSource, source: hooksSource,
}], }],
config, config,
guardOptions: { guardOptions: GUARD_OPTIONS,
failClosed: true, auditOptions: AUDIT_OPTIONS,
successOutput: '{"permission":"allow"}\n',
denyProtocol: 'cursor',
},
auditOptions: {
failClosed: true,
nativePayload: true,
successOutput: '{}\n',
},
}, GUARD_SCRIPT, AUDIT_SCRIPT); }, GUARD_SCRIPT, AUDIT_SCRIPT);
} }
export async function commitCursorInstallation( export async function commitCursorInstallation(
prepared: PreparedCursorInstallation, prepared: PreparedManagedInstallation,
renameFile?: RenameFile, renameFile?: RenameFile,
): Promise<void> { ): Promise<void> {
await commitManagedInstallation(prepared, renameFile); await commitManagedInstallation(prepared, renameFile);
+27 -208
View File
@@ -1,237 +1,56 @@
import { randomUUID } from 'node:crypto';
import fsp from 'node:fs/promises';
import type { FileHandle } from 'node:fs/promises';
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { import {
AGENT_KEY, AGENT_KEY,
CONFIG_FILE, CONFIG_FILE,
type CursorDocument, type CursorDocument,
type JsonObject,
type RenderedDocument, type RenderedDocument,
type RuntimeContract, type RuntimeContract,
createDocument, createDocument,
isObject,
parseDocument, parseDocument,
parseStrictJsonObject,
} from './cursor-contract.js'; } from './cursor-contract.js';
import { readPhysicalFile } from './managed-files.js';
function errorMessage(error: unknown): string { import { managedRuntimePresent } from './managed-runtime-status.js';
return error instanceof Error ? error.message : String(error); import {
} commitManagedTransaction,
prepareManagedFileChange,
function asError(error: unknown): Error { } from './managed-transaction.js';
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 { export function cursorConfigPath(): string {
return path.join(os.homedir(), '.cursor', CONFIG_FILE); 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> { export async function readDocument(): Promise<CursorDocument> {
const filePath = cursorConfigPath(); const filePath = cursorConfigPath();
const raw = await readOptionalPhysical(filePath, 'Cursor user hooks'); const snapshot = await readPhysicalFile(filePath, 'Cursor user hooks');
return raw === undefined ? createDocument(filePath) : parseDocument(filePath, raw); return snapshot ? parseDocument(filePath, snapshot.contents) : createDocument(filePath);
}
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> { export async function writeDocument(rendered: RenderedDocument): Promise<void> {
if (!rendered.changed) return; if (!rendered.changed) return;
await assertUnchanged(rendered.document); const change = await prepareManagedFileChange({
if (rendered.next === undefined) { filePath: rendered.document.filePath,
try { label: 'Cursor user hooks',
await fsp.unlink(rendered.document.filePath); next: rendered.next,
} catch (error) { mode: 0o600,
if (!hasErrorCode(error, 'ENOENT')) { expectedSource: rendered.document.raw,
throw new Error( verifyExpectedSource: true,
`Remove Cursor user hooks at ${rendered.document.filePath}: ${errorMessage(error)}`, });
{ cause: asError(error) }, if (!change) return;
); await commitManagedTransaction({
} displayName: 'Cursor',
} operation: 'uninstall',
return; directories: [{
} path: path.dirname(rendered.document.filePath),
label: 'Cursor hooks directory',
const directory = path.dirname(rendered.document.filePath); }],
await ensurePhysicalDirectory(directory); changes: [change],
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;
return parseStrictJsonObject(raw, `Elydora runtime config at ${filePath}`);
}
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> { export async function runtimeFilesExist(contracts: RuntimeContract[]): Promise<boolean> {
for (const contract of contracts) { for (const contract of contracts) {
const runtimeConfig = await readRuntimeConfig( if (await managedRuntimePresent(contract, AGENT_KEY)) return true;
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'),
physicalFileExists(
path.join(path.dirname(contract.guardPath), 'private.key'),
'Elydora private key',
),
]);
if (files.every(Boolean)) return true;
} }
return false; return false;
} }
+13 -96
View File
@@ -1,5 +1,13 @@
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { sameAgentId, samePath } from './common.js';
import {
parseLegacyWindowsCommand,
parsePosixCommand,
parsePowerShellSource,
posixSource,
powerShellSource,
} from './shell-command.js';
import type { JsonObject } from './strict-json.js'; import type { JsonObject } from './strict-json.js';
export const AGENT_KEY = 'droid'; export const AGENT_KEY = 'droid';
@@ -10,7 +18,6 @@ export const TOOL_EVENTS = ['PreToolUse', 'PostToolUse'] as const;
const HANDLER_KEYS = ['command', 'timeout', 'type']; const HANDLER_KEYS = ['command', 'timeout', 'type'];
const GROUP_KEYS = ['hooks', 'matcher']; const GROUP_KEYS = ['hooks', 'matcher'];
const WINDOWS_EXIT_SUFFIX = '; exit $LASTEXITCODE';
export type ToolEvent = typeof TOOL_EVENTS[number]; export type ToolEvent = typeof TOOL_EVENTS[number];
@@ -44,26 +51,13 @@ export interface ManagedRemoval {
readonly removeGroup: boolean; readonly removeGroup: boolean;
} }
interface ParsedArgument {
readonly value: string;
readonly next: number;
}
function quotePosix(value: string): string {
return `'${value.replaceAll("'", `'"'"'`)}'`;
}
function quotePowerShell(value: string): string {
return `'${value.replaceAll("'", "''")}'`;
}
export function buildCommand(scriptPath: string): string { export function buildCommand(scriptPath: string): string {
if (!path.isAbsolute(process.execPath) || !path.isAbsolute(scriptPath)) { if (!path.isAbsolute(process.execPath) || !path.isAbsolute(scriptPath)) {
throw new Error('Factory Droid hook commands require absolute executable and script paths'); throw new Error('Factory Droid hook commands require absolute executable and script paths');
} }
return process.platform === 'win32' return process.platform === 'win32'
? `& ${quotePowerShell(process.execPath)} ${quotePowerShell(scriptPath)}${WINDOWS_EXIT_SUFFIX}` ? powerShellSource(scriptPath)
: `${quotePosix(process.execPath)} ${quotePosix(scriptPath)}`; : posixSource(scriptPath);
} }
export function buildGroup(scriptPath: string): DroidGroup { export function buildGroup(scriptPath: string): DroidGroup {
@@ -150,90 +144,13 @@ export function readHookMap(value: unknown, label: string): DroidHookMap {
return hooks; return hooks;
} }
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;
}
const POSIX_APOSTROPHE = `'"'"'`;
function readPosixArgument(command: string, start: number): ParsedArgument | undefined {
if (command[start] !== "'") return undefined;
let value = '';
for (let index = start + 1; index < command.length;) {
if (command.startsWith(POSIX_APOSTROPHE, index)) {
value += "'";
index += POSIX_APOSTROPHE.length;
continue;
}
if (command[index] === "'") return { value, next: index + 1 };
value += command[index];
index += 1;
}
return undefined;
}
function parseTwoArguments(
command: string,
start: number,
readArgument: (command: string, start: number) => ParsedArgument | undefined,
): readonly [string, string] | undefined {
const executable = readArgument(command, start);
if (!executable || command[executable.next] !== ' ') return undefined;
const script = readArgument(command, executable.next + 1);
if (!script || script.next !== command.length || !executable.value || !script.value) return undefined;
return [executable.value, script.value];
}
function parseLegacyWindowsCommand(command: string): readonly [string, string] | undefined {
const match = /^"([^"\r\n]+)" "([^"\r\n]+)"$/.exec(command);
return match ? [match[1], match[2]] : 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) !== WINDOWS_EXIT_SUFFIX
|| !executable.value
|| !script.value) return undefined;
return [executable.value, script.value];
}
function parseGeneratedCommand( function parseGeneratedCommand(
command: string, command: string,
includeLegacy: boolean, includeLegacy: boolean,
): readonly [string, string] | undefined { ): readonly [string, string] | undefined {
if (process.platform !== 'win32') return parseTwoArguments(command, 0, readPosixArgument); if (process.platform !== 'win32') return parsePosixCommand(command);
const current = parsePowerShellCommand(command); return parsePowerShellSource(command)
return current ?? (includeLegacy ? parseLegacyWindowsCommand(command) : undefined); ?? (includeLegacy ? parseLegacyWindowsCommand(command) : undefined);
}
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;
}
export function sameAgentId(left: string, right: string): boolean {
return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right;
} }
export function managedAgentId( export function managedAgentId(
+5 -14
View File
@@ -1,11 +1,7 @@
import path from 'node:path'; import path from 'node:path';
import type { InstallConfig } from './base.js'; import type { InstallConfig } from './base.js';
import { import { MAX_SOURCE_BYTES, samePath } from './common.js';
AGENT_KEY, import { AGENT_KEY, AUDIT_SCRIPT, GUARD_SCRIPT } from './droid-contract.js';
AUDIT_SCRIPT,
GUARD_SCRIPT,
samePath,
} from './droid-contract.js';
import { import {
activeDocument, activeDocument,
installationDocuments, installationDocuments,
@@ -31,11 +27,6 @@ import {
const DISPLAY_NAME = 'Factory Droid'; const DISPLAY_NAME = 'Factory Droid';
const DIRECTORY_LABEL = 'Factory Droid user configuration directory'; const DIRECTORY_LABEL = 'Factory Droid user configuration directory';
const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
export type DroidRuntimePaths = ManagedRuntimePaths;
export type PreparedDroidInstallation = PreparedManagedInstallation;
export type { RenameFile };
function sourceLabel(document: DroidDocument): string { function sourceLabel(document: DroidDocument): string {
if (document.kind === 'settings') return 'Factory Droid user settings'; if (document.kind === 'settings') return 'Factory Droid user settings';
@@ -56,7 +47,7 @@ function hookLocations(sources: DroidSources) {
export async function preflightDroidInstallation( export async function preflightDroidInstallation(
config: InstallConfig, config: InstallConfig,
sources: DroidSources, sources: DroidSources,
): Promise<DroidRuntimePaths> { ): Promise<ManagedRuntimePaths> {
requireHooksEnabled(sources); requireHooksEnabled(sources);
return preflightManagedInstallation({ return preflightManagedInstallation({
agentKey: AGENT_KEY, agentKey: AGENT_KEY,
@@ -92,7 +83,7 @@ export async function prepareDroidInstallation(
config: InstallConfig, config: InstallConfig,
sources: DroidSources, sources: DroidSources,
rendered: readonly RenderedDocument[], rendered: readonly RenderedDocument[],
): Promise<PreparedDroidInstallation> { ): Promise<PreparedManagedInstallation> {
await preflightDroidInstallation(config, sources); await preflightDroidInstallation(config, sources);
const changed = installationChanges(sources, rendered); const changed = installationChanges(sources, rendered);
const prepared = await prepareManagedInstallation({ const prepared = await prepareManagedInstallation({
@@ -124,7 +115,7 @@ export async function prepareDroidInstallation(
} }
export async function commitDroidInstallation( export async function commitDroidInstallation(
prepared: PreparedDroidInstallation, prepared: PreparedManagedInstallation,
renameFile?: RenameFile, renameFile?: RenameFile,
): Promise<void> { ): Promise<void> {
await commitManagedInstallation(prepared, renameFile); await commitManagedInstallation(prepared, renameFile);
+4 -93
View File
@@ -1,13 +1,7 @@
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { import { MAX_SOURCE_BYTES } from './common.js';
AGENT_KEY, import { AGENT_KEY, type RuntimeContract } from './droid-contract.js';
AUDIT_SCRIPT,
GUARD_SCRIPT,
type RuntimeContract,
sameAgentId,
samePath,
} from './droid-contract.js';
import { import {
activeDocument, activeDocument,
createLegacyHookDocument, createLegacyHookDocument,
@@ -19,15 +13,9 @@ import {
type DroidDocumentKind, type DroidDocumentKind,
type DroidSources, type DroidSources,
} from './droid-config.js'; } from './droid-config.js';
import { generateGuardScript } from './guard-template.js';
import { generateHookScript } from './hook-template.js';
import { readDroidPolicy } from './droid-policy.js'; import { readDroidPolicy } from './droid-policy.js';
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js'; import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
import { parseStrictJsonObject, type JsonObject } from './strict-json.js'; import { managedRuntimeFilesExist } from './managed-runtime-status.js';
const MAX_SECRET_BYTES = 64 * 1024;
const MAX_CONFIG_BYTES = 512 * 1024;
const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
interface FactoryPaths { interface FactoryPaths {
readonly directory: string; readonly directory: string;
@@ -96,86 +84,9 @@ export function requireHooksEnabled(sources: DroidSources): void {
} }
} }
function requireString(value: unknown, field: string, configPath: string): string {
if (typeof value !== 'string' || value.trim().length === 0) {
throw new Error(`Elydora runtime config ${field} is invalid: ${configPath}`);
}
return value;
}
function validateRuntimeConfig(
config: JsonObject,
contract: RuntimeContract,
configPath: string,
): void {
const supported = new Set(['org_id', 'agent_id', 'kid', 'base_url', 'token', 'agent_name']);
const extra = Object.keys(config).find((key) => !supported.has(key));
if (extra) throw new Error(`Elydora runtime config has unsupported field "${extra}": ${configPath}`);
requireString(config.org_id, 'org_id', configPath);
requireString(config.kid, 'kid', configPath);
const agentId = requireString(config.agent_id, 'agent_id', configPath);
if (!sameAgentId(agentId, contract.agentId) || config.agent_name !== AGENT_KEY) {
throw new Error(`Elydora runtime identity does not match Factory Droid hooks: ${configPath}`);
}
if (config.token !== undefined) requireString(config.token, 'token', configPath);
const rawBaseUrl = requireString(config.base_url, 'base_url', configPath);
let baseUrl: URL;
try {
baseUrl = new URL(rawBaseUrl);
} catch (error) {
throw new Error(`Elydora runtime config base_url is invalid: ${configPath}`, {
cause: error instanceof Error ? error : new Error(String(error)),
});
}
if (!['http:', 'https:'].includes(baseUrl.protocol)
|| !baseUrl.hostname
|| baseUrl.username
|| baseUrl.password
|| baseUrl.search
|| baseUrl.hash) {
throw new Error(`Elydora runtime config base_url is invalid: ${configPath}`);
}
}
function validatePrivateKey(contents: string, keyPath: string): void {
const bytes = Buffer.from(contents, 'base64url');
if (bytes.length !== 32 || bytes.toString('base64url') !== contents) {
throw new Error(`Elydora private key is invalid: ${keyPath}`);
}
}
function validContractPaths(contract: RuntimeContract): boolean {
const agentDirectory = path.dirname(contract.guardPath);
return samePath(path.dirname(agentDirectory), path.join(os.homedir(), '.elydora'))
&& samePath(contract.guardPath, path.join(agentDirectory, GUARD_SCRIPT))
&& samePath(contract.auditPath, path.join(agentDirectory, AUDIT_SCRIPT));
}
export async function runtimeFilesExist(contracts: RuntimeContract[]): Promise<boolean> { export async function runtimeFilesExist(contracts: RuntimeContract[]): Promise<boolean> {
for (const contract of contracts) { for (const contract of contracts) {
if (!validContractPaths(contract)) continue; if (await managedRuntimeFilesExist(contract, AGENT_KEY)) return true;
const runtimeRoot = path.join(os.homedir(), '.elydora');
const agentDirectory = path.dirname(contract.guardPath);
if (!await inspectPhysicalDirectory(runtimeRoot, 'Elydora runtime directory')) continue;
if (!await inspectPhysicalDirectory(agentDirectory, 'Elydora agent runtime directory')) continue;
const configPath = path.join(agentDirectory, 'config.json');
const keyPath = path.join(agentDirectory, 'private.key');
const [config, key, guard, audit] = await Promise.all([
readPhysicalFile(configPath, 'Elydora runtime config', MAX_CONFIG_BYTES),
readPhysicalFile(keyPath, 'Elydora private key', MAX_SECRET_BYTES),
readPhysicalFile(contract.guardPath, 'Elydora guard runtime'),
readPhysicalFile(contract.auditPath, 'Elydora audit runtime'),
]);
if (!config || !key || !guard || !audit) continue;
const parsed = parseStrictJsonObject(config.contents, `Elydora runtime config at ${configPath}`);
validateRuntimeConfig(parsed, contract, configPath);
validatePrivateKey(key.contents, keyPath);
if (guard.contents === generateGuardScript(AGENT_KEY, contract.agentId)
&& audit.contents === generateHookScript(
AGENT_KEY,
contract.agentId,
{ nativePayload: true },
)) return true;
} }
return false; return false;
} }
+1 -6
View File
@@ -1,11 +1,10 @@
import fsp from 'node:fs/promises'; import fsp from 'node:fs/promises';
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { hasCode, MAX_SOURCE_BYTES } from './common.js';
import { inspectPhysicalDirectory, readPhysicalFile, type FileSnapshot } from './managed-files.js'; import { inspectPhysicalDirectory, readPhysicalFile, type FileSnapshot } from './managed-files.js';
import { parseStrictJsoncObject, type JsonObject } from './strict-json.js'; import { parseStrictJsoncObject, type JsonObject } from './strict-json.js';
const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
interface PolicyLocation { interface PolicyLocation {
readonly filePath: string; readonly filePath: string;
readonly label: string; readonly label: string;
@@ -37,10 +36,6 @@ export interface DroidPolicyState {
readonly preconditions: readonly DroidPolicyPrecondition[]; readonly preconditions: readonly DroidPolicyPrecondition[];
} }
function hasCode(error: unknown, code: string): boolean {
return typeof error === 'object' && error !== null && 'code' in error && error.code === code;
}
function optionalBoolean(root: JsonObject, field: string, label: string): boolean | undefined { function optionalBoolean(root: JsonObject, field: string, label: string): boolean | undefined {
const value = root[field]; const value = root[field];
if (value !== undefined && typeof value !== 'boolean') { if (value !== undefined && typeof value !== 'boolean') {
+20 -117
View File
@@ -1,58 +1,25 @@
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { samePath } from './common.js';
interface ParsedArgument { import {
readonly value: string; decodePowerShellSource,
readonly next: number; encodePowerShellSource,
} isNodeExecutable,
isPowerShellExecutable,
parsePosixCommand,
parsePowerShellSource,
posixSource,
quotePowerShell,
windowsPowerShellPath,
} from './shell-command.js';
export interface GeminiRuntimeReference { export interface GeminiRuntimeReference {
readonly agentId: string; readonly agentId: string;
readonly scriptPath: string; readonly scriptPath: string;
} }
export function sameGeminiPath(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;
}
export function sameGeminiAgentId(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("'", "''")}'`;
}
function windowsPowerShellPath(): string {
const configuredRoot = process.env.SystemRoot;
const systemRoot = configuredRoot
&& path.win32.isAbsolute(configuredRoot)
&& !/["%\r\n]/.test(configuredRoot)
? configuredRoot
: 'C:\\Windows';
return path.win32.join(
systemRoot,
'System32',
'WindowsPowerShell',
'v1.0',
'powershell.exe',
);
}
function windowsCommand(scriptPath: string): string { function windowsCommand(scriptPath: string): string {
const source = `& ${quotePowerShell(process.execPath)} ${quotePowerShell(scriptPath)}; exit $LASTEXITCODE`; return `& ${quotePowerShell(windowsPowerShellPath())} -NoLogo -NoProfile -NonInteractive -EncodedCommand ${encodePowerShellSource(scriptPath)}`;
const encoded = Buffer.from(source, 'utf16le').toString('base64');
return `& ${quotePowerShell(windowsPowerShellPath())} -NoLogo -NoProfile -NonInteractive -EncodedCommand ${encoded}`;
} }
export function buildGeminiCommand(scriptPath: string): string { export function buildGeminiCommand(scriptPath: string): string {
@@ -61,74 +28,15 @@ export function buildGeminiCommand(scriptPath: string): string {
} }
return process.platform === 'win32' return process.platform === 'win32'
? windowsCommand(scriptPath) ? windowsCommand(scriptPath)
: `${quotePosix(process.execPath)} ${quotePosix(scriptPath)}`; : posixSource(scriptPath);
}
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 parsePowerShellSource(source: string): readonly [string, string] | undefined {
if (!source.startsWith('& ')) return undefined;
const executable = readPowerShellArgument(source, 2);
if (!executable || source[executable.next] !== ' ') return undefined;
const script = readPowerShellArgument(source, executable.next + 1);
if (!script || source.slice(script.next) !== '; exit $LASTEXITCODE') return undefined;
return [executable.value, script.value];
} }
function parseWindowsCommand(command: string): readonly [string, string] | undefined { function parseWindowsCommand(command: string): readonly [string, string] | undefined {
if (!command.startsWith('& ')) return undefined; const match = /^& ('(?:[^']|'')+') -NoLogo -NoProfile -NonInteractive -EncodedCommand ([A-Za-z0-9+/]+={0,2})$/.exec(command);
const powershell = readPowerShellArgument(command, 2); if (!match) return undefined;
if (!powershell const powershell = parsePowerShellSource(`& ${match[1]} ''; exit $LASTEXITCODE`);
|| !path.win32.isAbsolute(powershell.value) if (!powershell || !isPowerShellExecutable(powershell[0])) return undefined;
|| path.win32.basename(powershell.value).toLowerCase() !== 'powershell.exe') return undefined; return decodePowerShellSource(match[2]);
const prefix = ' -NoLogo -NoProfile -NonInteractive -EncodedCommand ';
if (!command.startsWith(prefix, powershell.next)) return undefined;
const encoded = command.slice(powershell.next + prefix.length);
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) return undefined;
const buffer = Buffer.from(encoded, 'base64');
if (buffer.length % 2 !== 0 || buffer.toString('base64') !== encoded) return undefined;
return parsePowerShellSource(buffer.toString('utf16le'));
} }
function parseLegacyCommand(command: string): readonly [string, string] | undefined { function parseLegacyCommand(command: string): readonly [string, string] | undefined {
@@ -136,11 +44,6 @@ function parseLegacyCommand(command: string): readonly [string, string] | undefi
return match ? ['node', match[1]] : undefined; return match ? ['node', match[1]] : undefined;
} }
function isNodeExecutable(filePath: string): boolean {
const basename = path.basename(filePath).toLowerCase();
return basename === 'node' || basename === 'node.exe';
}
export function geminiRuntimeReference( export function geminiRuntimeReference(
command: string, command: string,
scriptName: string, scriptName: string,
@@ -155,7 +58,7 @@ export function geminiRuntimeReference(
|| path.basename(parsed[1]) !== scriptName) return undefined; || path.basename(parsed[1]) !== scriptName) return undefined;
if (parsed[0] !== 'node' && !path.isAbsolute(parsed[0])) return undefined; if (parsed[0] !== 'node' && !path.isAbsolute(parsed[0])) return undefined;
const agentDirectory = path.dirname(parsed[1]); const agentDirectory = path.dirname(parsed[1]);
if (!sameGeminiPath(path.dirname(agentDirectory), path.join(os.homedir(), '.elydora'))) { if (!samePath(path.dirname(agentDirectory), path.join(os.homedir(), '.elydora'))) {
return undefined; return undefined;
} }
const agentId = path.basename(agentDirectory); const agentId = path.basename(agentDirectory);
+6 -2
View File
@@ -1,9 +1,11 @@
import { sameAgentId } from './common.js';
import { import {
buildGeminiCommand, buildGeminiCommand,
geminiRuntimeReference, geminiRuntimeReference,
sameGeminiAgentId,
type GeminiRuntimeReference, type GeminiRuntimeReference,
} from './gemini-command.js'; } from './gemini-command.js';
import type { GuardScriptOptions } from './guard-template.js';
import type { HookScriptOptions } from './hook-template.js';
import { isObject, type JsonObject } from './strict-json.js'; import { isObject, type JsonObject } from './strict-json.js';
export const AGENT_KEY = 'gemini'; export const AGENT_KEY = 'gemini';
@@ -14,6 +16,8 @@ export const GUARD_HOOK_NAME = 'elydora-guard';
export const AUDIT_HOOK_NAME = 'elydora-audit'; export const AUDIT_HOOK_NAME = 'elydora-audit';
export const HOOK_TIMEOUT_MS = 10_000; export const HOOK_TIMEOUT_MS = 10_000;
export const MANAGED_EVENTS = ['BeforeTool', 'AfterTool'] as const; export const MANAGED_EVENTS = ['BeforeTool', 'AfterTool'] as const;
export const GUARD_OPTIONS: GuardScriptOptions = { successOutput: '{}\n' };
export const AUDIT_OPTIONS: HookScriptOptions = { nativePayload: true, successOutput: '{}\n' };
const KNOWN_EVENTS = new Set([ const KNOWN_EVENTS = new Set([
'BeforeTool', 'BeforeTool',
@@ -248,7 +252,7 @@ export function managedGeminiRemovals(
const handlerIndexes = group.hooks.flatMap((handler, handlerIndex) => { const handlerIndexes = group.hooks.flatMap((handler, handlerIndex) => {
const reference = managedReference(handler, scriptName, hookName, true); const reference = managedReference(handler, scriptName, hookName, true);
return reference return reference
&& (agentId === undefined || sameGeminiAgentId(reference.agentId, agentId)) && (agentId === undefined || sameAgentId(reference.agentId, agentId))
? [handlerIndex] ? [handlerIndex]
: []; : [];
}); });
+7 -9
View File
@@ -1,7 +1,9 @@
import type { InstallConfig } from './base.js'; import type { InstallConfig } from './base.js';
import { import {
AGENT_KEY, AGENT_KEY,
AUDIT_OPTIONS,
AUDIT_SCRIPT, AUDIT_SCRIPT,
GUARD_OPTIONS,
GUARD_SCRIPT, GUARD_SCRIPT,
} from './gemini-contract.js'; } from './gemini-contract.js';
import type { RenderedGeminiDocument } from './gemini-config.js'; import type { RenderedGeminiDocument } from './gemini-config.js';
@@ -18,14 +20,10 @@ const DISPLAY_NAME = 'Gemini CLI';
const SETTINGS_DIRECTORY_LABEL = 'Gemini CLI configuration directory'; const SETTINGS_DIRECTORY_LABEL = 'Gemini CLI configuration directory';
const SETTINGS_LABEL = 'Gemini CLI user settings'; const SETTINGS_LABEL = 'Gemini CLI user settings';
export type GeminiRuntimePaths = ManagedRuntimePaths;
export type PreparedGeminiInstallation = PreparedManagedInstallation;
export type { RenameFile };
export async function preflightGeminiInstallation( export async function preflightGeminiInstallation(
config: InstallConfig, config: InstallConfig,
settingsPath: string, settingsPath: string,
): Promise<GeminiRuntimePaths> { ): Promise<ManagedRuntimePaths> {
return preflightManagedInstallation({ return preflightManagedInstallation({
agentKey: AGENT_KEY, agentKey: AGENT_KEY,
hookLocations: [{ directoryLabel: SETTINGS_DIRECTORY_LABEL, filePath: settingsPath }], hookLocations: [{ directoryLabel: SETTINGS_DIRECTORY_LABEL, filePath: settingsPath }],
@@ -36,7 +34,7 @@ export async function preflightGeminiInstallation(
export async function prepareGeminiInstallation( export async function prepareGeminiInstallation(
config: InstallConfig, config: InstallConfig,
rendered: RenderedGeminiDocument, rendered: RenderedGeminiDocument,
): Promise<PreparedGeminiInstallation> { ): Promise<PreparedManagedInstallation> {
const settingsSource = rendered.next ?? rendered.document.raw; const settingsSource = rendered.next ?? rendered.document.raw;
if (settingsSource === undefined) throw new Error('Gemini CLI hook settings are missing'); if (settingsSource === undefined) throw new Error('Gemini CLI hook settings are missing');
return prepareManagedInstallation({ return prepareManagedInstallation({
@@ -50,13 +48,13 @@ export async function prepareGeminiInstallation(
source: settingsSource, source: settingsSource,
}], }],
config, config,
guardOptions: { successOutput: '{}\n' }, guardOptions: GUARD_OPTIONS,
auditOptions: { nativePayload: true, successOutput: '{}\n' }, auditOptions: AUDIT_OPTIONS,
}, GUARD_SCRIPT, AUDIT_SCRIPT); }, GUARD_SCRIPT, AUDIT_SCRIPT);
} }
export async function commitGeminiInstallation( export async function commitGeminiInstallation(
prepared: PreparedGeminiInstallation, prepared: PreparedManagedInstallation,
renameFile?: RenameFile, renameFile?: RenameFile,
): Promise<void> { ): Promise<void> {
await commitManagedInstallation(prepared, renameFile); await commitManagedInstallation(prepared, renameFile);
+8 -78
View File
@@ -2,7 +2,9 @@ import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { import {
AGENT_KEY, AGENT_KEY,
AUDIT_OPTIONS,
CONFIG_FILE, CONFIG_FILE,
GUARD_OPTIONS,
type GeminiRuntimeContract, type GeminiRuntimeContract,
} from './gemini-contract.js'; } from './gemini-contract.js';
import { import {
@@ -11,13 +13,12 @@ import {
type GeminiDocument, type GeminiDocument,
type RenderedGeminiDocument, type RenderedGeminiDocument,
} from './gemini-config.js'; } from './gemini-config.js';
import { sameGeminiAgentId, sameGeminiPath } from './gemini-command.js';
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js'; import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
import { managedRuntimeFilesExist } from './managed-runtime-status.js';
import { import {
commitManagedTransaction, commitManagedTransaction,
prepareManagedFileChange, prepareManagedFileChange,
} from './managed-transaction.js'; } from './managed-transaction.js';
import { parseStrictJsonObject, type JsonObject } from './strict-json.js';
export function geminiConfigurationDirectory(): string { export function geminiConfigurationDirectory(): string {
const configuredHome = process.env.GEMINI_CLI_HOME; const configuredHome = process.env.GEMINI_CLI_HOME;
@@ -64,86 +65,15 @@ export async function writeGeminiDocument(rendered: RenderedGeminiDocument): Pro
}); });
} }
function requireNonEmptyString(value: unknown, field: string, configPath: string): string {
if (typeof value !== 'string' || value.trim().length === 0) {
throw new Error(`Elydora runtime config ${field} is invalid: ${configPath}`);
}
return value;
}
function validateRuntimeConfig(
config: JsonObject,
contract: GeminiRuntimeContract,
configPath: string,
): void {
const supported = new Set(['org_id', 'agent_id', 'kid', 'base_url', 'token', 'agent_name']);
const extra = Object.keys(config).find((key) => !supported.has(key));
if (extra) {
throw new Error(`Elydora runtime config has unsupported field "${extra}": ${configPath}`);
}
requireNonEmptyString(config.org_id, 'org_id', configPath);
requireNonEmptyString(config.kid, 'kid', configPath);
const agentId = requireNonEmptyString(config.agent_id, 'agent_id', configPath);
if (!sameGeminiAgentId(agentId, contract.agentId) || config.agent_name !== AGENT_KEY) {
throw new Error(`Elydora runtime identity does not match Gemini CLI hooks: ${configPath}`);
}
if (config.token !== undefined) requireNonEmptyString(config.token, 'token', configPath);
const rawBaseUrl = requireNonEmptyString(config.base_url, 'base_url', configPath);
let baseUrl: URL;
try {
baseUrl = new URL(rawBaseUrl);
} catch (error) {
throw new Error(`Elydora runtime config base_url is invalid: ${configPath}`, {
cause: error instanceof Error ? error : new Error(String(error)),
});
}
if (!['http:', 'https:'].includes(baseUrl.protocol)
|| !baseUrl.hostname
|| baseUrl.username
|| baseUrl.password
|| baseUrl.search
|| baseUrl.hash) {
throw new Error(`Elydora runtime config base_url is invalid: ${configPath}`);
}
}
function validatePrivateKey(contents: string, keyPath: string): void {
const bytes = Buffer.from(contents, 'base64url');
if (bytes.length !== 32 || bytes.toString('base64url') !== contents) {
throw new Error(`Elydora private key is invalid: ${keyPath}`);
}
}
async function runtimeContractExists(contract: GeminiRuntimeContract): Promise<boolean> {
const runtimeRoot = path.join(os.homedir(), '.elydora');
const agentDirectory = path.dirname(contract.guardPath);
if (!sameGeminiPath(path.dirname(agentDirectory), runtimeRoot)
|| !sameGeminiPath(contract.auditPath, path.join(agentDirectory, 'hook.js'))) return false;
if (!await inspectPhysicalDirectory(runtimeRoot, 'Elydora runtime directory')) return false;
if (!await inspectPhysicalDirectory(agentDirectory, 'Elydora agent runtime directory')) {
return false;
}
const configPath = path.join(agentDirectory, 'config.json');
const keyPath = path.join(agentDirectory, 'private.key');
const [config, key, guard, audit] = await Promise.all([
readPhysicalFile(configPath, 'Elydora runtime config'),
readPhysicalFile(keyPath, 'Elydora private key'),
readPhysicalFile(contract.guardPath, 'Elydora guard runtime'),
readPhysicalFile(contract.auditPath, 'Elydora audit runtime'),
]);
if (!config || !key || !guard || !audit) return false;
const parsed = parseStrictJsonObject(config.contents, `Elydora runtime config at ${configPath}`);
validateRuntimeConfig(parsed, contract, configPath);
validatePrivateKey(key.contents, keyPath);
return guard.contents.length > 0 && audit.contents.length > 0;
}
export async function geminiRuntimeFilesExist( export async function geminiRuntimeFilesExist(
contracts: readonly GeminiRuntimeContract[], contracts: readonly GeminiRuntimeContract[],
): Promise<boolean> { ): Promise<boolean> {
for (const contract of contracts) { for (const contract of contracts) {
if (await runtimeContractExists(contract)) return true; const exists = await managedRuntimeFilesExist(contract, AGENT_KEY, {
guardOptions: GUARD_OPTIONS,
auditOptions: AUDIT_OPTIONS,
});
if (exists) return true;
} }
return false; return false;
} }
-3
View File
@@ -1,8 +1,5 @@
import { PROTECTED_RUNTIME_READER } from './runtime-reader-template.js'; import { PROTECTED_RUNTIME_READER } from './runtime-reader-template.js';
export { generateGuardScript } from './guard-template.js';
export type { GuardScriptOptions } from './guard-template.js';
export interface HookScriptOptions { export interface HookScriptOptions {
readonly failClosed?: boolean; readonly failClosed?: boolean;
readonly nativePayload?: boolean; readonly nativePayload?: boolean;
+1 -14
View File
@@ -1,8 +1,7 @@
import { constants } from 'node:fs'; import { constants } from 'node:fs';
import fsp from 'node:fs/promises'; import fsp from 'node:fs/promises';
import type { FileHandle } from 'node:fs/promises'; import type { FileHandle } from 'node:fs/promises';
import { asError, errorMessage, hasCode, MAX_SOURCE_BYTES } from './common.js';
const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
export interface FileSnapshot { export interface FileSnapshot {
readonly contents: string; readonly contents: string;
@@ -11,18 +10,6 @@ export interface FileSnapshot {
readonly mode: number; readonly mode: number;
} }
function asError(error: unknown): Error {
return error instanceof Error ? error : new Error(String(error));
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function hasCode(error: unknown, code: string): boolean {
return typeof error === 'object' && error !== null && 'code' in error && error.code === code;
}
export async function readPhysicalFile( export async function readPhysicalFile(
filePath: string, filePath: string,
label: string, label: string,
+1 -17
View File
@@ -2,6 +2,7 @@ import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { ensurePrivateDirectory, resolvePrivateChildDirectory } from '../runtime-paths.js'; import { ensurePrivateDirectory, resolvePrivateChildDirectory } from '../runtime-paths.js';
import type { InstallConfig } from './base.js'; import type { InstallConfig } from './base.js';
import { MAX_CONFIG_BYTES, MAX_SECRET_BYTES, sameAgentId, samePath } from './common.js';
import { generateGuardScript, type GuardScriptOptions } from './guard-template.js'; import { generateGuardScript, type GuardScriptOptions } from './guard-template.js';
import { generateHookScript, type HookScriptOptions } from './hook-template.js'; import { generateHookScript, type HookScriptOptions } from './hook-template.js';
import { import {
@@ -19,9 +20,6 @@ import {
} from './managed-transaction.js'; } from './managed-transaction.js';
import { parseStrictJsonObject } from './strict-json.js'; import { parseStrictJsonObject } from './strict-json.js';
const MAX_SECRET_BYTES = 64 * 1024;
const MAX_CONFIG_BYTES = 512 * 1024;
export interface ManagedRuntimePaths { export interface ManagedRuntimePaths {
readonly runtimeRoot: string; readonly runtimeRoot: string;
readonly agentDirectory: string; readonly agentDirectory: string;
@@ -79,14 +77,6 @@ interface RuntimeArtifactLocation {
export type { RenameFile }; export type { RenameFile };
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 validateInstallConfig(config: InstallConfig, agentKey: string): void { function validateInstallConfig(config: InstallConfig, agentKey: string): void {
for (const [field, value] of [ for (const [field, value] of [
['agentName', config.agentName], ['agentName', config.agentName],
@@ -146,12 +136,6 @@ export function managedRuntimePaths(
}; };
} }
function sameAgentId(left: unknown, right: string): boolean {
return typeof left === 'string' && (process.platform === 'win32'
? left.toLowerCase() === right.toLowerCase()
: left === right);
}
async function validateRuntimeIdentity( async function validateRuntimeIdentity(
paths: ManagedRuntimePaths, paths: ManagedRuntimePaths,
agentKey: string, agentKey: string,
+22 -7
View File
@@ -2,12 +2,10 @@ import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { generateGuardScript, type GuardScriptOptions } from './guard-template.js'; import { generateGuardScript, type GuardScriptOptions } from './guard-template.js';
import { generateHookScript, type HookScriptOptions } from './hook-template.js'; import { generateHookScript, type HookScriptOptions } from './hook-template.js';
import { MAX_CONFIG_BYTES, MAX_SECRET_BYTES, sameAgentId, samePath } from './common.js';
import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js'; import { inspectPhysicalDirectory, readPhysicalFile } from './managed-files.js';
import { samePath } from './managed-installation.js';
import { parseStrictJsonObject, type JsonObject } from './strict-json.js'; import { parseStrictJsonObject, type JsonObject } from './strict-json.js';
const MAX_SECRET_BYTES = 64 * 1024;
const MAX_CONFIG_BYTES = 512 * 1024;
const GUARD_SCRIPT = 'guard.js'; const GUARD_SCRIPT = 'guard.js';
const AUDIT_SCRIPT = 'hook.js'; const AUDIT_SCRIPT = 'hook.js';
@@ -22,10 +20,6 @@ export interface ManagedRuntimeStatusOptions {
readonly auditOptions?: HookScriptOptions; readonly auditOptions?: HookScriptOptions;
} }
function sameAgentId(left: string, right: string): boolean {
return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right;
}
function requireString(value: unknown, field: string, configPath: string): string { function requireString(value: unknown, field: string, configPath: string): string {
if (typeof value !== 'string' || value.trim().length === 0) { if (typeof value !== 'string' || value.trim().length === 0) {
throw new Error(`Elydora runtime config ${field} is invalid: ${configPath}`); throw new Error(`Elydora runtime config ${field} is invalid: ${configPath}`);
@@ -117,3 +111,24 @@ export async function managedRuntimeFilesExist(
options.auditOptions ?? { nativePayload: true }, options.auditOptions ?? { nativePayload: true },
); );
} }
// Presence-only check: identity mismatch reports false; parse failures still throw.
export async function managedRuntimePresent(
contract: ManagedRuntimeContract,
agentKey: string,
): Promise<boolean> {
const agentDirectory = path.dirname(contract.guardPath);
const configPath = path.join(agentDirectory, 'config.json');
const snapshot = await readPhysicalFile(configPath, 'Elydora runtime config', MAX_CONFIG_BYTES);
if (!snapshot) return false;
const config = parseStrictJsonObject(snapshot.contents, `Elydora runtime config at ${configPath}`);
if (config.agent_name !== agentKey || !sameAgentId(config.agent_id, contract.agentId)) {
return false;
}
const files = await Promise.all([
readPhysicalFile(contract.guardPath, 'Elydora guard runtime'),
readPhysicalFile(contract.auditPath, 'Elydora audit runtime'),
readPhysicalFile(path.join(agentDirectory, 'private.key'), 'Elydora private key', MAX_SECRET_BYTES),
]);
return files.every(Boolean);
}
+17 -43
View File
@@ -2,14 +2,13 @@ import { randomUUID } from 'node:crypto';
import fsp from 'node:fs/promises'; import fsp from 'node:fs/promises';
import type { FileHandle } from 'node:fs/promises'; import type { FileHandle } from 'node:fs/promises';
import path from 'node:path'; import path from 'node:path';
import { asError, errorMessage, hasCode, MAX_SOURCE_BYTES } from './common.js';
import { import {
inspectPhysicalDirectory, inspectPhysicalDirectory,
readPhysicalFile, readPhysicalFile,
type FileSnapshot, type FileSnapshot,
} from './managed-files.js'; } from './managed-files.js';
const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
export interface ManagedChangeSpec { export interface ManagedChangeSpec {
readonly filePath: string; readonly filePath: string;
readonly label: string; readonly label: string;
@@ -60,18 +59,6 @@ interface StagedChange {
export type RenameFile = (source: string, destination: string) => Promise<void>; export type RenameFile = (source: string, destination: string) => Promise<void>;
function asError(error: unknown): Error {
return error instanceof Error ? error : new Error(String(error));
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function hasCode(error: unknown, code: string): boolean {
return typeof error === 'object' && error !== null && 'code' in error && error.code === code;
}
function targetKey(filePath: string): string { function targetKey(filePath: string): string {
const resolved = path.resolve(filePath); const resolved = path.resolve(filePath);
return process.platform === 'win32' ? resolved.toLowerCase() : resolved; return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
@@ -113,16 +100,20 @@ export async function prepareManagedFileChange(
}; };
} }
async function assertUnchanged(change: ManagedFileChange, operationName: string): Promise<void> { function sameSnapshot(current: FileSnapshot | undefined, original: FileSnapshot | undefined): boolean {
const current = await readPhysicalFile(change.filePath, change.label, change.maximumBytes); if (!current || !original) return !current && !original;
if ((!current && change.original) return current.contents === original.contents
|| (current && !change.original) && current.device === original.device
|| (current && change.original && ( && current.inode === original.inode;
current.contents !== change.original.contents }
|| current.device !== change.original.device
|| current.inode !== change.original.inode async function assertUnchanged(
))) { target: ManagedFilePrecondition,
throw new Error(`${change.label} changed during ${operationName}: ${change.filePath}`); operationName: string,
): Promise<void> {
const current = await readPhysicalFile(target.filePath, target.label, target.maximumBytes);
if (!sameSnapshot(current, target.original)) {
throw new Error(`${target.label} changed during ${operationName}: ${target.filePath}`);
} }
} }
@@ -131,20 +122,7 @@ async function assertPreconditions(
operationName: string, operationName: string,
): Promise<void> { ): Promise<void> {
for (const condition of transaction.preconditions ?? []) { for (const condition of transaction.preconditions ?? []) {
const current = await readPhysicalFile( await assertUnchanged(condition, operationName);
condition.filePath,
condition.label,
condition.maximumBytes,
);
if ((!current && condition.original)
|| (current && !condition.original)
|| (current && condition.original && (
current.contents !== condition.original.contents
|| current.device !== condition.original.device
|| current.inode !== condition.original.inode
))) {
throw new Error(`${condition.label} changed during ${operationName}: ${condition.filePath}`);
}
} }
} }
@@ -285,11 +263,7 @@ async function assertCommittedUnchanged(staged: StagedChange): Promise<void> {
} }
return; return;
} }
const committed = staged.committedSnapshot; if (!current || !sameSnapshot(current, staged.committedSnapshot)) {
if (!current || !committed
|| current.contents !== committed.contents
|| current.device !== committed.device
|| current.inode !== committed.inode) {
throw new Error( throw new Error(
`${staged.change.label} changed during transaction recovery: ${staged.change.filePath}`, `${staged.change.label} changed during transaction recovery: ${staged.change.filePath}`,
); );
+1 -1
View File
@@ -1,7 +1,7 @@
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import type { HookScriptOptions } from './hook-template.js'; import type { HookScriptOptions } from './hook-template.js';
import { samePath } from './managed-installation.js'; import { samePath } from './common.js';
import { parseStrictJsonObject } from './strict-json.js'; import { parseStrictJsonObject } from './strict-json.js';
export const AGENT_KEY = 'opencode'; export const AGENT_KEY = 'opencode';
+128
View File
@@ -0,0 +1,128 @@
import path from 'node:path';
import { samePath } from './common.js';
export interface ParsedArgument {
readonly value: string;
readonly next: number;
}
export type CommandParts = readonly [executable: string, script: string];
const POSIX_APOSTROPHE = `'"'"'`;
const POWERSHELL_EXIT_SUFFIX = '; exit $LASTEXITCODE';
const ENCODED_COMMAND_FLAGS = '-NoLogo -NoProfile -NonInteractive -EncodedCommand';
export function quotePosix(value: string): string {
return `'${value.replaceAll("'", POSIX_APOSTROPHE)}'`;
}
export function quotePowerShell(value: string): string {
return `'${value.replaceAll("'", "''")}'`;
}
export function windowsPowerShellPath(): string {
const configuredRoot = process.platform === 'win32' ? process.env.SystemRoot : undefined;
const systemRoot = configuredRoot
&& path.win32.isAbsolute(configuredRoot)
&& !/["%\r\n]/.test(configuredRoot)
? configuredRoot
: 'C:\\Windows';
return path.win32.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
}
export function posixSource(scriptPath: string): string {
return `${quotePosix(process.execPath)} ${quotePosix(scriptPath)}`;
}
export function powerShellSource(scriptPath: string): string {
return `& ${quotePowerShell(process.execPath)} ${quotePowerShell(scriptPath)}${POWERSHELL_EXIT_SUFFIX}`;
}
export function encodePowerShellSource(scriptPath: string): string {
return Buffer.from(powerShellSource(scriptPath), 'utf16le').toString('base64');
}
export function encodedWindowsCommand(scriptPath: string): string {
return `"${windowsPowerShellPath()}" ${ENCODED_COMMAND_FLAGS} ${encodePowerShellSource(scriptPath)}`;
}
// The running executable, or a binary named node (node.exe case-insensitive on Windows).
export function isNodeExecutable(filePath: string): boolean {
if (samePath(filePath, process.execPath)) return true;
const basename = path.basename(filePath);
return basename === 'node' || basename.toLowerCase() === 'node.exe';
}
export function isPowerShellExecutable(filePath: string): boolean {
return path.win32.isAbsolute(filePath)
&& path.win32.basename(filePath).toLowerCase() === 'powershell.exe';
}
export function readPosixArgument(command: string, start: number): ParsedArgument | undefined {
if (command[start] !== "'") return undefined;
let value = '';
for (let index = start + 1; index < command.length;) {
if (command.startsWith(POSIX_APOSTROPHE, index)) {
value += "'";
index += POSIX_APOSTROPHE.length;
continue;
}
if (command[index] === "'") return { value, next: index + 1 };
value += command[index];
index += 1;
}
return undefined;
}
export function parsePosixCommand(command: string): CommandParts | 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;
}
export function parsePowerShellSource(source: string): CommandParts | undefined {
if (!source.startsWith('& ')) return undefined;
const executable = readPowerShellArgument(source, 2);
if (!executable || source[executable.next] !== ' ') return undefined;
const script = readPowerShellArgument(source, executable.next + 1);
if (!script || source.slice(script.next) !== POWERSHELL_EXIT_SUFFIX) return undefined;
return [executable.value, script.value];
}
export function decodePowerShellSource(encoded: string): CommandParts | undefined {
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) return undefined;
const buffer = Buffer.from(encoded, 'base64');
if (buffer.toString('base64') !== encoded || buffer.length % 2 !== 0) return undefined;
return parsePowerShellSource(buffer.toString('utf16le'));
}
export function parseEncodedWindowsCommand(command: string): CommandParts | undefined {
const match = /^"([^"\r\n]+)" -NoLogo -NoProfile -NonInteractive -EncodedCommand ([A-Za-z0-9+/]+={0,2})$/.exec(command);
if (!match || !isPowerShellExecutable(match[1])) return undefined;
return decodePowerShellSource(match[2]);
}
export function parseLegacyWindowsCommand(command: string): CommandParts | undefined {
const match = /^"([^"\r\n]+)" "([^"\r\n]+)"$/.exec(command);
return match ? [match[1], match[2]] : undefined;
}
+33 -31
View File
@@ -1,7 +1,3 @@
// ---------------------------------------------------------------------------
// Enums / status types
// ---------------------------------------------------------------------------
export type AgentStatus = 'active' | 'frozen' | 'revoked'; export type AgentStatus = 'active' | 'frozen' | 'revoked';
export type KeyStatus = 'active' | 'retired' | 'revoked'; export type KeyStatus = 'active' | 'retired' | 'revoked';
export type ExportStatus = 'queued' | 'running' | 'done' | 'failed'; export type ExportStatus = 'queued' | 'running' | 'done' | 'failed';
@@ -37,13 +33,16 @@ export type AdminAction =
| 'agent.register' | 'agent.update' | 'agent.freeze' | 'agent.unfreeze' | 'agent.register' | 'agent.update' | 'agent.freeze' | 'agent.unfreeze'
| 'agent.revoke' | 'agent.delete' | 'key.revoke' | 'export.create' | 'agent.revoke' | 'agent.delete' | 'key.revoke' | 'export.create'
| 'org.create' | 'org.update' | 'org.create' | 'org.update'
| 'member.invite' | 'member.remove' | 'member.role_change' | 'member.invite' | 'invitation.cancel' | 'member.remove' | 'member.role_change'
| 'agent.assign' | 'agent.unassign'; | 'agent.assign' | 'agent.unassign'
| 'webhook.register' | 'webhook.delete';
export type ErrorCode = export type ErrorCode =
| 'INVALID_SIGNATURE' | 'INVALID_SIGNATURE'
| 'UNKNOWN_AGENT' | 'UNKNOWN_AGENT'
| 'KEY_REVOKED' | 'KEY_REVOKED'
| 'KEY_RETIRED'
| 'AGENT_FROZEN' | 'AGENT_FROZEN'
| 'AGENT_REVOKED'
| 'TTL_EXPIRED' | 'TTL_EXPIRED'
| 'REPLAY_DETECTED' | 'REPLAY_DETECTED'
| 'PREV_HASH_MISMATCH' | 'PREV_HASH_MISMATCH'
@@ -55,10 +54,6 @@ export type ErrorCode =
| 'NOT_FOUND' | 'NOT_FOUND'
| 'VALIDATION_ERROR'; | 'VALIDATION_ERROR';
// ---------------------------------------------------------------------------
// Entities
// ---------------------------------------------------------------------------
export interface Agent { export interface Agent {
readonly agent_id: string; readonly agent_id: string;
readonly org_id: string; readonly org_id: string;
@@ -168,10 +163,6 @@ export interface Export {
readonly completed_at: number | null; readonly completed_at: number | null;
} }
// ---------------------------------------------------------------------------
// Protocol types
// ---------------------------------------------------------------------------
export interface EOR { export interface EOR {
readonly op_version: '1.0'; readonly op_version: '1.0';
readonly operation_id: string; readonly operation_id: string;
@@ -205,10 +196,6 @@ export interface EAR {
readonly elydora_signature: string; readonly elydora_signature: string;
} }
// ---------------------------------------------------------------------------
// API request/response types
// ---------------------------------------------------------------------------
export interface RegisterAgentRequest { export interface RegisterAgentRequest {
readonly agent_id: string; readonly agent_id: string;
readonly integration_type: IntegrationType; readonly integration_type: IntegrationType;
@@ -238,6 +225,7 @@ export interface SubmitOperationResponse {
export interface GetOperationResponse { export interface GetOperationResponse {
readonly operation: Operation; readonly operation: Operation;
readonly receipt?: Receipt; readonly receipt?: Receipt;
readonly payload?: Record<string, unknown> | string;
} }
export interface VerifyOperationResponse { export interface VerifyOperationResponse {
@@ -327,15 +315,22 @@ export interface DeleteAgentResponse {
readonly deleted: boolean; readonly deleted: boolean;
} }
export interface Webhook {
readonly webhook_id: string;
readonly org_id: string;
readonly endpoint_url: string;
readonly events: string[];
readonly status: 'active' | 'disabled';
readonly created_at: number;
readonly updated_at: number;
}
export interface ListWebhooksResponse { export interface ListWebhooksResponse {
readonly webhooks: unknown[]; readonly webhooks: Webhook[];
} }
export interface RegisterWebhookResponse { export interface RegisterWebhookResponse {
readonly webhook_id: string; readonly webhook: Webhook;
readonly endpoint_url: string;
readonly events: string[];
readonly created_at: number;
} }
export interface ListMembersResponse { export interface ListMembersResponse {
@@ -357,16 +352,26 @@ export interface DeepHealthResponse {
readonly status: 'healthy' | 'degraded'; readonly status: 'healthy' | 'degraded';
readonly version: string; readonly version: string;
readonly protocol_version: string; readonly protocol_version: string;
readonly capabilities: Record<string, string>;
readonly timestamp: number; readonly timestamp: number;
readonly dependencies: { readonly dependencies: {
readonly d1: { status: 'ok' | 'failed'; latency_ms: number; error?: string }; readonly d1: { status: 'ok' | 'failed'; latency_ms: number };
readonly r2: { status: 'ok' | 'failed'; latency_ms: number; error?: string }; readonly auth_storage: { status: 'ok' | 'failed'; latency_ms: number; contract_phase?: 'expand' | 'contract' };
readonly kv: { status: 'ok' | 'failed'; latency_ms: number; error?: string }; readonly r2: { status: 'ok' | 'failed'; latency_ms: number };
readonly kv: { status: 'ok' | 'failed'; latency_ms: number };
}; };
} }
export interface GetMeResponse { export interface GetMeResponse {
readonly user: User; readonly user: Omit<User, 'org_id'> & {
readonly org_id: string | null;
readonly onboarding_completed: boolean;
};
readonly current_organization: {
readonly org_id: string | null;
readonly ba_org_id: string | null;
readonly role: RbacRole;
};
} }
export interface IssueApiTokenResponse { export interface IssueApiTokenResponse {
@@ -385,6 +390,7 @@ export interface HealthResponse {
readonly status: string; readonly status: string;
readonly version: string; readonly version: string;
readonly protocol_version: string; readonly protocol_version: string;
readonly capabilities: Record<string, string>;
readonly timestamp: number; readonly timestamp: number;
} }
@@ -421,10 +427,6 @@ export interface ErrorResponse {
}; };
} }
// ---------------------------------------------------------------------------
// Client configuration
// ---------------------------------------------------------------------------
export interface ElydoraClientConfig { export interface ElydoraClientConfig {
readonly orgId: string; readonly orgId: string;
readonly agentId: string; readonly agentId: string;
+1 -19
View File
@@ -1,17 +1,10 @@
import crypto from 'node:crypto'; import crypto from 'node:crypto';
/** // UUIDv7 (RFC 9562): 48-bit ms timestamp, version 7, variant 10, 74 random bits
* Generate a UUIDv7 (time-ordered UUID per RFC 9562).
*
* Layout (128 bits):
* 48-bit Unix timestamp (ms) | 4-bit version (7) | 12-bit rand_a
* 2-bit variant (10) | 62-bit rand_b
*/
export function uuidv7(): string { export function uuidv7(): string {
const now = Date.now(); const now = Date.now();
const random = crypto.randomBytes(10); const random = crypto.randomBytes(10);
// Bytes 0-5: 48-bit timestamp (ms)
const bytes = Buffer.alloc(16); const bytes = Buffer.alloc(16);
bytes[0] = (now / 2 ** 40) & 0xff; bytes[0] = (now / 2 ** 40) & 0xff;
bytes[1] = (now / 2 ** 32) & 0xff; bytes[1] = (now / 2 ** 32) & 0xff;
@@ -20,11 +13,9 @@ export function uuidv7(): string {
bytes[4] = (now / 2 ** 8) & 0xff; bytes[4] = (now / 2 ** 8) & 0xff;
bytes[5] = now & 0xff; bytes[5] = now & 0xff;
// Bytes 6-7: version (0111) + 12 bits random
bytes[6] = 0x70 | (random[0]! & 0x0f); bytes[6] = 0x70 | (random[0]! & 0x0f);
bytes[7] = random[1]!; bytes[7] = random[1]!;
// Bytes 8-15: variant (10) + 62 bits random
bytes[8] = 0x80 | (random[2]! & 0x3f); bytes[8] = 0x80 | (random[2]! & 0x3f);
bytes[9] = random[3]!; bytes[9] = random[3]!;
bytes[10] = random[4]!; bytes[10] = random[4]!;
@@ -44,25 +35,16 @@ export function uuidv7(): string {
); );
} }
/**
* Generate a random nonce: 16 random bytes, base64url encoded.
*/
export function generateNonce(): string { export function generateNonce(): string {
const bytes = crypto.randomBytes(16); const bytes = crypto.randomBytes(16);
return base64urlEncode(bytes); return base64urlEncode(bytes);
} }
/**
* Encode a Buffer or Uint8Array to base64url (no padding, RFC 4648 section 5).
*/
export function base64urlEncode(data: Buffer | Uint8Array): string { export function base64urlEncode(data: Buffer | Uint8Array): string {
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data); const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
return buf.toString('base64url'); return buf.toString('base64url');
} }
/**
* Decode a base64url string (no padding) to a Buffer.
*/
export function base64urlDecode(input: string): Buffer { export function base64urlDecode(input: string): Buffer {
return Buffer.from(input, 'base64url'); return Buffer.from(input, 'base64url');
} }
+1 -1
View File
@@ -6,7 +6,7 @@ import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import test from 'node:test'; import test from 'node:test';
import { generateGuardScript } from '../dist/plugins/hook-template.js'; import { generateGuardScript } from '../dist/plugins/guard-template.js';
const AGENT_ID = 'agent-1'; const AGENT_ID = 'agent-1';