utils.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. /**
  2. * CodeGraph Utilities
  3. *
  4. * Common utility functions for memory management, concurrency, batching,
  5. * and security validation.
  6. *
  7. * @module utils
  8. *
  9. * @example
  10. * ```typescript
  11. * import { Mutex, processInBatches, MemoryMonitor, validatePathWithinRoot } from 'codegraph';
  12. *
  13. * // Use mutex for concurrent safety
  14. * const mutex = new Mutex();
  15. * await mutex.withLock(async () => {
  16. * await performCriticalOperation();
  17. * });
  18. *
  19. * // Process items in batches to manage memory
  20. * const results = await processInBatches(items, 100, async (item) => {
  21. * return await processItem(item);
  22. * });
  23. *
  24. * // Monitor memory usage
  25. * const monitor = new MemoryMonitor(512, (usage) => {
  26. * console.warn(`Memory usage exceeded 512MB: ${usage / 1024 / 1024}MB`);
  27. * });
  28. * monitor.start();
  29. * ```
  30. */
  31. import * as fs from 'fs';
  32. import * as path from 'path';
  33. // ============================================================
  34. // SECURITY UTILITIES
  35. // ============================================================
  36. /**
  37. * Sensitive system directories that should never be used as project roots.
  38. * Checked on all platforms; non-applicable paths are harmlessly skipped.
  39. */
  40. const SENSITIVE_PATHS = new Set([
  41. '/', '/etc', '/usr', '/bin', '/sbin', '/var', '/tmp', '/dev', '/proc', '/sys',
  42. '/root', '/boot', '/lib', '/lib64', '/opt',
  43. 'c:\\', 'c:\\windows', 'c:\\windows\\system32',
  44. ]);
  45. /**
  46. * Config "languages" whose nodes are pure key/value DATA lifted from a config
  47. * file (e.g. Spring `application.{yml,properties}`), not source code.
  48. */
  49. export const CONFIG_LEAF_LANGUAGES: ReadonlySet<string> = new Set(['yaml', 'properties']);
  50. /**
  51. * A config-leaf node is a single key lifted out of a pure config/data file —
  52. * `kind: 'constant'` in a {@link CONFIG_LEAF_LANGUAGES} language. Its on-disk
  53. * line is `key = <value>`, and that value is routinely a secret (DB password,
  54. * API key, JDBC URL with embedded creds). CodeGraph must surface the KEY only
  55. * and never read/return the value, or it pushes secrets into agent context
  56. * unbidden — the value isn't needed for resolution, and an agent that genuinely
  57. * needs it can read the file directly. (#383)
  58. */
  59. export function isConfigLeafNode(node: { kind: string; language?: string }): boolean {
  60. return node.kind === 'constant' && !!node.language && CONFIG_LEAF_LANGUAGES.has(node.language);
  61. }
  62. /**
  63. * Whether `child` is `parent` itself or sits underneath it. Case-insensitive on
  64. * Windows — NTFS is case-insensitive, and realpathSync can hand back a different
  65. * case than the lexical root, which would otherwise false-reject a valid file.
  66. */
  67. function isWithinDir(child: string, parent: string): boolean {
  68. let c = child;
  69. let p = parent;
  70. if (process.platform === 'win32') {
  71. c = c.toLowerCase();
  72. p = p.toLowerCase();
  73. }
  74. return c === p || c.startsWith(p + path.sep);
  75. }
  76. /**
  77. * The lexical half of {@link validatePathWithinRoot}, on its own.
  78. *
  79. * Returns the resolved absolute path when `filePath` stays inside
  80. * `projectRoot` after `../` segments are applied, or null when it escapes.
  81. * No filesystem access — for callers on a hot path that only need to refuse a
  82. * lexical escape, and for which the realpath half would be both unnecessary
  83. * and far too expensive (the existence probe in resolution's `fileExists`,
  84. * #1631: two `realpathSync` calls per probe made it ~70x slower).
  85. *
  86. * This is NOT a substitute for `validatePathWithinRoot` on any path whose
  87. * contents get served — those must keep the symlink-aware check (#527).
  88. */
  89. export function lexicalPathWithinRoot(projectRoot: string, filePath: string): string | null {
  90. const resolved = path.resolve(projectRoot, filePath);
  91. return isWithinDir(resolved, path.resolve(projectRoot)) ? resolved : null;
  92. }
  93. /**
  94. * Validate that a file path stays within the project root, resolving symlinks.
  95. *
  96. * Two layers: a cheap lexical check that catches `../` traversal, then a
  97. * realpath check that catches symlink escapes — an in-repo symlink whose
  98. * logical path is inside the root but whose real target points outside it
  99. * (issue #527). A symlink that stays within the root is still allowed, so
  100. * legitimate in-tree symlinks keep working. Both content-serving read sinks
  101. * (codegraph_node `includeCode`, codegraph_explore source) go through here, so
  102. * this is the chokepoint that keeps out-of-root file contents from leaking.
  103. *
  104. * `allowSymlinkEscape` waives **only** the realpath-escape rejection (the
  105. * lexical `../` guard still applies) for the INDEXING read path. The directory
  106. * walk deliberately descends into in-root symlinks whose targets live outside
  107. * the root (e.g. a `game/` symlink in a Dota custom-game tree, #935); discovery
  108. * and the reader must agree, or every file the walk enumerated fails to index.
  109. * Indexing only reads paths it just discovered, into a local index — it never
  110. * serves them to an agent, so this does not widen the #527 leak surface. The
  111. * content-serving sinks must never pass this flag.
  112. *
  113. * @param projectRoot - The project root directory
  114. * @param filePath - The (relative or absolute) file path to validate
  115. * @param options.allowSymlinkEscape - Follow in-root symlinks out of the root
  116. * (indexing read path only); defaults to the strict, leak-safe behavior.
  117. * @returns The resolved absolute path (realpath when it exists), or null if it
  118. * escapes the root
  119. */
  120. export function validatePathWithinRoot(
  121. projectRoot: string,
  122. filePath: string,
  123. options?: { allowSymlinkEscape?: boolean }
  124. ): string | null {
  125. // 1. Lexical containment — cheap, catches `../` traversal. Applies even on
  126. // the indexing read path: a crafted `../` escape is still rejected.
  127. const resolved = lexicalPathWithinRoot(projectRoot, filePath);
  128. if (resolved === null) {
  129. return null;
  130. }
  131. const normalizedRoot = path.resolve(projectRoot);
  132. // 2. Symlink-aware containment — resolve symlinks on both sides and re-check,
  133. // so an in-repo symlink whose real target escapes the root is rejected.
  134. // The indexing read path (allowSymlinkEscape) skips only this rejection so
  135. // it stays consistent with the directory walk, which already followed the
  136. // in-root symlink to enumerate these files (#935).
  137. try {
  138. const realRoot = fs.realpathSync(normalizedRoot);
  139. const realResolved = fs.realpathSync(resolved);
  140. if (options?.allowSymlinkEscape) {
  141. return realResolved;
  142. }
  143. return isWithinDir(realResolved, realRoot) ? realResolved : null;
  144. } catch (err) {
  145. // ENOENT: the path doesn't exist yet (a file about to be written, or an
  146. // index entry for a since-deleted file) — no symlink to follow, and the
  147. // lexical check already passed, so allow the lexical path. Any other
  148. // resolution failure (ELOOP, EACCES, …) is treated as unsafe → reject.
  149. if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
  150. return resolved;
  151. }
  152. return null;
  153. }
  154. }
  155. /**
  156. * Validate that a path is a safe project root directory.
  157. *
  158. * Rejects sensitive system directories and ensures the path is
  159. * a real, existing directory. Used at MCP and API entry points
  160. * to prevent arbitrary directory access.
  161. *
  162. * @param dirPath - The path to validate
  163. * @returns An error message if invalid, or null if valid
  164. */
  165. export function validateProjectPath(dirPath: string): string | null {
  166. const resolved = path.resolve(dirPath);
  167. // Block sensitive system directories
  168. if (SENSITIVE_PATHS.has(resolved) || SENSITIVE_PATHS.has(resolved.toLowerCase())) {
  169. return `Refusing to operate on sensitive system directory: ${resolved}`;
  170. }
  171. // Also block common sensitive home subdirectories
  172. const homeDir = require('os').homedir();
  173. const sensitiveHomeDirs = ['.ssh', '.gnupg', '.aws', '.config'];
  174. for (const dir of sensitiveHomeDirs) {
  175. const sensitivePath = path.join(homeDir, dir);
  176. if (resolved === sensitivePath || resolved.startsWith(sensitivePath + path.sep)) {
  177. return `Refusing to operate on sensitive directory: ${resolved}`;
  178. }
  179. }
  180. // Verify it's a real directory
  181. try {
  182. const stats = fs.statSync(resolved);
  183. if (!stats.isDirectory()) {
  184. return `Path is not a directory: ${resolved}`;
  185. }
  186. } catch {
  187. return `Path does not exist or is not accessible: ${resolved}`;
  188. }
  189. return null;
  190. }
  191. /**
  192. * Safely parse JSON with a fallback value.
  193. * Prevents crashes from corrupted database metadata.
  194. */
  195. export function safeJsonParse<T>(value: string, fallback: T): T {
  196. try {
  197. return JSON.parse(value);
  198. } catch {
  199. return fallback;
  200. }
  201. }
  202. /**
  203. * Clamp a numeric value to a range.
  204. * Used to enforce sane limits on MCP tool inputs.
  205. */
  206. export function clamp(value: number, min: number, max: number): number {
  207. return Math.max(min, Math.min(max, value));
  208. }
  209. /**
  210. * Normalize a file path to use forward slashes.
  211. * Fixes Windows backslash paths so glob matching works consistently.
  212. */
  213. export function normalizePath(filePath: string): string {
  214. return filePath.replace(/\\/g, '/');
  215. }
  216. /**
  217. * Cross-process file lock using a lock file with PID tracking.
  218. *
  219. * Prevents multiple processes (e.g., git hooks, CLI, MCP server) from
  220. * writing to the same database simultaneously.
  221. */
  222. export class FileLock {
  223. private lockPath: string;
  224. private held = false;
  225. /** Locks older than this are considered stale regardless of PID status */
  226. private static readonly STALE_TIMEOUT_MS = 2 * 60 * 1000; // 2 minutes
  227. constructor(lockPath: string) {
  228. this.lockPath = lockPath;
  229. }
  230. /**
  231. * Acquire the lock. Throws if the lock is held by another live process.
  232. */
  233. acquire(): void {
  234. // Check for existing lock
  235. if (fs.existsSync(this.lockPath)) {
  236. try {
  237. const content = fs.readFileSync(this.lockPath, 'utf-8').trim();
  238. const pid = parseInt(content, 10);
  239. const stat = fs.statSync(this.lockPath);
  240. const lockAge = Date.now() - stat.mtimeMs;
  241. // Treat locks older than the timeout as stale, regardless of PID
  242. if (lockAge < FileLock.STALE_TIMEOUT_MS && !isNaN(pid) && this.isProcessAlive(pid)) {
  243. throw new Error(
  244. `CodeGraph database is locked by another process (PID ${pid}). ` +
  245. `If this is stale, run 'codegraph unlock' or delete ${this.lockPath}`
  246. );
  247. }
  248. // Stale lock (dead process or timed out) - remove it
  249. fs.unlinkSync(this.lockPath);
  250. } catch (err) {
  251. if (err instanceof Error && err.message.includes('locked by another')) {
  252. throw err;
  253. }
  254. // Other errors reading lock file - try to remove it
  255. try { fs.unlinkSync(this.lockPath); } catch { /* ignore */ }
  256. }
  257. }
  258. // Write our PID to the lock file using exclusive create flag
  259. try {
  260. fs.writeFileSync(this.lockPath, String(process.pid), { flag: 'wx' });
  261. this.held = true;
  262. } catch (err: any) {
  263. if (err.code === 'EEXIST') {
  264. // Race condition: another process grabbed the lock between our check and write
  265. throw new Error(
  266. 'CodeGraph database is locked by another process. ' +
  267. `If this is stale, run 'codegraph unlock' or delete ${this.lockPath}`
  268. );
  269. }
  270. throw err;
  271. }
  272. }
  273. /**
  274. * Release the lock
  275. */
  276. release(): void {
  277. if (!this.held) return;
  278. try {
  279. // Only remove if we still own it (check PID)
  280. const content = fs.readFileSync(this.lockPath, 'utf-8').trim();
  281. if (parseInt(content, 10) === process.pid) {
  282. fs.unlinkSync(this.lockPath);
  283. }
  284. } catch {
  285. // Lock file already gone - that's fine
  286. }
  287. this.held = false;
  288. }
  289. /**
  290. * Execute a function while holding the lock
  291. */
  292. withLock<T>(fn: () => T): T {
  293. this.acquire();
  294. try {
  295. return fn();
  296. } finally {
  297. this.release();
  298. }
  299. }
  300. /**
  301. * Execute an async function while holding the lock
  302. */
  303. async withLockAsync<T>(fn: () => Promise<T>): Promise<T> {
  304. this.acquire();
  305. try {
  306. return await fn();
  307. } finally {
  308. this.release();
  309. }
  310. }
  311. /**
  312. * Check if a process is still running
  313. */
  314. private isProcessAlive(pid: number): boolean {
  315. try {
  316. process.kill(pid, 0);
  317. return true;
  318. } catch {
  319. return false;
  320. }
  321. }
  322. }
  323. /**
  324. * Process items in batches to manage memory
  325. *
  326. * @param items - Array of items to process
  327. * @param batchSize - Number of items per batch
  328. * @param processor - Function to process each item
  329. * @param onBatchComplete - Optional callback after each batch
  330. * @returns Array of results
  331. */
  332. export async function processInBatches<T, R>(
  333. items: T[],
  334. batchSize: number,
  335. processor: (item: T, index: number) => Promise<R>,
  336. onBatchComplete?: (completed: number, total: number) => void
  337. ): Promise<R[]> {
  338. const results: R[] = [];
  339. for (let i = 0; i < items.length; i += batchSize) {
  340. const batch = items.slice(i, Math.min(i + batchSize, items.length));
  341. const batchResults = await Promise.all(
  342. batch.map((item, idx) => processor(item, i + idx))
  343. );
  344. results.push(...batchResults);
  345. if (onBatchComplete) {
  346. onBatchComplete(Math.min(i + batchSize, items.length), items.length);
  347. }
  348. // Allow GC between batches
  349. if (global.gc) {
  350. global.gc();
  351. }
  352. }
  353. return results;
  354. }
  355. /**
  356. * Simple mutex lock for preventing concurrent operations
  357. */
  358. export class Mutex {
  359. private locked = false;
  360. private waitQueue: Array<() => void> = [];
  361. /**
  362. * Acquire the lock
  363. *
  364. * @returns A release function to call when done
  365. */
  366. async acquire(): Promise<() => void> {
  367. while (this.locked) {
  368. await new Promise<void>((resolve) => {
  369. this.waitQueue.push(resolve);
  370. });
  371. }
  372. this.locked = true;
  373. return () => {
  374. this.locked = false;
  375. const next = this.waitQueue.shift();
  376. if (next) {
  377. next();
  378. }
  379. };
  380. }
  381. /**
  382. * Execute a function while holding the lock
  383. */
  384. async withLock<T>(fn: () => Promise<T> | T): Promise<T> {
  385. const release = await this.acquire();
  386. try {
  387. return await fn();
  388. } finally {
  389. release();
  390. }
  391. }
  392. /**
  393. * Check if the lock is currently held
  394. */
  395. isLocked(): boolean {
  396. return this.locked;
  397. }
  398. }
  399. /**
  400. * Chunked file reader for large files
  401. *
  402. * Reads a file in chunks to avoid loading entire file into memory.
  403. */
  404. export async function* readFileInChunks(
  405. filePath: string,
  406. chunkSize: number = 64 * 1024
  407. ): AsyncGenerator<string, void, undefined> {
  408. const fs = await import('fs');
  409. const fd = fs.openSync(filePath, 'r');
  410. const buffer = Buffer.alloc(chunkSize);
  411. try {
  412. let bytesRead: number;
  413. while ((bytesRead = fs.readSync(fd, buffer, 0, chunkSize, null)) > 0) {
  414. yield buffer.toString('utf-8', 0, bytesRead);
  415. }
  416. } finally {
  417. fs.closeSync(fd);
  418. }
  419. }
  420. /**
  421. * Debounce a function
  422. *
  423. * @param fn - Function to debounce
  424. * @param delay - Delay in milliseconds
  425. * @returns Debounced function
  426. */
  427. export function debounce<T extends (...args: unknown[]) => unknown>(
  428. fn: T,
  429. delay: number
  430. ): (...args: Parameters<T>) => void {
  431. let timeoutId: ReturnType<typeof setTimeout> | null = null;
  432. return (...args: Parameters<T>) => {
  433. if (timeoutId) {
  434. clearTimeout(timeoutId);
  435. }
  436. timeoutId = setTimeout(() => {
  437. fn(...args);
  438. timeoutId = null;
  439. }, delay);
  440. };
  441. }
  442. /**
  443. * Throttle a function
  444. *
  445. * @param fn - Function to throttle
  446. * @param limit - Minimum time between calls in milliseconds
  447. * @returns Throttled function
  448. */
  449. export function throttle<T extends (...args: unknown[]) => unknown>(
  450. fn: T,
  451. limit: number
  452. ): (...args: Parameters<T>) => void {
  453. let lastCall = 0;
  454. let timeoutId: ReturnType<typeof setTimeout> | null = null;
  455. return (...args: Parameters<T>) => {
  456. const now = Date.now();
  457. const remaining = limit - (now - lastCall);
  458. if (remaining <= 0) {
  459. if (timeoutId) {
  460. clearTimeout(timeoutId);
  461. timeoutId = null;
  462. }
  463. lastCall = now;
  464. fn(...args);
  465. } else if (!timeoutId) {
  466. timeoutId = setTimeout(() => {
  467. lastCall = Date.now();
  468. timeoutId = null;
  469. fn(...args);
  470. }, remaining);
  471. }
  472. };
  473. }
  474. /**
  475. * Estimate memory usage of an object (rough approximation)
  476. *
  477. * @param obj - Object to measure
  478. * @returns Approximate size in bytes
  479. */
  480. export function estimateSize(obj: unknown): number {
  481. const seen = new WeakSet();
  482. function sizeOf(value: unknown): number {
  483. if (value === null || value === undefined) {
  484. return 0;
  485. }
  486. switch (typeof value) {
  487. case 'boolean':
  488. return 4;
  489. case 'number':
  490. return 8;
  491. case 'string':
  492. return 2 * (value as string).length;
  493. case 'object':
  494. if (seen.has(value as object)) {
  495. return 0;
  496. }
  497. seen.add(value as object);
  498. if (Array.isArray(value)) {
  499. return value.reduce((acc: number, item) => acc + sizeOf(item), 0);
  500. }
  501. return Object.entries(value as object).reduce(
  502. (acc, [key, val]) => acc + sizeOf(key) + sizeOf(val),
  503. 0
  504. );
  505. default:
  506. return 0;
  507. }
  508. }
  509. return sizeOf(obj);
  510. }
  511. /**
  512. * Memory monitor for tracking usage during operations
  513. */
  514. export class MemoryMonitor {
  515. private checkInterval: ReturnType<typeof setInterval> | null = null;
  516. private peakUsage = 0;
  517. private threshold: number;
  518. private onThresholdExceeded?: (usage: number) => void;
  519. constructor(
  520. thresholdMB: number = 500,
  521. onThresholdExceeded?: (usage: number) => void
  522. ) {
  523. this.threshold = thresholdMB * 1024 * 1024;
  524. this.onThresholdExceeded = onThresholdExceeded;
  525. }
  526. /**
  527. * Start monitoring memory usage
  528. */
  529. start(intervalMs: number = 1000): void {
  530. this.stop();
  531. this.peakUsage = 0;
  532. this.checkInterval = setInterval(() => {
  533. const usage = process.memoryUsage().heapUsed;
  534. if (usage > this.peakUsage) {
  535. this.peakUsage = usage;
  536. }
  537. if (usage > this.threshold && this.onThresholdExceeded) {
  538. this.onThresholdExceeded(usage);
  539. }
  540. }, intervalMs);
  541. }
  542. /**
  543. * Stop monitoring
  544. */
  545. stop(): void {
  546. if (this.checkInterval) {
  547. clearInterval(this.checkInterval);
  548. this.checkInterval = null;
  549. }
  550. }
  551. /**
  552. * Get peak memory usage in bytes
  553. */
  554. getPeakUsage(): number {
  555. return this.peakUsage;
  556. }
  557. /**
  558. * Get current memory usage in bytes
  559. */
  560. getCurrentUsage(): number {
  561. return process.memoryUsage().heapUsed;
  562. }
  563. }