@dreamtree-org/graphify 1.0.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,364 +0,0 @@
1
- // src/security.ts
2
- import { createHash } from "crypto";
3
- import * as dns from "dns";
4
- import * as http from "http";
5
- import * as https from "https";
6
- import * as fs from "fs";
7
- import * as net from "net";
8
- import * as nodePath from "path";
9
- var ALLOWED_SCHEMES = /* @__PURE__ */ new Set(["http:", "https:"]);
10
- var MAX_FETCH_BYTES = 50 * 1024 * 1024;
11
- var MAX_TEXT_BYTES = 10 * 1024 * 1024;
12
- var MAX_LABEL_LEN = 256;
13
- var BLOCKED_HOSTNAMES = /* @__PURE__ */ new Set([
14
- "metadata.google.internal",
15
- "metadata.internal",
16
- "metadata",
17
- "metadata.azure.com",
18
- "instance-data",
19
- "instance-data.ec2.internal"
20
- ]);
21
- function ipv4ToInt(ip) {
22
- const parts = ip.split(".");
23
- if (parts.length !== 4) return null;
24
- let result = 0;
25
- for (const part of parts) {
26
- if (!/^\d{1,3}$/.test(part)) return null;
27
- const n = Number(part);
28
- if (n > 255) return null;
29
- result = result << 8 | n;
30
- }
31
- return result >>> 0;
32
- }
33
- function ipv4InCidr(ipInt, cidr) {
34
- const [base, prefixStr] = cidr.split("/");
35
- const prefix = Number(prefixStr);
36
- const baseInt = ipv4ToInt(base ?? "");
37
- if (baseInt === null) return false;
38
- const mask = prefix === 0 ? 0 : ~0 << 32 - prefix >>> 0;
39
- return (ipInt & mask) >>> 0 === (baseInt & mask) >>> 0;
40
- }
41
- var BLOCKED_IPV4_CIDRS = [
42
- "0.0.0.0/8",
43
- // "this" network
44
- "10.0.0.0/8",
45
- // private
46
- "100.64.0.0/10",
47
- // carrier-grade NAT (CGN)
48
- "127.0.0.0/8",
49
- // loopback
50
- "169.254.0.0/16",
51
- // link-local (covers 169.254.169.254 cloud metadata)
52
- "172.16.0.0/12",
53
- // private
54
- "192.0.0.0/24",
55
- // IETF protocol assignments
56
- "192.0.2.0/24",
57
- // TEST-NET-1
58
- "192.168.0.0/16",
59
- // private
60
- "198.18.0.0/15",
61
- // benchmarking
62
- "198.51.100.0/24",
63
- // TEST-NET-2
64
- "203.0.113.0/24",
65
- // TEST-NET-3
66
- "224.0.0.0/4",
67
- // multicast
68
- "240.0.0.0/4",
69
- // reserved
70
- "255.255.255.255/32"
71
- // broadcast
72
- ];
73
- function isForbiddenIpv4(ip) {
74
- const ipInt = ipv4ToInt(ip);
75
- if (ipInt === null) return true;
76
- return BLOCKED_IPV4_CIDRS.some((cidr) => ipv4InCidr(ipInt, cidr));
77
- }
78
- function expandIpv6(ip) {
79
- const withoutZone = ip.split("%")[0] ?? "";
80
- const parts = withoutZone.split("::");
81
- if (parts.length > 2) return null;
82
- const head = parts[0] ? parts[0].split(":").filter((s) => s.length > 0) : [];
83
- const tail = parts.length === 2 && parts[1] ? parts[1].split(":").filter((s) => s.length > 0) : [];
84
- let missing = 0;
85
- if (parts.length === 2) {
86
- missing = 8 - head.length - tail.length;
87
- if (missing < 0) return null;
88
- } else if (head.length + tail.length !== 8) {
89
- return null;
90
- }
91
- const groupsHex = [...head, ...Array(missing).fill("0"), ...tail];
92
- if (groupsHex.length !== 8) return null;
93
- const groups = [];
94
- for (const g of groupsHex) {
95
- if (!/^[0-9a-fA-F]{1,4}$/.test(g)) return null;
96
- groups.push(parseInt(g, 16));
97
- }
98
- return groups;
99
- }
100
- function isForbiddenIpv6(ip) {
101
- const lower = ip.toLowerCase();
102
- if (lower === "::1" || lower === "::") return true;
103
- const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(lower);
104
- if (mapped) return isForbiddenIpv4(mapped[1]);
105
- const groups = expandIpv6(lower);
106
- if (groups === null) return true;
107
- const first = groups[0];
108
- if ((first & 65472) === 65152) return true;
109
- if ((first & 65024) === 64512) return true;
110
- if ((first & 65280) === 65280) return true;
111
- if (groups.every((g) => g === 0)) return true;
112
- return false;
113
- }
114
- function isForbiddenIp(ip) {
115
- return net.isIPv6(ip) ? isForbiddenIpv6(ip) : isForbiddenIpv4(ip);
116
- }
117
- function validateUrl(url) {
118
- let parsed;
119
- try {
120
- parsed = new URL(url);
121
- } catch {
122
- throw new Error(`Invalid URL: ${url}`);
123
- }
124
- if (!ALLOWED_SCHEMES.has(parsed.protocol)) {
125
- throw new Error(
126
- `URL scheme not allowed: "${parsed.protocol}" (allowed: ${[...ALLOWED_SCHEMES].join(", ")})`
127
- );
128
- }
129
- const hostname = parsed.hostname.toLowerCase();
130
- if (BLOCKED_HOSTNAMES.has(hostname)) {
131
- throw new Error(`URL targets a blocked host: ${hostname}`);
132
- }
133
- const bareHost = hostname.startsWith("[") && hostname.endsWith("]") ? hostname.slice(1, -1) : hostname;
134
- if (net.isIP(bareHost) && isForbiddenIp(bareHost)) {
135
- throw new Error(`URL targets a forbidden IP address: ${bareHost}`);
136
- }
137
- return parsed.toString();
138
- }
139
- function validateGraphPath(path2, base) {
140
- const baseDir = base ?? nodePath.join(process.cwd(), "graphify-out");
141
- let resolvedBase;
142
- try {
143
- resolvedBase = fs.realpathSync(baseDir);
144
- } catch {
145
- throw new Error(`Base directory does not exist: ${baseDir}`);
146
- }
147
- const candidate = nodePath.isAbsolute(path2) ? path2 : nodePath.join(resolvedBase, path2);
148
- const resolvedCandidate = nodePath.resolve(candidate);
149
- let realCandidate = resolvedCandidate;
150
- try {
151
- realCandidate = fs.realpathSync(resolvedCandidate);
152
- } catch {
153
- }
154
- const relative2 = nodePath.relative(resolvedBase, realCandidate);
155
- const escapes = relative2 === ".." || relative2.startsWith(`..${nodePath.sep}`) || nodePath.isAbsolute(relative2);
156
- if (escapes) {
157
- throw new Error(`Path escapes graphify-out/: ${path2}`);
158
- }
159
- return realCandidate;
160
- }
161
- function sanitizeLabel(text) {
162
- if (text == null) return "";
163
- const stripped = String(text).replace(/[\x00-\x1f\x7f]/g, "");
164
- return stripped.slice(0, MAX_LABEL_LEN);
165
- }
166
- function escapeHtml(text) {
167
- return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
168
- }
169
-
170
- // src/graphStore.ts
171
- import * as fs2 from "fs/promises";
172
- import * as path from "path";
173
- import Graph from "graphology";
174
- async function loadGraph(outDir = path.join(process.cwd(), "graphify-out")) {
175
- const jsonPath = validateGraphPath("graph.json", outDir);
176
- const raw = await fs2.readFile(jsonPath, "utf-8");
177
- const data = JSON.parse(raw);
178
- return Graph.from(data);
179
- }
180
-
181
- // src/query.ts
182
- var STOPWORDS = /* @__PURE__ */ new Set([
183
- "a",
184
- "an",
185
- "the",
186
- "is",
187
- "are",
188
- "was",
189
- "were",
190
- "do",
191
- "does",
192
- "did",
193
- "how",
194
- "what",
195
- "where",
196
- "when",
197
- "why",
198
- "who",
199
- "which",
200
- "to",
201
- "of",
202
- "in",
203
- "on",
204
- "for",
205
- "and",
206
- "or",
207
- "this",
208
- "that",
209
- "it",
210
- "does",
211
- "that's"
212
- ]);
213
- function tokenize(text) {
214
- return text.toLowerCase().split(/[^a-z0-9_.]+/).filter((token) => token.length > 1 && !STOPWORDS.has(token));
215
- }
216
- function scoreNodes(graph, query) {
217
- const tokens = tokenize(query);
218
- const matches = [];
219
- graph.forEachNode((id, attributes) => {
220
- const label = attributes.label ?? id;
221
- const haystack = `${label} ${id}`.toLowerCase();
222
- let score = 0;
223
- for (const token of tokens) {
224
- if (haystack.includes(token)) score += 1;
225
- }
226
- if (score > 0) matches.push({ id, label, score });
227
- });
228
- matches.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));
229
- return matches;
230
- }
231
- function resolveNode(graph, query) {
232
- const matches = scoreNodes(graph, query);
233
- return matches[0] ?? null;
234
- }
235
- var DEFAULT_MAX_DEPTH = 2;
236
- var DEFAULT_MAX_SEEDS = 5;
237
- var DEFAULT_BUDGET = 40;
238
- function queryGraph(graph, question, options = {}) {
239
- const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;
240
- const maxSeeds = options.maxSeeds ?? DEFAULT_MAX_SEEDS;
241
- const budget = options.budget ?? DEFAULT_BUDGET;
242
- const allMatches = scoreNodes(graph, question);
243
- const seeds = allMatches.length > 0 ? allMatches.slice(0, maxSeeds) : [];
244
- const visited = /* @__PURE__ */ new Map();
245
- const frontier = seeds.map((s) => ({ id: s.id, depth: 0 }));
246
- for (const seed of seeds) visited.set(seed.id, 0);
247
- while (frontier.length > 0 && visited.size < budget) {
248
- const current = options.dfs ? frontier.pop() : frontier.shift();
249
- if (current.depth >= maxDepth) continue;
250
- const neighbors = [...graph.neighbors(current.id)].sort((a, b) => a.localeCompare(b));
251
- for (const neighbor of neighbors) {
252
- if (visited.has(neighbor) || visited.size >= budget) continue;
253
- visited.set(neighbor, current.depth + 1);
254
- frontier.push({ id: neighbor, depth: current.depth + 1 });
255
- }
256
- }
257
- const visitedNodes = [...visited.entries()].map(([id, depth]) => {
258
- const attrs = graph.getNodeAttributes(id);
259
- return {
260
- id,
261
- label: attrs.label ?? id,
262
- sourceFile: attrs.sourceFile ?? "",
263
- sourceLocation: attrs.sourceLocation ?? "",
264
- depth
265
- };
266
- }).sort((a, b) => a.depth - b.depth || a.id.localeCompare(b.id));
267
- const edges = [];
268
- graph.forEachEdge((_edge, attrs, source, target) => {
269
- if (visited.has(source) && visited.has(target)) {
270
- edges.push({
271
- source,
272
- target,
273
- relation: String(attrs.relation),
274
- confidence: String(attrs.confidence)
275
- });
276
- }
277
- });
278
- edges.sort(
279
- (a, b) => a.source.localeCompare(b.source) || a.target.localeCompare(b.target) || a.relation.localeCompare(b.relation)
280
- );
281
- return { seeds, visited: visitedNodes, edges };
282
- }
283
- function shortestPath(graph, fromQuery, toQuery) {
284
- const from = resolveNode(graph, fromQuery);
285
- const to = resolveNode(graph, toQuery);
286
- if (!from || !to) return null;
287
- if (from.id === to.id) {
288
- return { from, to, found: true, path: [from.id], edges: [] };
289
- }
290
- const predecessor = /* @__PURE__ */ new Map();
291
- const visited = /* @__PURE__ */ new Set([from.id]);
292
- const queue = [from.id];
293
- while (queue.length > 0) {
294
- const current = queue.shift();
295
- if (current === to.id) break;
296
- const neighbors = [...graph.neighbors(current)].sort((a, b) => a.localeCompare(b));
297
- for (const neighbor of neighbors) {
298
- if (visited.has(neighbor)) continue;
299
- visited.add(neighbor);
300
- predecessor.set(neighbor, current);
301
- queue.push(neighbor);
302
- }
303
- }
304
- if (!visited.has(to.id)) {
305
- return { from, to, found: false, path: [], edges: [] };
306
- }
307
- const path2 = [to.id];
308
- let cursor = to.id;
309
- while (cursor !== from.id) {
310
- const prev = predecessor.get(cursor);
311
- if (!prev) break;
312
- path2.unshift(prev);
313
- cursor = prev;
314
- }
315
- const edges = [];
316
- for (let i = 0; i < path2.length - 1; i++) {
317
- const a = path2[i];
318
- const b = path2[i + 1];
319
- const key = graph.edges(a, b)[0] ?? graph.edges(b, a)[0];
320
- if (key) {
321
- const attrs = graph.getEdgeAttributes(key);
322
- edges.push({ source: a, target: b, relation: String(attrs.relation), confidence: String(attrs.confidence) });
323
- }
324
- }
325
- return { from, to, found: true, path: path2, edges };
326
- }
327
- function explainNode(graph, query) {
328
- const match = resolveNode(graph, query);
329
- if (!match) return null;
330
- const attrs = graph.getNodeAttributes(match.id);
331
- const outgoing = [];
332
- const incoming = [];
333
- graph.forEachOutEdge(match.id, (_edge, edgeAttrs, source, target) => {
334
- outgoing.push({ source, target, relation: String(edgeAttrs.relation), confidence: String(edgeAttrs.confidence) });
335
- });
336
- graph.forEachInEdge(match.id, (_edge, edgeAttrs, source, target) => {
337
- incoming.push({ source, target, relation: String(edgeAttrs.relation), confidence: String(edgeAttrs.confidence) });
338
- });
339
- outgoing.sort((a, b) => a.target.localeCompare(b.target) || a.relation.localeCompare(b.relation));
340
- incoming.sort((a, b) => a.source.localeCompare(b.source) || a.relation.localeCompare(b.relation));
341
- return {
342
- id: match.id,
343
- label: match.label,
344
- sourceFile: attrs.sourceFile ?? "",
345
- sourceLocation: attrs.sourceLocation ?? "",
346
- communityLabel: attrs.communityLabel,
347
- outgoing,
348
- incoming
349
- };
350
- }
351
-
352
- export {
353
- validateUrl,
354
- validateGraphPath,
355
- sanitizeLabel,
356
- escapeHtml,
357
- loadGraph,
358
- scoreNodes,
359
- resolveNode,
360
- queryGraph,
361
- shortestPath,
362
- explainNode
363
- };
364
- //# sourceMappingURL=chunk-5ANIDX3G.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/security.ts","../src/graphStore.ts","../src/query.ts"],"sourcesContent":["/**\n * Security helpers — URL validation, SSRF-guarded fetch, path guards, label\n * sanitization, prompt-injection defenses. Every control listed in\n * SECURITY.md must have a corresponding function here and a unit test in\n * tests/security.test.ts. See the master prompt §5 for the full checklist.\n */\n\nimport { createHash } from 'node:crypto';\nimport * as dns from 'node:dns';\nimport * as http from 'node:http';\nimport * as https from 'node:https';\nimport * as fs from 'node:fs';\nimport * as net from 'node:net';\nimport * as nodePath from 'node:path';\n\nconst ALLOWED_SCHEMES = new Set(['http:', 'https:']);\nconst MAX_FETCH_BYTES = 50 * 1024 * 1024;\nconst MAX_TEXT_BYTES = 10 * 1024 * 1024;\nconst MAX_LABEL_LEN = 256;\nconst MAX_REDIRECTS = 5;\nconst REQUEST_TIMEOUT_MS = 15_000;\n\n/** Hostnames that must never be reachable, regardless of what they resolve to. */\nconst BLOCKED_HOSTNAMES = new Set([\n 'metadata.google.internal',\n 'metadata.internal',\n 'metadata',\n 'metadata.azure.com',\n 'instance-data',\n 'instance-data.ec2.internal',\n]);\n\n// ---------------------------------------------------------------------------\n// IP range checks (SSRF guard core). Implemented without extra dependencies.\n// ---------------------------------------------------------------------------\n\nfunction ipv4ToInt(ip: string): number | null {\n const parts = ip.split('.');\n if (parts.length !== 4) return null;\n let result = 0;\n for (const part of parts) {\n if (!/^\\d{1,3}$/.test(part)) return null;\n const n = Number(part);\n if (n > 255) return null;\n result = (result << 8) | n;\n }\n return result >>> 0;\n}\n\nfunction ipv4InCidr(ipInt: number, cidr: string): boolean {\n const [base, prefixStr] = cidr.split('/');\n const prefix = Number(prefixStr);\n const baseInt = ipv4ToInt(base ?? '');\n if (baseInt === null) return false;\n const mask = prefix === 0 ? 0 : (~0 << (32 - prefix)) >>> 0;\n return (ipInt & mask) >>> 0 === (baseInt & mask) >>> 0;\n}\n\n/** IPv4 ranges that must never be connected to from a server-side fetch. */\nconst BLOCKED_IPV4_CIDRS = [\n '0.0.0.0/8', // \"this\" network\n '10.0.0.0/8', // private\n '100.64.0.0/10', // carrier-grade NAT (CGN)\n '127.0.0.0/8', // loopback\n '169.254.0.0/16', // link-local (covers 169.254.169.254 cloud metadata)\n '172.16.0.0/12', // private\n '192.0.0.0/24', // IETF protocol assignments\n '192.0.2.0/24', // TEST-NET-1\n '192.168.0.0/16', // private\n '198.18.0.0/15', // benchmarking\n '198.51.100.0/24', // TEST-NET-2\n '203.0.113.0/24', // TEST-NET-3\n '224.0.0.0/4', // multicast\n '240.0.0.0/4', // reserved\n '255.255.255.255/32', // broadcast\n];\n\nexport function isForbiddenIpv4(ip: string): boolean {\n const ipInt = ipv4ToInt(ip);\n if (ipInt === null) return true; // malformed -> treat as forbidden, fail closed\n return BLOCKED_IPV4_CIDRS.some((cidr) => ipv4InCidr(ipInt, cidr));\n}\n\n/** Expand a (possibly `::`-compressed) IPv6 address into 8 16-bit groups. */\nfunction expandIpv6(ip: string): number[] | null {\n const withoutZone = ip.split('%')[0] ?? '';\n const parts = withoutZone.split('::');\n if (parts.length > 2) return null;\n\n const head = parts[0] ? parts[0].split(':').filter((s) => s.length > 0) : [];\n const tail = parts.length === 2 && parts[1] ? parts[1].split(':').filter((s) => s.length > 0) : [];\n\n let missing = 0;\n if (parts.length === 2) {\n missing = 8 - head.length - tail.length;\n if (missing < 0) return null;\n } else if (head.length + tail.length !== 8) {\n return null;\n }\n\n const groupsHex = [...head, ...Array(missing).fill('0'), ...tail];\n if (groupsHex.length !== 8) return null;\n\n const groups: number[] = [];\n for (const g of groupsHex) {\n if (!/^[0-9a-fA-F]{1,4}$/.test(g)) return null;\n groups.push(parseInt(g, 16));\n }\n return groups;\n}\n\nexport function isForbiddenIpv6(ip: string): boolean {\n const lower = ip.toLowerCase();\n if (lower === '::1' || lower === '::') return true;\n\n const mapped = /^::ffff:(\\d+\\.\\d+\\.\\d+\\.\\d+)$/.exec(lower);\n if (mapped) return isForbiddenIpv4(mapped[1] as string);\n\n const groups = expandIpv6(lower);\n if (groups === null) return true; // unparsable -> fail closed\n const first = groups[0] as number;\n if ((first & 0xffc0) === 0xfe80) return true; // fe80::/10 link-local\n if ((first & 0xfe00) === 0xfc00) return true; // fc00::/7 unique local\n if ((first & 0xff00) === 0xff00) return true; // ff00::/8 multicast\n if (groups.every((g) => g === 0)) return true; // unspecified/all-zero\n return false;\n}\n\nexport function isForbiddenIp(ip: string): boolean {\n return net.isIPv6(ip) ? isForbiddenIpv6(ip) : isForbiddenIpv4(ip);\n}\n\n// ---------------------------------------------------------------------------\n// URL validation\n// ---------------------------------------------------------------------------\n\n/**\n * Validate a URL is http/https and, when the hostname is itself a literal\n * IP or a known cloud-metadata hostname, reject it synchronously. DNS-bound\n * hostnames are re-validated at connect time by safeFetch() (see below) —\n * this function alone cannot rule out DNS rebinding for a hostname that\n * currently resolves to a public IP.\n */\nexport function validateUrl(url: string): string {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new Error(`Invalid URL: ${url}`);\n }\n\n if (!ALLOWED_SCHEMES.has(parsed.protocol)) {\n throw new Error(\n `URL scheme not allowed: \"${parsed.protocol}\" (allowed: ${[...ALLOWED_SCHEMES].join(', ')})`,\n );\n }\n\n const hostname = parsed.hostname.toLowerCase();\n if (BLOCKED_HOSTNAMES.has(hostname)) {\n throw new Error(`URL targets a blocked host: ${hostname}`);\n }\n\n // WHATWG URL keeps the brackets on an IPv6 literal host (e.g. \"[::1]\") —\n // strip them before checking net.isIP()/isForbiddenIp().\n const bareHost =\n hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;\n if (net.isIP(bareHost) && isForbiddenIp(bareHost)) {\n throw new Error(`URL targets a forbidden IP address: ${bareHost}`);\n }\n\n return parsed.toString();\n}\n\n// ---------------------------------------------------------------------------\n// safeFetch — SSRF-guarded, size-capped, redirect-revalidating fetch\n// ---------------------------------------------------------------------------\n\nexport type LookupFn = (hostname: string) => Promise<{ address: string; family: number }>;\n\n/**\n * Resolve a hostname (or pass through a literal IP) and validate the\n * result. `lookup` defaults to the real `dns.promises.lookup` — tests\n * substitute a fake to exercise the rebind guard deterministically without\n * making a real DNS query.\n */\nexport async function resolveAndValidate(\n hostname: string,\n lookup: LookupFn = dns.promises.lookup,\n): Promise<{ address: string; family: number }> {\n if (net.isIP(hostname)) {\n if (isForbiddenIp(hostname)) {\n throw new Error(`Refusing to connect to forbidden IP: ${hostname}`);\n }\n return { address: hostname, family: net.isIPv6(hostname) ? 6 : 4 };\n }\n const result = await lookup(hostname);\n if (isForbiddenIp(result.address)) {\n throw new Error(`Refusing to connect to forbidden IP: ${hostname} -> ${result.address}`);\n }\n return result;\n}\n\nexport interface RawResponse {\n statusCode: number;\n headers: http.IncomingHttpHeaders;\n body: Buffer;\n}\n\n/** Minimal shape of the `http`/`https` modules that requestOnce() needs — narrow on purpose so tests can substitute a fake transport instead of mocking network I/O. */\nexport type RequestTransport = Pick<typeof http, 'request'>;\n\n/**\n * Issue a single HTTP(S) request, connecting to `resolvedAddress` directly\n * (via a `lookup` override) rather than re-resolving DNS at connect time —\n * this is what prevents a DNS-rebind attacker from swapping the target\n * between validation and connection (TOCTOU). Streams the body and aborts\n * once it exceeds the byte cap for its declared content type.\n */\nexport function requestOnce(\n target: URL,\n resolvedAddress: string,\n resolvedFamily: number,\n transport: RequestTransport = target.protocol === 'https:' ? https : http,\n): Promise<RawResponse> {\n return new Promise((resolve, reject) => {\n const req = transport.request(\n {\n protocol: target.protocol,\n hostname: target.hostname,\n host: target.hostname,\n port: target.port || (target.protocol === 'https:' ? 443 : 80),\n path: `${target.pathname}${target.search}`,\n method: 'GET',\n timeout: REQUEST_TIMEOUT_MS,\n headers: { 'user-agent': 'graphify/0.1', accept: '*/*' },\n // Force the connection to the address we already validated — do not\n // let Node re-resolve `target.hostname` at connect time.\n lookup: (\n _hostname: string,\n options: unknown,\n callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void,\n ) => {\n callback(null, resolvedAddress, resolvedFamily);\n },\n } as http.RequestOptions,\n (res) => {\n const statusCode = res.statusCode ?? 0;\n const contentType = String(res.headers['content-type'] ?? '');\n const isTextual = /^text\\/|json|xml|html|charset=/i.test(contentType);\n const cap = isTextual ? MAX_TEXT_BYTES : MAX_FETCH_BYTES;\n\n const chunks: Buffer[] = [];\n let total = 0;\n let aborted = false;\n\n res.on('data', (chunk: Buffer) => {\n total += chunk.length;\n if (total > cap) {\n aborted = true;\n res.destroy();\n req.destroy();\n reject(new Error(`Response exceeded ${cap} byte cap (content-type: ${contentType})`));\n return;\n }\n chunks.push(chunk);\n });\n res.on('end', () => {\n if (aborted) return;\n resolve({ statusCode, headers: res.headers, body: Buffer.concat(chunks) });\n });\n res.on('error', (err) => {\n if (!aborted) reject(err);\n });\n },\n );\n\n req.on('timeout', () => {\n req.destroy(new Error(`Request timed out after ${REQUEST_TIMEOUT_MS}ms`));\n });\n req.on('error', reject);\n req.end();\n });\n}\n\nexport interface SafeFetchDeps {\n /** Override DNS resolution + IP validation (default: resolveAndValidate). */\n resolve?: (hostname: string) => Promise<{ address: string; family: number }>;\n /** Override the actual request (default: requestOnce against real http/https). */\n request?: (target: URL, address: string, family: number) => Promise<RawResponse>;\n}\n\n/**\n * Fetch a URL with the SSRF guards from validateUrl() plus streaming size\n * caps (MAX_FETCH_BYTES / MAX_TEXT_BYTES) and a hard error on non-2xx\n * status. Every redirect hop is independently validated and re-resolved —\n * a redirect to a private/loopback/metadata address is rejected exactly\n * like a direct request would be.\n *\n * `deps` exists so tests can substitute the DNS/network collaborators with\n * deterministic fakes (see tests/security.test.ts) instead of mocking\n * Node's core modules or hitting real sockets — production callers should\n * never need to pass it.\n */\nexport async function safeFetch(url: string, deps: SafeFetchDeps = {}): Promise<Buffer> {\n const resolve = deps.resolve ?? resolveAndValidate;\n const doRequest = deps.request ?? requestOnce;\n\n let current = validateUrl(url);\n for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {\n const target = new URL(current);\n const { address, family } = await resolve(target.hostname);\n const response = await doRequest(target, address, family);\n\n if (response.statusCode >= 300 && response.statusCode < 400) {\n const location = response.headers.location;\n if (!location) {\n throw new Error(`Redirect response (${response.statusCode}) missing Location header`);\n }\n const next = new URL(location, target).toString();\n current = validateUrl(next);\n continue;\n }\n\n if (response.statusCode < 200 || response.statusCode >= 300) {\n throw new Error(`Non-2xx response: ${response.statusCode}`);\n }\n\n return response.body;\n }\n throw new Error(`Too many redirects (> ${MAX_REDIRECTS}) while fetching ${url}`);\n}\n\n// ---------------------------------------------------------------------------\n// Path traversal guard\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve `path` and require it stays inside `base` (defaults to\n * `<cwd>/graphify-out`). `base` must already exist. Throws on traversal\n * attempts (`../`, absolute escapes, symlink-resolved escapes).\n */\nexport function validateGraphPath(path: string, base?: string): string {\n const baseDir = base ?? nodePath.join(process.cwd(), 'graphify-out');\n\n let resolvedBase: string;\n try {\n resolvedBase = fs.realpathSync(baseDir);\n } catch {\n throw new Error(`Base directory does not exist: ${baseDir}`);\n }\n\n const candidate = nodePath.isAbsolute(path) ? path : nodePath.join(resolvedBase, path);\n const resolvedCandidate = nodePath.resolve(candidate);\n\n // Resolve symlinks for whichever is the deepest existing ancestor, so a\n // symlink inside an otherwise-valid path can't escape the base dir either.\n let realCandidate = resolvedCandidate;\n try {\n realCandidate = fs.realpathSync(resolvedCandidate);\n } catch {\n // Path (or part of it) may not exist yet (e.g. a file we're about to\n // write) — fall back to the lexically-resolved path for the check.\n }\n\n const relative = nodePath.relative(resolvedBase, realCandidate);\n const escapes = relative === '..' || relative.startsWith(`..${nodePath.sep}`) || nodePath.isAbsolute(relative);\n if (escapes) {\n throw new Error(`Path escapes graphify-out/: ${path}`);\n }\n\n return realCandidate;\n}\n\n// ---------------------------------------------------------------------------\n// Label sanitization (unchanged reference implementation) + HTML escaping\n// ---------------------------------------------------------------------------\n\n/** Strip control characters, cap length. Apply to every node/edge label. */\nexport function sanitizeLabel(text: string | null | undefined): string {\n if (text == null) return '';\n // eslint-disable-next-line no-control-regex -- intentional: stripping raw control chars\n const stripped = String(text).replace(/[\\x00-\\x1f\\x7f]/g, '');\n return stripped.slice(0, MAX_LABEL_LEN);\n}\n\n/**\n * HTML-escape a string. Callers must run sanitizeLabel() first for\n * length/control-char stripping, then escapeHtml() immediately before\n * embedding into graph.html (XSS control, see SECURITY.md).\n */\nexport function escapeHtml(text: string): string {\n return text\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;');\n}\n\n// ---------------------------------------------------------------------------\n// Prompt-injection defenses for LLM-bound file content\n// ---------------------------------------------------------------------------\n\n/**\n * Known jailbreak / chat-template sentinels that must never reach a prompt\n * unescaped, whether they occur in source files or are forged to spoof our\n * own <untrusted_source> delimiter.\n */\nconst SENTINEL_PATTERNS: RegExp[] = [\n /<\\|im_start\\|>/gi,\n /<\\|im_end\\|>/gi,\n /<\\|system\\|>/gi,\n /\\[INST\\]/gi,\n /\\[\\/INST\\]/gi,\n /<<SYS>>/gi,\n /<<\\/SYS>>/gi,\n /<\\/untrusted_source>/gi,\n /<untrusted_source/gi,\n];\n\n/**\n * Render brackets as fullwidth lookalikes (< > [ ]) so the defanged\n * echo is human-visible but no longer byte-identical to the original\n * sentinel — a naive downstream scan for the literal delimiter/sentinel\n * text will not re-match our own \"we found one\" marker.\n */\nfunction toFullwidthBrackets(text: string): string {\n return text\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\\[/g, '[')\n .replace(/\\]/g, ']');\n}\n\n/**\n * Replace known jailbreak/chat-template sentinels with a visibly defanged\n * form — never silently stripped (silent stripping can itself be an\n * injection vector if it changes meaning unexpectedly).\n */\nfunction defangSentinels(content: string): string {\n let result = content;\n for (const pattern of SENTINEL_PATTERNS) {\n result = result.replace(pattern, (match) => `[DEFANGED:${toFullwidthBrackets(match)}]`);\n }\n return result;\n}\n\n/**\n * Wrap file content for LLM prompts in a hash-stamped untrusted-source\n * delimiter and neutralize known jailbreak/chat-template sentinels. This\n * raises the bar against prompt injection; it does not eliminate it —\n * document that plainly wherever this is referenced.\n */\nexport function wrapUntrustedSource(path: string, content: string): string {\n const sha256 = createHash('sha256').update(content, 'utf8').digest('hex');\n const safePath = escapeHtml(sanitizeLabel(path));\n const defanged = defangSentinels(content);\n return `<untrusted_source path=\"${safePath}\" sha256=\"${sha256}\">\\n${defanged}\\n</untrusted_source>`;\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport Graph from 'graphology';\nimport { validateGraphPath } from './security.js';\n\n/**\n * Load a previously-exported graph.json back into a graphology Graph.\n * Always goes through security.validateGraphPath() (path-traversal guard —\n * see SECURITY.md) so a caller-supplied `outDir`/CLI arg can never make\n * this read outside the graphify-out/ directory it resolves to.\n */\nexport async function loadGraph(outDir: string = path.join(process.cwd(), 'graphify-out')): Promise<Graph> {\n const jsonPath = validateGraphPath('graph.json', outDir);\n const raw = await fs.readFile(jsonPath, 'utf-8');\n const data: unknown = JSON.parse(raw);\n return Graph.from(data as Parameters<typeof Graph.from>[0]);\n}\n","import type Graph from 'graphology';\n\n/**\n * Library-level graph queries shared by the CLI (`graphify query/path/\n * explain`) and the MCP server tools of the same name. None of this is an\n * LLM call — it's lexical node matching + graph traversal, so it works\n * fully offline and deterministically.\n */\n\nconst STOPWORDS = new Set([\n 'a', 'an', 'the', 'is', 'are', 'was', 'were', 'do', 'does', 'did', 'how',\n 'what', 'where', 'when', 'why', 'who', 'which', 'to', 'of', 'in', 'on',\n 'for', 'and', 'or', 'this', 'that', 'it', 'does', 'that\\'s',\n]);\n\nfunction tokenize(text: string): string[] {\n return text\n .toLowerCase()\n .split(/[^a-z0-9_.]+/)\n .filter((token) => token.length > 1 && !STOPWORDS.has(token));\n}\n\nexport interface NodeMatch {\n id: string;\n label: string;\n score: number;\n}\n\n/** Score every node by how many query tokens appear in its label or id. */\nexport function scoreNodes(graph: Graph, query: string): NodeMatch[] {\n const tokens = tokenize(query);\n const matches: NodeMatch[] = [];\n\n graph.forEachNode((id, attributes) => {\n const label = (attributes.label as string | undefined) ?? id;\n const haystack = `${label} ${id}`.toLowerCase();\n let score = 0;\n for (const token of tokens) {\n if (haystack.includes(token)) score += 1;\n }\n if (score > 0) matches.push({ id, label, score });\n });\n\n matches.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));\n return matches;\n}\n\n/**\n * Best-effort single-node resolution: the highest-scoring lexical match,\n * or null if nothing in the graph matches at all. Deliberately does *not*\n * fall back to \"the most connected node\" — path/explain name a specific\n * node by intent, and silently substituting an unrelated one would be\n * more misleading than clearly saying \"no match\".\n */\nexport function resolveNode(graph: Graph, query: string): NodeMatch | null {\n const matches = scoreNodes(graph, query);\n return matches[0] ?? null;\n}\n\nexport interface VisitedNode {\n id: string;\n label: string;\n sourceFile: string;\n sourceLocation: string;\n depth: number;\n}\n\nexport interface TraversalEdge {\n source: string;\n target: string;\n relation: string;\n confidence: string;\n}\n\nexport interface QueryResult {\n seeds: NodeMatch[];\n visited: VisitedNode[];\n edges: TraversalEdge[];\n}\n\nexport interface QueryOptions {\n dfs?: boolean;\n /** Approximate cap on how many nodes to include (a stand-in for a true token budget — see docs). */\n budget?: number;\n maxDepth?: number;\n maxSeeds?: number;\n}\n\nconst DEFAULT_MAX_DEPTH = 2;\nconst DEFAULT_MAX_SEEDS = 5;\nconst DEFAULT_BUDGET = 40;\n\n/**\n * BFS (default, broad context) or DFS (--dfs, trace a specific path)\n * traversal from the nodes whose label best matches `question`'s\n * keywords. This is lexical retrieval, not natural-language\n * understanding — it surfaces the neighborhood of the graph an agent (or\n * a human) should look at to answer the question, it does not itself\n * compose an answer.\n */\nexport function queryGraph(graph: Graph, question: string, options: QueryOptions = {}): QueryResult {\n const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;\n const maxSeeds = options.maxSeeds ?? DEFAULT_MAX_SEEDS;\n const budget = options.budget ?? DEFAULT_BUDGET;\n\n const allMatches = scoreNodes(graph, question);\n const seeds = allMatches.length > 0 ? allMatches.slice(0, maxSeeds) : [];\n\n const visited = new Map<string, number>(); // id -> depth\n const frontier: Array<{ id: string; depth: number }> = seeds.map((s) => ({ id: s.id, depth: 0 }));\n for (const seed of seeds) visited.set(seed.id, 0);\n\n while (frontier.length > 0 && visited.size < budget) {\n const current = options.dfs ? (frontier.pop() as { id: string; depth: number }) : (frontier.shift() as { id: string; depth: number });\n if (current.depth >= maxDepth) continue;\n\n const neighbors = [...graph.neighbors(current.id)].sort((a, b) => a.localeCompare(b));\n for (const neighbor of neighbors) {\n if (visited.has(neighbor) || visited.size >= budget) continue;\n visited.set(neighbor, current.depth + 1);\n frontier.push({ id: neighbor, depth: current.depth + 1 });\n }\n }\n\n const visitedNodes: VisitedNode[] = [...visited.entries()]\n .map(([id, depth]) => {\n const attrs = graph.getNodeAttributes(id);\n return {\n id,\n label: (attrs.label as string | undefined) ?? id,\n sourceFile: (attrs.sourceFile as string | undefined) ?? '',\n sourceLocation: (attrs.sourceLocation as string | undefined) ?? '',\n depth,\n };\n })\n .sort((a, b) => a.depth - b.depth || a.id.localeCompare(b.id));\n\n const edges: TraversalEdge[] = [];\n graph.forEachEdge((_edge, attrs, source, target) => {\n if (visited.has(source) && visited.has(target)) {\n edges.push({\n source,\n target,\n relation: String(attrs.relation),\n confidence: String(attrs.confidence),\n });\n }\n });\n edges.sort(\n (a, b) => a.source.localeCompare(b.source) || a.target.localeCompare(b.target) || a.relation.localeCompare(b.relation),\n );\n\n return { seeds, visited: visitedNodes, edges };\n}\n\nexport interface PathResult {\n from: NodeMatch;\n to: NodeMatch;\n found: boolean;\n path: string[];\n edges: TraversalEdge[];\n}\n\n/** Shortest path between the nodes that best match `fromQuery` and `toQuery` (undirected BFS — connectivity, not call direction). */\nexport function shortestPath(graph: Graph, fromQuery: string, toQuery: string): PathResult | null {\n const from = resolveNode(graph, fromQuery);\n const to = resolveNode(graph, toQuery);\n if (!from || !to) return null;\n\n if (from.id === to.id) {\n return { from, to, found: true, path: [from.id], edges: [] };\n }\n\n const predecessor = new Map<string, string>();\n const visited = new Set<string>([from.id]);\n const queue: string[] = [from.id];\n\n while (queue.length > 0) {\n const current = queue.shift() as string;\n if (current === to.id) break;\n const neighbors = [...graph.neighbors(current)].sort((a, b) => a.localeCompare(b));\n for (const neighbor of neighbors) {\n if (visited.has(neighbor)) continue;\n visited.add(neighbor);\n predecessor.set(neighbor, current);\n queue.push(neighbor);\n }\n }\n\n if (!visited.has(to.id)) {\n return { from, to, found: false, path: [], edges: [] };\n }\n\n const path: string[] = [to.id];\n let cursor = to.id;\n while (cursor !== from.id) {\n const prev = predecessor.get(cursor);\n if (!prev) break;\n path.unshift(prev);\n cursor = prev;\n }\n\n const edges: TraversalEdge[] = [];\n for (let i = 0; i < path.length - 1; i++) {\n const a = path[i] as string;\n const b = path[i + 1] as string;\n const key = graph.edges(a, b)[0] ?? graph.edges(b, a)[0];\n if (key) {\n const attrs = graph.getEdgeAttributes(key);\n edges.push({ source: a, target: b, relation: String(attrs.relation), confidence: String(attrs.confidence) });\n }\n }\n\n return { from, to, found: true, path, edges };\n}\n\nexport interface ExplainResult {\n id: string;\n label: string;\n sourceFile: string;\n sourceLocation: string;\n communityLabel?: string;\n outgoing: TraversalEdge[];\n incoming: TraversalEdge[];\n}\n\n/** Plain-language-ready explanation of the node that best matches `query`. */\nexport function explainNode(graph: Graph, query: string): ExplainResult | null {\n const match = resolveNode(graph, query);\n if (!match) return null;\n\n const attrs = graph.getNodeAttributes(match.id);\n const outgoing: TraversalEdge[] = [];\n const incoming: TraversalEdge[] = [];\n\n graph.forEachOutEdge(match.id, (_edge, edgeAttrs, source, target) => {\n outgoing.push({ source, target, relation: String(edgeAttrs.relation), confidence: String(edgeAttrs.confidence) });\n });\n graph.forEachInEdge(match.id, (_edge, edgeAttrs, source, target) => {\n incoming.push({ source, target, relation: String(edgeAttrs.relation), confidence: String(edgeAttrs.confidence) });\n });\n\n outgoing.sort((a, b) => a.target.localeCompare(b.target) || a.relation.localeCompare(b.relation));\n incoming.sort((a, b) => a.source.localeCompare(b.source) || a.relation.localeCompare(b.relation));\n\n return {\n id: match.id,\n label: match.label,\n sourceFile: (attrs.sourceFile as string | undefined) ?? '',\n sourceLocation: (attrs.sourceLocation as string | undefined) ?? '',\n communityLabel: attrs.communityLabel as string | undefined,\n outgoing,\n incoming,\n };\n}\n"],"mappings":";AAOA,SAAS,kBAAkB;AAC3B,YAAY,SAAS;AACrB,YAAY,UAAU;AACtB,YAAY,WAAW;AACvB,YAAY,QAAQ;AACpB,YAAY,SAAS;AACrB,YAAY,cAAc;AAE1B,IAAM,kBAAkB,oBAAI,IAAI,CAAC,SAAS,QAAQ,CAAC;AACnD,IAAM,kBAAkB,KAAK,OAAO;AACpC,IAAM,iBAAiB,KAAK,OAAO;AACnC,IAAM,gBAAgB;AAKtB,IAAM,oBAAoB,oBAAI,IAAI;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAMD,SAAS,UAAU,IAA2B;AAC5C,QAAM,QAAQ,GAAG,MAAM,GAAG;AAC1B,MAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,MAAI,SAAS;AACb,aAAW,QAAQ,OAAO;AACxB,QAAI,CAAC,YAAY,KAAK,IAAI,EAAG,QAAO;AACpC,UAAM,IAAI,OAAO,IAAI;AACrB,QAAI,IAAI,IAAK,QAAO;AACpB,aAAU,UAAU,IAAK;AAAA,EAC3B;AACA,SAAO,WAAW;AACpB;AAEA,SAAS,WAAW,OAAe,MAAuB;AACxD,QAAM,CAAC,MAAM,SAA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