@zebbern/hacktricks-mcp 0.1.5 → 0.2.0

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.
@@ -0,0 +1,224 @@
1
+ import { holdsKubernetes, parseKubernetesGrant, rateKubernetesGrant, KUBERNETES_GRANT_SYNTAX, } from "./kubernetes-rbac.js";
2
+ import { covers, evalRequires, PERMISSION_KEYS, SEVERITIES, } from "./permissions.js";
3
+ /** How many techniques are listed at most; `escalationTotal` says how many there are. */
4
+ const ESCALATION_LIMIT = 30;
5
+ /** How many rated permissions a wildcard grant names at most, per rating. */
6
+ const WILDCARD_EXAMPLES = 12;
7
+ const loaded = new WeakMap();
8
+ function dataOf(db, provider) {
9
+ let providers = loaded.get(db);
10
+ if (!providers)
11
+ loaded.set(db, (providers = new Map()));
12
+ const cached = providers.get(provider);
13
+ if (cached)
14
+ return cached;
15
+ const fold = (name) => (provider === "gcp" || provider === "k8s" ? name : name.toLowerCase());
16
+ const risk = new Map();
17
+ for (const row of db.prepare("SELECT permission, severity FROM permission_risk WHERE provider = ?").all(provider)) {
18
+ risk.set(fold(row.permission), { name: row.permission, severity: row.severity });
19
+ }
20
+ const combinations = db.prepare("SELECT severity, permissions FROM permission_combination WHERE provider = ?").all(provider).map((row) => ({ severity: row.severity, permissions: JSON.parse(row.permissions) }));
21
+ const escalations = db.prepare("SELECT * FROM escalation WHERE provider = ?").all(provider);
22
+ const rules = provider === "k8s"
23
+ ? db
24
+ .prepare("SELECT rule FROM permission_rule WHERE provider = ? ORDER BY position")
25
+ .all(provider).map((row) => JSON.parse(row.rule))
26
+ : [];
27
+ const data = { risk, fold, combinations, escalations, rules };
28
+ providers.set(provider, data);
29
+ return data;
30
+ }
31
+ /**
32
+ * Rate the permissions a principal holds and list the escalation techniques
33
+ * they enable, at most `limit` of them (`escalationTotal` says how many there
34
+ * are). Throws when a Kubernetes grant is not written as expected.
35
+ */
36
+ export function checkPermissions(db, provider, held, limit = ESCALATION_LIMIT) {
37
+ const data = dataOf(db, provider);
38
+ const grants = held.map((grant) => grant.trim()).filter((grant) => grant.length > 0);
39
+ const kubernetes = [];
40
+ if (provider === "k8s") {
41
+ for (const grant of grants) {
42
+ const parsed = parseKubernetesGrant(grant);
43
+ if (!parsed)
44
+ throw new Error(`"${grant}" is not a Kubernetes grant. Write each one as ${KUBERNETES_GRANT_SYNTAX}.`);
45
+ kubernetes.push(parsed);
46
+ }
47
+ }
48
+ const combinations = data.combinations.filter((combination) => combination.permissions.every((need) => grants.some((grant) => covers(grant, need, provider))));
49
+ const matches = [];
50
+ const byId = new Map();
51
+ let notEvaluated = 0;
52
+ for (const row of data.escalations) {
53
+ byId.set(row.id, row);
54
+ const held_ = evalRequires(JSON.parse(row.requires), PERMISSION_KEYS[provider], (leaf, key) => provider === "k8s"
55
+ ? holdsKubernetes(leaf, kubernetes)
56
+ : grants.some((grant) => covers(grant, String(leaf[key]), provider)));
57
+ if (held_ !== true) {
58
+ if (held_ === null)
59
+ notEvaluated++;
60
+ continue;
61
+ }
62
+ const { page, section } = locate(db, row.source);
63
+ const target = JSON.parse(row.target);
64
+ matches.push({ id: row.id,
65
+ service: row.service,
66
+ title: row.title,
67
+ summary: row.summary,
68
+ severity: row.severity,
69
+ confidence: row.confidence,
70
+ needs: JSON.parse(row.needs),
71
+ gains: [target.kind, target.scope].filter(Boolean).join(", ").replace(/^([^,]+), (.+)$/, "$1 ($2)"),
72
+ conditions: JSON.parse(row.conditions),
73
+ blockers: JSON.parse(row.blockers),
74
+ mitigation: row.mitigation,
75
+ page,
76
+ section, });
77
+ }
78
+ // Order for "what can I do with these permissions": techniques of a service
79
+ // the held permissions belong to, then those that use more of them.
80
+ const heldServices = new Set(grants.map(serviceOf));
81
+ const serviceRank = (row) => (heldServices.has(row.service.replace(/_/g, "").toLowerCase()) ? 0 : 1);
82
+ matches.sort((a, b) => serviceRank(byId.get(a.id)) - serviceRank(byId.get(b.id)) ||
83
+ b.needs.length - a.needs.length ||
84
+ SEVERITIES.indexOf(a.severity) - SEVERITIES.indexOf(b.severity) ||
85
+ a.id.localeCompare(b.id));
86
+ return {
87
+ provider,
88
+ risk: provider === "k8s" ? kubernetes.map((grant, i) => rateRule(data, grant, grants[i])) : grants.map((grant) => rateGrant(data, grant, provider)),
89
+ combinations,
90
+ escalation: matches.slice(0, limit),
91
+ escalationTotal: matches.length,
92
+ notEvaluated,
93
+ // Sections named after the permissions themselves: the catalog does not
94
+ // cover everything the book describes.
95
+ sections: provider === "k8s" ? [] : sectionsFor(db, provider, grants),
96
+ };
97
+ }
98
+ /** The service a permission belongs to, as the catalog spells a technique's `service`: the first segment of its name. */
99
+ function serviceOf(permission) {
100
+ return permission.toLowerCase().replace(/^microsoft\./, "").split(/[.:/]/)[0].replace(/_/g, "");
101
+ }
102
+ /** One held permission against the rated list. */
103
+ function rateGrant(data, grant, provider) {
104
+ const exact = data.risk.get(data.fold(grant));
105
+ if (exact)
106
+ return { permission: exact.name, severity: exact.severity };
107
+ if (!grant.includes("*") && !grant.includes("?"))
108
+ return { permission: grant, severity: "not rated" };
109
+ // A wildcard covers every rated permission it matches.
110
+ const counts = new Map(SEVERITIES.map((s) => [s, 0]));
111
+ const examples = new Map(SEVERITIES.map((s) => [s, []]));
112
+ for (const [key, { name, severity }] of data.risk) {
113
+ if (!covers(grant, key, provider))
114
+ continue;
115
+ counts.set(severity, (counts.get(severity) ?? 0) + 1);
116
+ const list = examples.get(severity) ?? [];
117
+ if (list.length < WILDCARD_EXAMPLES)
118
+ list.push(name);
119
+ }
120
+ const matched = SEVERITIES.filter((s) => (counts.get(s) ?? 0) > 0);
121
+ if (matched.length === 0)
122
+ return { permission: grant, severity: "not rated" };
123
+ const note = [`matches ${matched.reduce((n, s) => n + (counts.get(s) ?? 0), 0).toLocaleString("en-US")} rated permissions`];
124
+ for (const severity of ["critical", "high"]) {
125
+ const list = examples.get(severity) ?? [];
126
+ if (list.length === 0)
127
+ continue;
128
+ const shown = list.slice(0, 6).join(", ");
129
+ note.push(`${counts.get(severity)} ${severity}: ${shown}${list.length > 6 ? ", ..." : ""}`);
130
+ }
131
+ return { permission: grant, severity: matched[0], note: note.join(": ") };
132
+ }
133
+ function rateRule(data, grant, text) {
134
+ const rating = rateKubernetesGrant(data.rules, grant);
135
+ return { permission: text, severity: rating.severity, note: rating.description || undefined };
136
+ }
137
+ /** The page a technique's `source` points to, and the heading its anchor stands for. */
138
+ function locate(db, source) {
139
+ const hash = source.indexOf("#");
140
+ const page = hash < 0 ? source : source.slice(0, hash);
141
+ if (hash < 0 || page.length === 0)
142
+ return { page };
143
+ const row = db.prepare("SELECT outline FROM pages WHERE book = 'hacktricks-cloud' AND path = ?").get(page);
144
+ if (!row)
145
+ return { page };
146
+ // Anchors on the wiki are heading slugs: lowercase, punctuation dropped, spaces as hyphens, repeats numbered.
147
+ const anchor = decodeURIComponent(source.slice(hash + 1));
148
+ const seen = new Map();
149
+ for (const heading of JSON.parse(row.outline)) {
150
+ const text = headingText(heading.text);
151
+ const slug = text.toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, "").replace(/\s/g, "-");
152
+ const repeats = seen.get(slug) ?? 0;
153
+ seen.set(slug, repeats + 1);
154
+ if ((repeats ? `${slug}-${repeats}` : slug) === anchor)
155
+ return { page, section: text };
156
+ }
157
+ return { page };
158
+ }
159
+ /** A heading as a reader sees it: without anchors and emphasis. */
160
+ function headingText(raw) {
161
+ return raw
162
+ .replace(/<[^>]+>/g, "")
163
+ .replace(/[*_`]+/g, "")
164
+ .replace(/\s+/g, " ")
165
+ .trim();
166
+ }
167
+ /** At most this many sections are listed per permission. */
168
+ const SECTIONS_PER_PERMISSION = 8;
169
+ const sectionsLoaded = new WeakMap();
170
+ /**
171
+ * Permission names at the start of a heading or after a separator, in the
172
+ * spellings of the three clouds: "iam:PassRole", "Microsoft.Authorization/...",
173
+ * "iam.serviceAccounts.getAccessToken", "Application.ReadWrite.All".
174
+ */
175
+ const PERMISSION_IN_HEADING = /(?:^|[\s,(|+])((?:[a-z0-9-]+:[A-Za-z0-9*:-]+)|(?:Microsoft\.[A-Za-z0-9.]+\/[A-Za-z0-9./_-]+)|(?:[a-z][a-zA-Z0-9]*(?:\.[a-z][a-zA-Z0-9]*)+)|(?:[A-Z][a-zA-Z]+\.[a-zA-Z]+\.All)|(?:microsoft\.[a-z]+\/[^\s|)]+))/g;
176
+ /**
177
+ * The sections of the Cloud book, by the permission their heading names. Many
178
+ * headings are the permission itself ("iam:CreatePolicyVersion",
179
+ * "Microsoft.Authorization/roleAssignments/write") or start with it
180
+ * ("iam:PassRole (+ a compute service)"). They cover permissions the
181
+ * escalation catalog has no technique for.
182
+ */
183
+ function sectionsByHeading(db) {
184
+ const cached = sectionsLoaded.get(db);
185
+ if (cached)
186
+ return cached;
187
+ const sections = new Map();
188
+ for (const row of db.prepare("SELECT path, outline FROM pages WHERE book = 'hacktricks-cloud'").all()) {
189
+ for (const heading of JSON.parse(row.outline)) {
190
+ const text = headingText(heading.text);
191
+ for (const match of text.matchAll(PERMISSION_IN_HEADING)) {
192
+ const key = match[1].toLowerCase();
193
+ sections.set(key, [...(sections.get(key) ?? []), { permission: match[1], page: row.path, heading: text }]);
194
+ }
195
+ }
196
+ }
197
+ // Privilege escalation pages first: a permission that names many sections is most often asked about as "what does this let me do?".
198
+ for (const [key, list] of sections) {
199
+ list.sort((a, b) => Number(!a.page.includes("privilege-escalation")) - Number(!b.page.includes("privilege-escalation")));
200
+ sections.set(key, list);
201
+ }
202
+ sectionsLoaded.set(db, sections);
203
+ return sections;
204
+ }
205
+ function sectionsFor(db, provider, grants) {
206
+ const sections = sectionsByHeading(db);
207
+ const found = [];
208
+ for (const grant of grants) {
209
+ const wildcard = grant.includes("*") || grant.includes("?");
210
+ const keys = wildcard ? [...sections.keys()].filter((key) => covers(grant, key, provider)) : [grant.toLowerCase()];
211
+ let shown = 0;
212
+ for (const key of keys) {
213
+ for (const section of sections.get(key) ?? []) {
214
+ if (shown === SECTIONS_PER_PERMISSION)
215
+ break;
216
+ found.push({ ...section, permission: grant });
217
+ shown++;
218
+ }
219
+ if (shown === SECTIONS_PER_PERMISSION)
220
+ break;
221
+ }
222
+ }
223
+ return found;
224
+ }
@@ -0,0 +1,195 @@
1
+ /**
2
+ * HackTricks Cloud's privilege escalation catalog: the shapes the indexer
3
+ * stores, and how a technique's `requires` tree is evaluated.
4
+ *
5
+ * The catalog is src/privilege-escalation-paths in that book: one file per
6
+ * service, each technique stating the permissions it needs, what it gains and
7
+ * the page section that explains it. The rated permission lists and Kubernetes
8
+ * rules of src/permission-categorizations are stored by the same indexer and
9
+ * read by src/permission-check.ts, which answers the tool call.
10
+ */
11
+ import { grantText } from "./kubernetes-rbac.js";
12
+ export const PROVIDERS = ["aws", "gcp", "azure", "k8s"];
13
+ export const SEVERITIES = ["critical", "high", "medium", "low"];
14
+ /** AWS and Azure permission names are case-insensitive; GCP's are not. */
15
+ const IGNORE_CASE = { aws: true, gcp: false, azure: true, k8s: false };
16
+ /** Keys of a requirement leaf that name a permission. Every other key is a condition that is not evaluated. */
17
+ export const PERMISSION_KEYS = {
18
+ aws: ["action"],
19
+ gcp: ["action"],
20
+ azure: ["action", "entra_permission", "graph_app_permission", "entra_role", "entra_catalog_role", "entra_pim_eligible_role"],
21
+ k8s: ["verb"],
22
+ };
23
+ export function isSeverity(value) {
24
+ return typeof value === "string" && SEVERITIES.includes(value);
25
+ }
26
+ /** The rated lists of a categorization file: its `permission_categories`, one list per severity. */
27
+ export function riskRows(provider, file) {
28
+ const categories = (file.permission_categories ?? {});
29
+ const rows = [];
30
+ for (const severity of SEVERITIES) {
31
+ const permissions = categories[severity];
32
+ if (!Array.isArray(permissions))
33
+ continue;
34
+ for (const permission of permissions) {
35
+ if (typeof permission === "string")
36
+ rows.push({ provider, permission, severity });
37
+ }
38
+ }
39
+ return rows;
40
+ }
41
+ export function combinationRows(provider, combinations) {
42
+ const rows = [];
43
+ for (const severity of SEVERITIES) {
44
+ const lists = combinations?.[severity];
45
+ if (!Array.isArray(lists))
46
+ continue;
47
+ for (const list of lists) {
48
+ if (Array.isArray(list) && list.every((p) => typeof p === "string")) {
49
+ rows.push({ provider, severity, permissions: list });
50
+ }
51
+ }
52
+ }
53
+ return rows;
54
+ }
55
+ /** Rows for the escalation table. A technique without an id, a requirement or a severity is skipped. */
56
+ export function escalationRows(provider, techniques) {
57
+ const rows = [];
58
+ for (const t of techniques) {
59
+ if (typeof t?.id !== "string" || t.requires === undefined || !isSeverity(t.severity))
60
+ continue;
61
+ rows.push({
62
+ provider,
63
+ id: t.id,
64
+ service: String(t.service ?? ""),
65
+ title: String(t.title ?? t.id),
66
+ summary: String(t.summary ?? ""),
67
+ severity: t.severity,
68
+ confidence: String(t.confidence ?? ""),
69
+ target: JSON.stringify({ kind: t.target?.kind ?? "", scope: t.target?.scope ?? "", outcome: t.target?.outcome ?? "" }),
70
+ source: typeof t.source === "string" ? t.source.replace(/^src\//, "") : "",
71
+ requires: JSON.stringify(t.requires),
72
+ needs: JSON.stringify(needsOf(provider, t.requires)),
73
+ conditions: JSON.stringify(sentencesOf(t.conditions)),
74
+ blockers: JSON.stringify(Array.isArray(t.blockers) ? t.blockers.map(String) : []),
75
+ mitigation: String(t.mitigation ?? ""),
76
+ });
77
+ }
78
+ return rows;
79
+ }
80
+ export function ruleRows(provider, rules) {
81
+ if (!Array.isArray(rules))
82
+ return [];
83
+ return rules
84
+ .filter((rule) => rule !== null && typeof rule === "object" && !Array.isArray(rule))
85
+ .map((rule, position) => ({ provider, position, rule: JSON.stringify(rule) }));
86
+ }
87
+ // --- the permissions a requirement names -------------------------------------------
88
+ /** The permission a leaf names, in the notation of `needs`. */
89
+ function permissionOf(provider, leaf) {
90
+ for (const key of PERMISSION_KEYS[provider]) {
91
+ const value = leaf[key];
92
+ if (typeof value === "string" && value.length > 0)
93
+ return value;
94
+ }
95
+ return null;
96
+ }
97
+ /** Every permission a `requires` tree names, without duplicates. */
98
+ export function needsOf(provider, requires) {
99
+ const needs = new Set();
100
+ visitLeaves(requires, (item) => {
101
+ if ("all_of" in item || "any_of" in item)
102
+ return; // a group names no permission of its own
103
+ const permission = provider === "k8s" ? grantText(item) : permissionOf(provider, item);
104
+ if (permission)
105
+ needs.add(permission);
106
+ });
107
+ return [...needs];
108
+ }
109
+ /**
110
+ * Call `leaf` for every requirement item: a list is a conjunction, `all_of` a
111
+ * conjunction, and each element of `any_of` an alternative.
112
+ */
113
+ export function visitLeaves(node, leaf) {
114
+ if (Array.isArray(node)) {
115
+ for (const item of node)
116
+ visitLeaves(item, leaf);
117
+ return;
118
+ }
119
+ if (node === null || typeof node !== "object")
120
+ return;
121
+ const item = node;
122
+ leaf(item);
123
+ visitLeaves(item.all_of, leaf);
124
+ visitLeaves(item.any_of, leaf);
125
+ }
126
+ /** Sentences of a `conditions` list, whose items are `{ id, description }` or plain strings. */
127
+ function sentencesOf(conditions) {
128
+ if (!Array.isArray(conditions))
129
+ return [];
130
+ return conditions
131
+ .map((c) => (c !== null && typeof c === "object" ? String(c.description ?? "") : String(c ?? "")))
132
+ .filter((sentence) => sentence.trim().length > 0);
133
+ }
134
+ export const allOf = (results) => (results.includes(false) ? false : results.includes(null) ? null : true);
135
+ export const anyOf = (results) => (results.includes(true) ? true : results.includes(null) ? null : false);
136
+ /**
137
+ * Does the principal hold everything a `requires` tree asks for? A list is a
138
+ * conjunction, `all_of` is a conjunction, and each element of `any_of` is an
139
+ * alternative. `holds(item, key)` answers for a leaf and its permission key;
140
+ * a leaf without a permission key (a condition on a resource, a scope or the
141
+ * request) is not a requirement of its own.
142
+ */
143
+ export function evalRequires(requires, permissionKeys, holds) {
144
+ let asked = false;
145
+ const result = evaluate(requires, permissionKeys, (leaf, key) => {
146
+ asked = true;
147
+ return holds(leaf, key);
148
+ });
149
+ // A requirement that names no permission at all (an empty one, or only
150
+ // conditions) depends on how things are configured, so it is never held.
151
+ return asked ? result : null;
152
+ }
153
+ function evaluate(requires, permissionKeys, holds) {
154
+ if (Array.isArray(requires))
155
+ return allOf(requires.map((item) => evaluate(item, permissionKeys, holds)));
156
+ if (requires === null || typeof requires !== "object")
157
+ return null;
158
+ const item = requires;
159
+ const results = [];
160
+ for (const [key, value] of Object.entries(item)) {
161
+ if (key === "all_of")
162
+ results.push(evaluate(value ?? [], permissionKeys, holds));
163
+ else if (key === "any_of") {
164
+ // An empty alternative would hold for everyone; the book does not write one, so it is not assumed.
165
+ const alternatives = Array.isArray(value) ? value : [];
166
+ results.push(anyOf(alternatives.map((alt) => (Array.isArray(alt) && alt.length === 0 ? null : evaluate(alt, permissionKeys, holds)))));
167
+ }
168
+ else if (permissionKeys.includes(key))
169
+ results.push(holds(item, key));
170
+ }
171
+ // An item that states only a condition ("the buildspec must be inline", "the
172
+ // verb starts with ...") is a requirement this module cannot evaluate. Next
173
+ // to a permission, as `request_context` is, it is simply not evaluated.
174
+ const group = item.all_of !== undefined || item.any_of !== undefined;
175
+ return results.length === 0 && !group ? null : allOf(results);
176
+ }
177
+ // --- matching names ------------------------------------------------------------------
178
+ const patterns = new Map();
179
+ /** `*` and `?` as IAM and Azure use them. */
180
+ function patternOf(grant, ignoreCase) {
181
+ const key = `${ignoreCase ? "i" : "s"}:${grant}`;
182
+ let pattern = patterns.get(key);
183
+ if (!pattern) {
184
+ pattern = new RegExp(`^${grant.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".")}$`, ignoreCase ? "i" : "");
185
+ patterns.set(key, pattern);
186
+ }
187
+ return pattern;
188
+ }
189
+ /** Does a held permission cover a required one? `*` and `?` are wildcards, as IAM and Azure use them. */
190
+ export function covers(grant, need, provider) {
191
+ const ignoreCase = IGNORE_CASE[provider];
192
+ if (!grant.includes("*") && !grant.includes("?"))
193
+ return ignoreCase ? grant.toLowerCase() === need.toLowerCase() : grant === need;
194
+ return patternOf(grant, ignoreCase).test(need);
195
+ }
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Keep the served index current without waiting for a new package install.
3
+ *
4
+ * The package ships with the index that was current when it was published.
5
+ * After startup the server asks the project's latest GitHub release for its
6
+ * data/meta.json (a few hundred bytes) and, if that release carries a newer
7
+ * index, downloads it in the background and swaps it in. Tool calls never
8
+ * wait on the network: the index opened at startup answers until a newer one
9
+ * is ready. Any failure (no network, a proxy, a rate limit, a release
10
+ * without index files, a corrupt download) leaves the current index in place.
11
+ *
12
+ * Environment:
13
+ * HACKTRICKS_OFFLINE=1 never touch the network
14
+ * HACKTRICKS_INDEX_URL base URL to fetch index files from, instead of
15
+ * this project's releases
16
+ * HACKTRICKS_CACHE_DIR where downloaded indexes are kept
17
+ */
18
+ import fs from "node:fs";
19
+ import os from "node:os";
20
+ import path from "node:path";
21
+ import { fileURLToPath } from "node:url";
22
+ import { INDEX_SCHEMA, openDbReadonly } from "./db.js";
23
+ /** How often a long-running server looks for a newer index. */
24
+ const CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000;
25
+ const META_TIMEOUT_MS = 5_000;
26
+ const DOWNLOAD_TIMEOUT_MS = 10 * 60_000;
27
+ const FILES = ["meta.json", "toc.json", "hacktricks.db"];
28
+ /** A download slower than this (see DOWNLOAD_TIMEOUT_MS) cannot still be in progress. */
29
+ const STALE_AFTER_MS = 60 * 60_000;
30
+ /** Open the index stored in a directory: the package's data/, or a downloaded copy. */
31
+ export function openIndex(dir, dbPath = path.join(dir, "hacktricks.db")) {
32
+ const read = (name) => {
33
+ const file = path.join(dir, name);
34
+ return fs.existsSync(file) ? fs.readFileSync(file, "utf8") : null;
35
+ };
36
+ const meta = read("meta.json");
37
+ const toc = read("toc.json");
38
+ return {
39
+ dir,
40
+ db: openDbReadonly(dbPath),
41
+ meta: meta ? JSON.parse(meta) : { syncedAt: "unknown", pageCount: 0 },
42
+ toc: toc ? JSON.parse(toc) : {},
43
+ };
44
+ }
45
+ function cacheDir() {
46
+ if (process.env.HACKTRICKS_CACHE_DIR)
47
+ return process.env.HACKTRICKS_CACHE_DIR;
48
+ if (process.platform === "win32") {
49
+ return path.join(process.env.LOCALAPPDATA ?? os.homedir(), "hacktricks-mcp", "cache");
50
+ }
51
+ if (process.platform === "darwin")
52
+ return path.join(os.homedir(), "Library", "Caches", "hacktricks-mcp");
53
+ return path.join(process.env.XDG_CACHE_HOME ?? path.join(os.homedir(), ".cache"), "hacktricks-mcp");
54
+ }
55
+ /** Index files are attached to this project's releases; package.json is the one place the repository is named. */
56
+ function releaseUrl(name) {
57
+ const pkgRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
58
+ const repository = JSON.parse(fs.readFileSync(path.join(pkgRoot, "package.json"), "utf8")).repository.url;
59
+ const base = process.env.HACKTRICKS_INDEX_URL ?? `${repository.replace(/^git\+|\.git$/g, "")}/releases/latest/download`;
60
+ return `${base.replace(/\/+$/, "")}/${name}`;
61
+ }
62
+ /** Best effort: on Windows a folder another server process still reads from cannot be deleted. */
63
+ function remove(dir) {
64
+ try {
65
+ fs.rmSync(dir, { recursive: true, force: true });
66
+ }
67
+ catch {
68
+ // still in use elsewhere
69
+ }
70
+ }
71
+ async function fetchFile(name, timeoutMs) {
72
+ const res = await fetch(releaseUrl(name), { signal: AbortSignal.timeout(timeoutMs) });
73
+ if (!res.ok)
74
+ throw new Error(`${name}: HTTP ${res.status}`);
75
+ return res;
76
+ }
77
+ /** A downloaded index counts only if it is whole and readable: the advertised size, the expected columns, the advertised page count. */
78
+ function usable(index) {
79
+ try {
80
+ const pages = index.db.prepare("SELECT count(book) AS n FROM pages").get().n;
81
+ return (fs.statSync(path.join(index.dir, "hacktricks.db")).size === index.meta.dbBytes &&
82
+ pages === index.meta.pageCount &&
83
+ Object.keys(index.toc).length > 0);
84
+ }
85
+ catch {
86
+ return false;
87
+ }
88
+ }
89
+ /** The index of the latest release, if it is newer than `syncedAt` and this server can read it. */
90
+ async function newerIndex(syncedAt) {
91
+ const meta = (await (await fetchFile("meta.json", META_TIMEOUT_MS)).json());
92
+ if (meta.schema !== INDEX_SCHEMA || typeof meta.syncedAt !== "string" || meta.syncedAt <= syncedAt) {
93
+ return null;
94
+ }
95
+ const cache = cacheDir();
96
+ fs.mkdirSync(cache, { recursive: true });
97
+ const dir = path.join(cache, `index-${INDEX_SCHEMA}-${meta.syncedAt.replace(/\D/g, "")}`);
98
+ if (!fs.existsSync(path.join(dir, "hacktricks.db"))) {
99
+ // Remove what a process that died mid-download left behind.
100
+ for (const name of fs.readdirSync(cache)) {
101
+ const stale = path.join(cache, name);
102
+ if (name.startsWith("tmp-") && Date.now() - fs.statSync(stale).mtimeMs > STALE_AFTER_MS)
103
+ remove(stale);
104
+ }
105
+ const staging = fs.mkdtempSync(path.join(cache, "tmp-"));
106
+ try {
107
+ for (const name of FILES) {
108
+ const res = await fetchFile(name, DOWNLOAD_TIMEOUT_MS);
109
+ fs.writeFileSync(path.join(staging, name), Buffer.from(await res.arrayBuffer()));
110
+ }
111
+ const index = openIndex(staging);
112
+ const complete = usable(index);
113
+ // Windows refuses to move or delete a file that is still open.
114
+ index.db.close();
115
+ if (!complete)
116
+ throw new Error("downloaded index is incomplete");
117
+ // The folder appears under its final name only once it is complete.
118
+ // Another server process may have installed the same index meanwhile.
119
+ try {
120
+ fs.renameSync(staging, dir);
121
+ }
122
+ catch {
123
+ // already installed by that process
124
+ }
125
+ }
126
+ finally {
127
+ remove(staging);
128
+ }
129
+ }
130
+ return openIndex(dir);
131
+ }
132
+ /**
133
+ * The newest index an earlier run of this server downloaded, when it is newer
134
+ * than `current` and still whole; otherwise null. Starting on it means a
135
+ * session uses the latest index it already has from its first tool call, with
136
+ * or without a network.
137
+ */
138
+ export function newestCachedIndex(current) {
139
+ try {
140
+ const cache = cacheDir();
141
+ if (!fs.existsSync(cache))
142
+ return null;
143
+ // Folder names end in the sync time as digits, so they sort oldest first.
144
+ const folders = fs.readdirSync(cache).filter((name) => name.startsWith(`index-${INDEX_SCHEMA}-`)).sort();
145
+ const newest = folders[folders.length - 1];
146
+ if (!newest)
147
+ return null;
148
+ const index = openIndex(path.join(cache, newest));
149
+ if (usable(index) && index.meta.syncedAt > current.meta.syncedAt)
150
+ return index;
151
+ index.db.close();
152
+ }
153
+ catch {
154
+ // an unreadable cache is no reason not to start on the bundled index
155
+ }
156
+ return null;
157
+ }
158
+ /**
159
+ * Check for a newer index now and every few hours. `active` is the index
160
+ * being served; `swap` is called with a verified newer one, between tool calls.
161
+ */
162
+ export function refreshInBackground(active, swap) {
163
+ const check = async () => {
164
+ try {
165
+ const next = await newerIndex(active().meta.syncedAt);
166
+ if (!next)
167
+ return;
168
+ swap(next);
169
+ console.error(`hacktricks-mcp: using index synced ${next.meta.syncedAt} (${next.meta.pageCount} pages)`);
170
+ // Indexes older than the one now in use are not needed anymore.
171
+ const cache = cacheDir();
172
+ for (const name of fs.readdirSync(cache)) {
173
+ if (name.startsWith("index-") && name !== path.basename(next.dir))
174
+ remove(path.join(cache, name));
175
+ }
176
+ }
177
+ catch (err) {
178
+ // "fetch failed" alone does not say why; Node keeps the reason on `cause`.
179
+ const cause = err.cause?.message;
180
+ console.error(`hacktricks-mcp: keeping the current index, refresh failed: ${err.message}${cause ? ` (${cause})` : ""}`);
181
+ }
182
+ };
183
+ void check();
184
+ setInterval(() => void check(), CHECK_INTERVAL_MS).unref();
185
+ }