utils.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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. * Validate that a file path stays within the project root, resolving symlinks.
  78. *
  79. * Two layers: a cheap lexical check that catches `../` traversal, then a
  80. * realpath check that catches symlink escapes — an in-repo symlink whose
  81. * logical path is inside the root but whose real target points outside it
  82. * (issue #527). A symlink that stays within the root is still allowed, so
  83. * legitimate in-tree symlinks keep working. Both content-serving read sinks
  84. * (codegraph_node `includeCode`, codegraph_explore source) go through here, so
  85. * this is the chokepoint that keeps out-of-root file contents from leaking.
  86. *
  87. * @param projectRoot - The project root directory
  88. * @param filePath - The (relative or absolute) file path to validate
  89. * @returns The resolved absolute path (realpath when it exists), or null if it
  90. * escapes the root
  91. */
  92. export function validatePathWithinRoot(projectRoot: string, filePath: string): string | null {
  93. const resolved = path.resolve(projectRoot, filePath);
  94. const normalizedRoot = path.resolve(projectRoot);
  95. // 1. Lexical containment — cheap, catches `../` traversal.
  96. if (!isWithinDir(resolved, normalizedRoot)) {
  97. return null;
  98. }
  99. // 2. Symlink-aware containment — resolve symlinks on both sides and re-check,
  100. // so an in-repo symlink whose real target escapes the root is rejected.
  101. try {
  102. const realRoot = fs.realpathSync(normalizedRoot);
  103. const realResolved = fs.realpathSync(resolved);
  104. return isWithinDir(realResolved, realRoot) ? realResolved : null;
  105. } catch (err) {
  106. // ENOENT: the path doesn't exist yet (a file about to be written, or an
  107. // index entry for a since-deleted file) — no symlink to follow, and the
  108. // lexical check already passed, so allow the lexical path. Any other
  109. // resolution failure (ELOOP, EACCES, …) is treated as unsafe → reject.
  110. if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
  111. return resolved;
  112. }
  113. return null;
  114. }
  115. }
  116. /**
  117. * Validate that a path is a safe project root directory.
  118. *
  119. * Rejects sensitive system directories and ensures the path is
  120. * a real, existing directory. Used at MCP and API entry points
  121. * to prevent arbitrary directory access.
  122. *
  123. * @param dirPath - The path to validate
  124. * @returns An error message if invalid, or null if valid
  125. */
  126. export function validateProjectPath(dirPath: string): string | null {
  127. const resolved = path.resolve(dirPath);
  128. // Block sensitive system directories
  129. if (SENSITIVE_PATHS.has(resolved) || SENSITIVE_PATHS.has(resolved.toLowerCase())) {
  130. return `Refusing to operate on sensitive system directory: ${resolved}`;
  131. }
  132. // Also block common sensitive home subdirectories
  133. const homeDir = require('os').homedir();
  134. const sensitiveHomeDirs = ['.ssh', '.gnupg', '.aws', '.config'];
  135. for (const dir of sensitiveHomeDirs) {
  136. const sensitivePath = path.join(homeDir, dir);
  137. if (resolved === sensitivePath || resolved.startsWith(sensitivePath + path.sep)) {
  138. return `Refusing to operate on sensitive directory: ${resolved}`;
  139. }
  140. }
  141. // Verify it's a real directory
  142. try {
  143. const stats = fs.statSync(resolved);
  144. if (!stats.isDirectory()) {
  145. return `Path is not a directory: ${resolved}`;
  146. }
  147. } catch {
  148. return `Path does not exist or is not accessible: ${resolved}`;
  149. }
  150. return null;
  151. }
  152. /**
  153. * Safely parse JSON with a fallback value.
  154. * Prevents crashes from corrupted database metadata.
  155. */
  156. export function safeJsonParse<T>(value: string, fallback: T): T {
  157. try {
  158. return JSON.parse(value);
  159. } catch {
  160. return fallback;
  161. }
  162. }
  163. /**
  164. * Clamp a numeric value to a range.
  165. * Used to enforce sane limits on MCP tool inputs.
  166. */
  167. export function clamp(value: number, min: number, max: number): number {
  168. return Math.max(min, Math.min(max, value));
  169. }
  170. /**
  171. * Normalize a file path to use forward slashes.
  172. * Fixes Windows backslash paths so glob matching works consistently.
  173. */
  174. export function normalizePath(filePath: string): string {
  175. return filePath.replace(/\\/g, '/');
  176. }
  177. /**
  178. * Cross-process file lock using a lock file with PID tracking.
  179. *
  180. * Prevents multiple processes (e.g., git hooks, CLI, MCP server) from
  181. * writing to the same database simultaneously.
  182. */
  183. export class FileLock {
  184. private lockPath: string;
  185. private held = false;
  186. /** Locks older than this are considered stale regardless of PID status */
  187. private static readonly STALE_TIMEOUT_MS = 2 * 60 * 1000; // 2 minutes
  188. constructor(lockPath: string) {
  189. this.lockPath = lockPath;
  190. }
  191. /**
  192. * Acquire the lock. Throws if the lock is held by another live process.
  193. */
  194. acquire(): void {
  195. // Check for existing lock
  196. if (fs.existsSync(this.lockPath)) {
  197. try {
  198. const content = fs.readFileSync(this.lockPath, 'utf-8').trim();
  199. const pid = parseInt(content, 10);
  200. const stat = fs.statSync(this.lockPath);
  201. const lockAge = Date.now() - stat.mtimeMs;
  202. // Treat locks older than the timeout as stale, regardless of PID
  203. if (lockAge < FileLock.STALE_TIMEOUT_MS && !isNaN(pid) && this.isProcessAlive(pid)) {
  204. throw new Error(
  205. `CodeGraph database is locked by another process (PID ${pid}). ` +
  206. `If this is stale, run 'codegraph unlock' or delete ${this.lockPath}`
  207. );
  208. }
  209. // Stale lock (dead process or timed out) - remove it
  210. fs.unlinkSync(this.lockPath);
  211. } catch (err) {
  212. if (err instanceof Error && err.message.includes('locked by another')) {
  213. throw err;
  214. }
  215. // Other errors reading lock file - try to remove it
  216. try { fs.unlinkSync(this.lockPath); } catch { /* ignore */ }
  217. }
  218. }
  219. // Write our PID to the lock file using exclusive create flag
  220. try {
  221. fs.writeFileSync(this.lockPath, String(process.pid), { flag: 'wx' });
  222. this.held = true;
  223. } catch (err: any) {
  224. if (err.code === 'EEXIST') {
  225. // Race condition: another process grabbed the lock between our check and write
  226. throw new Error(
  227. 'CodeGraph database is locked by another process. ' +
  228. `If this is stale, run 'codegraph unlock' or delete ${this.lockPath}`
  229. );
  230. }
  231. throw err;
  232. }
  233. }
  234. /**
  235. * Release the lock
  236. */
  237. release(): void {
  238. if (!this.held) return;
  239. try {
  240. // Only remove if we still own it (check PID)
  241. const content = fs.readFileSync(this.lockPath, 'utf-8').trim();
  242. if (parseInt(content, 10) === process.pid) {
  243. fs.unlinkSync(this.lockPath);
  244. }
  245. } catch {
  246. // Lock file already gone - that's fine
  247. }
  248. this.held = false;
  249. }
  250. /**
  251. * Execute a function while holding the lock
  252. */
  253. withLock<T>(fn: () => T): T {
  254. this.acquire();
  255. try {
  256. return fn();
  257. } finally {
  258. this.release();
  259. }
  260. }
  261. /**
  262. * Execute an async function while holding the lock
  263. */
  264. async withLockAsync<T>(fn: () => Promise<T>): Promise<T> {
  265. this.acquire();
  266. try {
  267. return await fn();
  268. } finally {
  269. this.release();
  270. }
  271. }
  272. /**
  273. * Check if a process is still running
  274. */
  275. private isProcessAlive(pid: number): boolean {
  276. try {
  277. process.kill(pid, 0);
  278. return true;
  279. } catch {
  280. return false;
  281. }
  282. }
  283. }
  284. /**
  285. * Process items in batches to manage memory
  286. *
  287. * @param items - Array of items to process
  288. * @param batchSize - Number of items per batch
  289. * @param processor - Function to process each item
  290. * @param onBatchComplete - Optional callback after each batch
  291. * @returns Array of results
  292. */
  293. export async function processInBatches<T, R>(
  294. items: T[],
  295. batchSize: number,
  296. processor: (item: T, index: number) => Promise<R>,
  297. onBatchComplete?: (completed: number, total: number) => void
  298. ): Promise<R[]> {
  299. const results: R[] = [];
  300. for (let i = 0; i < items.length; i += batchSize) {
  301. const batch = items.slice(i, Math.min(i + batchSize, items.length));
  302. const batchResults = await Promise.all(
  303. batch.map((item, idx) => processor(item, i + idx))
  304. );
  305. results.push(...batchResults);
  306. if (onBatchComplete) {
  307. onBatchComplete(Math.min(i + batchSize, items.length), items.length);
  308. }
  309. // Allow GC between batches
  310. if (global.gc) {
  311. global.gc();
  312. }
  313. }
  314. return results;
  315. }
  316. /**
  317. * Simple mutex lock for preventing concurrent operations
  318. */
  319. export class Mutex {
  320. private locked = false;
  321. private waitQueue: Array<() => void> = [];
  322. /**
  323. * Acquire the lock
  324. *
  325. * @returns A release function to call when done
  326. */
  327. async acquire(): Promise<() => void> {
  328. while (this.locked) {
  329. await new Promise<void>((resolve) => {
  330. this.waitQueue.push(resolve);
  331. });
  332. }
  333. this.locked = true;
  334. return () => {
  335. this.locked = false;
  336. const next = this.waitQueue.shift();
  337. if (next) {
  338. next();
  339. }
  340. };
  341. }
  342. /**
  343. * Execute a function while holding the lock
  344. */
  345. async withLock<T>(fn: () => Promise<T> | T): Promise<T> {
  346. const release = await this.acquire();
  347. try {
  348. return await fn();
  349. } finally {
  350. release();
  351. }
  352. }
  353. /**
  354. * Check if the lock is currently held
  355. */
  356. isLocked(): boolean {
  357. return this.locked;
  358. }
  359. }
  360. /**
  361. * Chunked file reader for large files
  362. *
  363. * Reads a file in chunks to avoid loading entire file into memory.
  364. */
  365. export async function* readFileInChunks(
  366. filePath: string,
  367. chunkSize: number = 64 * 1024
  368. ): AsyncGenerator<string, void, undefined> {
  369. const fs = await import('fs');
  370. const fd = fs.openSync(filePath, 'r');
  371. const buffer = Buffer.alloc(chunkSize);
  372. try {
  373. let bytesRead: number;
  374. while ((bytesRead = fs.readSync(fd, buffer, 0, chunkSize, null)) > 0) {
  375. yield buffer.toString('utf-8', 0, bytesRead);
  376. }
  377. } finally {
  378. fs.closeSync(fd);
  379. }
  380. }
  381. /**
  382. * Debounce a function
  383. *
  384. * @param fn - Function to debounce
  385. * @param delay - Delay in milliseconds
  386. * @returns Debounced function
  387. */
  388. export function debounce<T extends (...args: unknown[]) => unknown>(
  389. fn: T,
  390. delay: number
  391. ): (...args: Parameters<T>) => void {
  392. let timeoutId: ReturnType<typeof setTimeout> | null = null;
  393. return (...args: Parameters<T>) => {
  394. if (timeoutId) {
  395. clearTimeout(timeoutId);
  396. }
  397. timeoutId = setTimeout(() => {
  398. fn(...args);
  399. timeoutId = null;
  400. }, delay);
  401. };
  402. }
  403. /**
  404. * Throttle a function
  405. *
  406. * @param fn - Function to throttle
  407. * @param limit - Minimum time between calls in milliseconds
  408. * @returns Throttled function
  409. */
  410. export function throttle<T extends (...args: unknown[]) => unknown>(
  411. fn: T,
  412. limit: number
  413. ): (...args: Parameters<T>) => void {
  414. let lastCall = 0;
  415. let timeoutId: ReturnType<typeof setTimeout> | null = null;
  416. return (...args: Parameters<T>) => {
  417. const now = Date.now();
  418. const remaining = limit - (now - lastCall);
  419. if (remaining <= 0) {
  420. if (timeoutId) {
  421. clearTimeout(timeoutId);
  422. timeoutId = null;
  423. }
  424. lastCall = now;
  425. fn(...args);
  426. } else if (!timeoutId) {
  427. timeoutId = setTimeout(() => {
  428. lastCall = Date.now();
  429. timeoutId = null;
  430. fn(...args);
  431. }, remaining);
  432. }
  433. };
  434. }
  435. /**
  436. * Estimate memory usage of an object (rough approximation)
  437. *
  438. * @param obj - Object to measure
  439. * @returns Approximate size in bytes
  440. */
  441. export function estimateSize(obj: unknown): number {
  442. const seen = new WeakSet();
  443. function sizeOf(value: unknown): number {
  444. if (value === null || value === undefined) {
  445. return 0;
  446. }
  447. switch (typeof value) {
  448. case 'boolean':
  449. return 4;
  450. case 'number':
  451. return 8;
  452. case 'string':
  453. return 2 * (value as string).length;
  454. case 'object':
  455. if (seen.has(value as object)) {
  456. return 0;
  457. }
  458. seen.add(value as object);
  459. if (Array.isArray(value)) {
  460. return value.reduce((acc: number, item) => acc + sizeOf(item), 0);
  461. }
  462. return Object.entries(value as object).reduce(
  463. (acc, [key, val]) => acc + sizeOf(key) + sizeOf(val),
  464. 0
  465. );
  466. default:
  467. return 0;
  468. }
  469. }
  470. return sizeOf(obj);
  471. }
  472. /**
  473. * Memory monitor for tracking usage during operations
  474. */
  475. export class MemoryMonitor {
  476. private checkInterval: ReturnType<typeof setInterval> | null = null;
  477. private peakUsage = 0;
  478. private threshold: number;
  479. private onThresholdExceeded?: (usage: number) => void;
  480. constructor(
  481. thresholdMB: number = 500,
  482. onThresholdExceeded?: (usage: number) => void
  483. ) {
  484. this.threshold = thresholdMB * 1024 * 1024;
  485. this.onThresholdExceeded = onThresholdExceeded;
  486. }
  487. /**
  488. * Start monitoring memory usage
  489. */
  490. start(intervalMs: number = 1000): void {
  491. this.stop();
  492. this.peakUsage = 0;
  493. this.checkInterval = setInterval(() => {
  494. const usage = process.memoryUsage().heapUsed;
  495. if (usage > this.peakUsage) {
  496. this.peakUsage = usage;
  497. }
  498. if (usage > this.threshold && this.onThresholdExceeded) {
  499. this.onThresholdExceeded(usage);
  500. }
  501. }, intervalMs);
  502. }
  503. /**
  504. * Stop monitoring
  505. */
  506. stop(): void {
  507. if (this.checkInterval) {
  508. clearInterval(this.checkInterval);
  509. this.checkInterval = null;
  510. }
  511. }
  512. /**
  513. * Get peak memory usage in bytes
  514. */
  515. getPeakUsage(): number {
  516. return this.peakUsage;
  517. }
  518. /**
  519. * Get current memory usage in bytes
  520. */
  521. getCurrentUsage(): number {
  522. return process.memoryUsage().heapUsed;
  523. }
  524. }