@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.
- package/README.md +51 -9
- package/data/hacktricks.db +0 -0
- package/data/meta.json +8 -4
- package/data/toc.json +14631 -5537
- package/dist/books.js +27 -0
- package/dist/db.js +349 -64
- package/dist/kubernetes-rbac.js +138 -0
- package/dist/markdown.js +12 -0
- package/dist/permission-check.js +224 -0
- package/dist/permissions.js +195 -0
- package/dist/refresh.js +185 -0
- package/dist/server.js +331 -74
- package/dist/toc.js +25 -5
- package/package.json +10 -3
package/dist/books.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export const BOOKS = [
|
|
2
|
+
{
|
|
3
|
+
id: "hacktricks",
|
|
4
|
+
title: "HackTricks",
|
|
5
|
+
repository: "HackTricks-wiki/hacktricks",
|
|
6
|
+
site: "https://hacktricks.wiki/en/",
|
|
7
|
+
},
|
|
8
|
+
{
|
|
9
|
+
id: "hacktricks-cloud",
|
|
10
|
+
title: "HackTricks Cloud",
|
|
11
|
+
repository: "HackTricks-wiki/hacktricks-cloud",
|
|
12
|
+
site: "https://cloud.hacktricks.wiki/en/",
|
|
13
|
+
},
|
|
14
|
+
];
|
|
15
|
+
/** The markdown source of a page on GitHub. */
|
|
16
|
+
export function sourceUrl(book, pagePath) {
|
|
17
|
+
return `https://github.com/${book.repository}/blob/master/src/${pagePath}`;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The rendered page on the public wiki. A `README.md` is the index of its
|
|
21
|
+
* folder and has no page of its own: asking the site for `.../README.html`
|
|
22
|
+
* returns its not-found page.
|
|
23
|
+
*/
|
|
24
|
+
export function wikiUrl(book, pagePath) {
|
|
25
|
+
const folder = /^(.*)\/README\.md$/.exec(pagePath);
|
|
26
|
+
return book.site + (folder ? `${folder[1]}/` : pagePath === "README.md" ? "" : pagePath.replace(/\.md$/, ".html"));
|
|
27
|
+
}
|
package/dist/db.js
CHANGED
|
@@ -5,15 +5,27 @@
|
|
|
5
5
|
import { DatabaseSync } from "node:sqlite";
|
|
6
6
|
import fs from "node:fs";
|
|
7
7
|
import path from "node:path";
|
|
8
|
+
/**
|
|
9
|
+
* Layout of the index files in data/. Bump it when a rebuild must reach every
|
|
10
|
+
* index although upstream has not moved: a layout change, or a change in how
|
|
11
|
+
* the indexer turns pages into rows (this file, src/toc.ts, src/markdown.ts,
|
|
12
|
+
* src/permissions.ts).
|
|
13
|
+
* The sync script then rebuilds, and a server ignores indexes built for another
|
|
14
|
+
* number (src/refresh.ts).
|
|
15
|
+
*/
|
|
16
|
+
export const INDEX_SCHEMA = 3;
|
|
8
17
|
const SCHEMA = `
|
|
9
18
|
CREATE TABLE IF NOT EXISTS pages (
|
|
10
19
|
page_id INTEGER PRIMARY KEY,
|
|
11
|
-
|
|
20
|
+
book TEXT NOT NULL,
|
|
21
|
+
path TEXT NOT NULL,
|
|
12
22
|
title TEXT NOT NULL,
|
|
13
23
|
category TEXT NOT NULL DEFAULT '',
|
|
14
24
|
url TEXT NOT NULL DEFAULT '',
|
|
25
|
+
wiki TEXT NOT NULL DEFAULT '',
|
|
15
26
|
outline TEXT NOT NULL DEFAULT '[]',
|
|
16
|
-
content TEXT NOT NULL
|
|
27
|
+
content TEXT NOT NULL,
|
|
28
|
+
UNIQUE (book, path)
|
|
17
29
|
);
|
|
18
30
|
CREATE VIRTUAL TABLE IF NOT EXISTS pages_fts USING fts5(
|
|
19
31
|
title, path, category, content,
|
|
@@ -24,6 +36,42 @@ CREATE TRIGGER IF NOT EXISTS pages_ai AFTER INSERT ON pages BEGIN
|
|
|
24
36
|
INSERT INTO pages_fts(rowid, title, path, category, content)
|
|
25
37
|
VALUES (new.page_id, new.title, new.path, new.category, new.content);
|
|
26
38
|
END;
|
|
39
|
+
|
|
40
|
+
-- HackTricks Cloud's permission data (src/permissions.ts), for hacktricks_cloud_permissions.
|
|
41
|
+
CREATE TABLE IF NOT EXISTS permission_risk (
|
|
42
|
+
provider TEXT NOT NULL,
|
|
43
|
+
permission TEXT NOT NULL,
|
|
44
|
+
severity TEXT NOT NULL,
|
|
45
|
+
PRIMARY KEY (provider, permission)
|
|
46
|
+
);
|
|
47
|
+
CREATE TABLE IF NOT EXISTS permission_combination (
|
|
48
|
+
provider TEXT NOT NULL,
|
|
49
|
+
severity TEXT NOT NULL,
|
|
50
|
+
permissions TEXT NOT NULL -- JSON list; every permission must be held
|
|
51
|
+
);
|
|
52
|
+
CREATE TABLE IF NOT EXISTS escalation (
|
|
53
|
+
provider TEXT NOT NULL,
|
|
54
|
+
id TEXT NOT NULL,
|
|
55
|
+
service TEXT NOT NULL,
|
|
56
|
+
title TEXT NOT NULL,
|
|
57
|
+
summary TEXT NOT NULL,
|
|
58
|
+
severity TEXT NOT NULL,
|
|
59
|
+
confidence TEXT NOT NULL,
|
|
60
|
+
target TEXT NOT NULL, -- JSON { kind, scope, outcome }
|
|
61
|
+
source TEXT NOT NULL, -- <page path>#<anchor>
|
|
62
|
+
requires TEXT NOT NULL, -- JSON, as the book writes it
|
|
63
|
+
needs TEXT NOT NULL, -- JSON list of the permissions named
|
|
64
|
+
conditions TEXT NOT NULL, -- JSON list of sentences
|
|
65
|
+
blockers TEXT NOT NULL, -- JSON list of identifiers
|
|
66
|
+
mitigation TEXT NOT NULL,
|
|
67
|
+
PRIMARY KEY (provider, id)
|
|
68
|
+
);
|
|
69
|
+
CREATE TABLE IF NOT EXISTS permission_rule (
|
|
70
|
+
provider TEXT NOT NULL,
|
|
71
|
+
position INTEGER NOT NULL, -- the first rule that matches wins
|
|
72
|
+
rule TEXT NOT NULL, -- JSON, as the book writes it
|
|
73
|
+
PRIMARY KEY (provider, position)
|
|
74
|
+
);
|
|
27
75
|
`;
|
|
28
76
|
export function createDb(dbPath) {
|
|
29
77
|
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
|
@@ -31,6 +79,38 @@ export function createDb(dbPath) {
|
|
|
31
79
|
db.exec(SCHEMA);
|
|
32
80
|
return db;
|
|
33
81
|
}
|
|
82
|
+
/** Fill the permission tables with what src/permissions.ts made of HackTricks Cloud's data. */
|
|
83
|
+
export function insertPermissionData(db, data) {
|
|
84
|
+
const inTransaction = (run) => {
|
|
85
|
+
db.exec("BEGIN");
|
|
86
|
+
try {
|
|
87
|
+
const result = run();
|
|
88
|
+
db.exec("COMMIT");
|
|
89
|
+
return result;
|
|
90
|
+
}
|
|
91
|
+
catch (err) {
|
|
92
|
+
db.exec("ROLLBACK");
|
|
93
|
+
throw err;
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
inTransaction(() => {
|
|
97
|
+
const risk = db.prepare("INSERT INTO permission_risk (provider, permission, severity) VALUES (?, ?, ?)");
|
|
98
|
+
for (const row of data.risk)
|
|
99
|
+
risk.run(row.provider, row.permission, row.severity);
|
|
100
|
+
const combination = db.prepare("INSERT INTO permission_combination (provider, severity, permissions) VALUES (?, ?, ?)");
|
|
101
|
+
for (const row of data.combinations)
|
|
102
|
+
combination.run(row.provider, row.severity, JSON.stringify(row.permissions));
|
|
103
|
+
const escalation = db.prepare(`INSERT INTO escalation (provider, id, service, title, summary, severity, confidence, target, source,
|
|
104
|
+
requires, needs, conditions, blockers, mitigation)
|
|
105
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
106
|
+
for (const row of data.escalations) {
|
|
107
|
+
escalation.run(row.provider, row.id, row.service, row.title, row.summary, row.severity, row.confidence, row.target, row.source, row.requires, row.needs, row.conditions, row.blockers, row.mitigation);
|
|
108
|
+
}
|
|
109
|
+
const rule = db.prepare("INSERT INTO permission_rule (provider, position, rule) VALUES (?, ?, ?)");
|
|
110
|
+
for (const row of data.rules)
|
|
111
|
+
rule.run(row.provider, row.position, row.rule);
|
|
112
|
+
});
|
|
113
|
+
}
|
|
34
114
|
export function openDbReadonly(dbPath) {
|
|
35
115
|
if (!fs.existsSync(dbPath)) {
|
|
36
116
|
throw new Error(`HackTricks index not found at ${dbPath}. Run "npm run sync" to build it, or reinstall the package.`);
|
|
@@ -38,8 +118,8 @@ export function openDbReadonly(dbPath) {
|
|
|
38
118
|
return new DatabaseSync(dbPath, { readOnly: true });
|
|
39
119
|
}
|
|
40
120
|
export function insertPage(db, page) {
|
|
41
|
-
db.prepare(`INSERT INTO pages (path, title, category, url, outline, content)
|
|
42
|
-
VALUES (?, ?, ?, ?, ?, ?)`).run(page.path, page.title, page.category, page.url, page.outline, page.content);
|
|
121
|
+
db.prepare(`INSERT INTO pages (book, path, title, category, url, wiki, outline, content)
|
|
122
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(page.book, page.path, page.title, page.category, page.url, page.wiki, page.outline, page.content);
|
|
43
123
|
}
|
|
44
124
|
/**
|
|
45
125
|
* Common security abbreviations agents and users actually type.
|
|
@@ -64,86 +144,291 @@ const ALIASES = {
|
|
|
64
144
|
revshell: "reverse shell",
|
|
65
145
|
};
|
|
66
146
|
/**
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
147
|
+
* Function words and chat filler. They carry no topic, and requiring every word
|
|
148
|
+
* of a question lets long hub pages crowd out the page named after the
|
|
149
|
+
* technique, so they are dropped from queries long enough to contain them.
|
|
150
|
+
*
|
|
151
|
+
* Deliberately absent: words that can be a topic of their own, such as
|
|
152
|
+
* "use" (use-after-free), "find" (the command), "make" or "at".
|
|
71
153
|
*/
|
|
72
|
-
|
|
73
|
-
|
|
154
|
+
export const STOPWORDS = new Set(("a an the and or not of in on to from with by as for if then than so up out about into " +
|
|
155
|
+
"is are was were be been being am do does did done have has had will would could should can " +
|
|
156
|
+
"may might must shall i me my mine we us our you your he she it its they them their " +
|
|
157
|
+
"this that these those there here what which who whom whose when where why how " +
|
|
158
|
+
"best way ways easily quickly please need want help via step steps").split(" "));
|
|
159
|
+
/** Split a free-text query into the terms that carry meaning. */
|
|
160
|
+
function queryTerms(query) {
|
|
161
|
+
const all = query
|
|
74
162
|
.split(/\s+/)
|
|
75
163
|
.map((t) => t.replace(/[^\w.-]/g, ""))
|
|
76
164
|
.filter((t) => t.length > 0);
|
|
77
|
-
//
|
|
78
|
-
//
|
|
79
|
-
const
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
165
|
+
// Short queries are already keywords, and every word may matter in them
|
|
166
|
+
// ("use after free"). Filler only creeps into longer ones.
|
|
167
|
+
const meaningful = all.length > 3 ? all.filter((t) => !STOPWORDS.has(t.toLowerCase())) : all;
|
|
168
|
+
return meaningful.length > 0 ? meaningful : all;
|
|
169
|
+
}
|
|
170
|
+
const quote = (s) => `"${s.replace(/"/g, '""')}"`;
|
|
171
|
+
/**
|
|
172
|
+
* Endings dropped from a query word before it is looked for in titles and
|
|
173
|
+
* paths, applied in turn and only while at least `minStem` letters remain.
|
|
174
|
+
* A title uses one word form and a question another ("Privilege Escalation"
|
|
175
|
+
* against "escalate privileges"); the full-text match is stemmed, and without
|
|
176
|
+
* this the title match was not: "escalate" never matched "escalation".
|
|
177
|
+
*/
|
|
178
|
+
const NAME_ENDINGS = [
|
|
179
|
+
["sses", "ss", 4],
|
|
180
|
+
["ies", "", 4],
|
|
181
|
+
["es", "", 4],
|
|
182
|
+
["s", "", 3],
|
|
183
|
+
["ation", "", 4],
|
|
184
|
+
["ment", "", 4],
|
|
185
|
+
["ing", "", 4],
|
|
186
|
+
["ate", "", 4],
|
|
187
|
+
["ed", "", 4],
|
|
188
|
+
];
|
|
189
|
+
/** The stem prefix a word is matched by in titles and paths: "escalating" gives "escalat". */
|
|
190
|
+
function nameKey(word) {
|
|
191
|
+
let w = word.toLowerCase();
|
|
192
|
+
for (let rule = NAME_ENDINGS.find(([ending, , minStem]) => w.endsWith(ending) && w.length - ending.length >= minStem); rule;) {
|
|
193
|
+
w = w.slice(0, w.length - rule[0].length) + rule[1];
|
|
194
|
+
rule = NAME_ENDINGS.find(([ending, , minStem]) => w.endsWith(ending) && w.length - ending.length >= minStem);
|
|
195
|
+
}
|
|
196
|
+
return w;
|
|
197
|
+
}
|
|
198
|
+
/** FTS5 match for one term: the term itself, or an abbreviation plus its expansion. */
|
|
199
|
+
function termExpr(term) {
|
|
200
|
+
const alias = ALIASES[term.toLowerCase()];
|
|
201
|
+
return alias ? `(${quote(term)} OR ${alias.split(" ").map(quote).join(" OR ")})` : quote(term);
|
|
202
|
+
}
|
|
203
|
+
const pageCounts = new WeakMap();
|
|
204
|
+
function pageCount(db) {
|
|
205
|
+
let n = pageCounts.get(db);
|
|
206
|
+
if (n === undefined) {
|
|
207
|
+
n = db.prepare("SELECT count(*) AS n FROM pages").get().n;
|
|
208
|
+
pageCounts.set(db, n);
|
|
209
|
+
}
|
|
210
|
+
return n;
|
|
211
|
+
}
|
|
212
|
+
// Title and path with separators folded to spaces. A term is credited when a
|
|
213
|
+
// word in there starts with its stem (NAME_ENDINGS), so "escalate" matches
|
|
214
|
+
// "escalation" and "string" matches "strings", while "nc" does not match
|
|
215
|
+
// "function".
|
|
216
|
+
const NAME_SQL = "lower(replace(replace(replace(replace(replace(replace(p.title || ' ' || p.path, '/', ' '), '-', ' '), '_', ' '), '.', ' '), '(', ' '), ')', ' '))";
|
|
217
|
+
const TERM_IN_NAME_SQL = `' ' || ${NAME_SQL} || ' ' LIKE '% ' || ? || '%'`;
|
|
218
|
+
const namingCounts = new WeakMap();
|
|
219
|
+
/** How many pages have each of these words starting a word in its title or path. */
|
|
220
|
+
function pagesNaming(db, words) {
|
|
221
|
+
let counts = namingCounts.get(db);
|
|
222
|
+
if (!counts)
|
|
223
|
+
namingCounts.set(db, (counts = new Map()));
|
|
224
|
+
const key = words.join(" ");
|
|
225
|
+
let n = counts.get(key);
|
|
226
|
+
if (n === undefined) {
|
|
227
|
+
n = db
|
|
228
|
+
.prepare(`SELECT count(*) AS n FROM pages p WHERE ${words.map(() => TERM_IN_NAME_SQL).join(" AND ")}`)
|
|
229
|
+
.get(...words).n;
|
|
230
|
+
counts.set(key, n);
|
|
231
|
+
}
|
|
232
|
+
return n;
|
|
89
233
|
}
|
|
234
|
+
/**
|
|
235
|
+
* A term found in at most this fraction of the pages is treated as specific.
|
|
236
|
+
* Containing the specific terms of a query is what earns the match bonus:
|
|
237
|
+
* hub pages contain every common word anyway, so matching those says nothing.
|
|
238
|
+
*/
|
|
239
|
+
const SPECIFIC_FRACTION = 0.2;
|
|
240
|
+
/**
|
|
241
|
+
* How likely a page about a term is to name it in its title or path. Name
|
|
242
|
+
* credit is a likelihood ratio on it (see searchPages): each query term a page
|
|
243
|
+
* names is worth ln(NAMING_RATE / share of pages naming it), each term it does
|
|
244
|
+
* not name costs ln(1 / (1 - NAMING_RATE)).
|
|
245
|
+
*/
|
|
246
|
+
const NAMING_RATE = 0.6;
|
|
247
|
+
/**
|
|
248
|
+
* A term found in at least this fraction of the pages takes no part in name
|
|
249
|
+
* credit (it gains a page nothing and costs it nothing), with one exception
|
|
250
|
+
* below. Name rarity alone overrates such words: two thirds of the pages
|
|
251
|
+
* contain "id" but only 42 titles name it, so it was worth as much as a
|
|
252
|
+
* technique name, and "Az - Entra ID Logs" outranked "Az - EntraID Privesc"
|
|
253
|
+
* for a question about privilege escalation in Entra ID.
|
|
254
|
+
*/
|
|
255
|
+
const NAME_SHARE = 0.5;
|
|
256
|
+
/**
|
|
257
|
+
* The exception: a very common term still counts when the pages that contain
|
|
258
|
+
* it name it in their title or path at least this often, because then it is
|
|
259
|
+
* what pages are about. Pages that contain "id" name it 2% of the time. Pages
|
|
260
|
+
* that contain "post" name it 27% of the time, although "post" is in 61% of
|
|
261
|
+
* the pages because Cloud pages repeat their phase names; left out, "S3 post
|
|
262
|
+
* exploitation" returned S3 privesc and enum pages first.
|
|
263
|
+
*/
|
|
264
|
+
const TITLE_RATE = 0.05;
|
|
265
|
+
/**
|
|
266
|
+
* How much holding every specific query term is worth, on the same scale as
|
|
267
|
+
* name credit: as much as naming a term that about one page in 250 names.
|
|
268
|
+
* Lower lets a page whose title carries a rare word win while missing an
|
|
269
|
+
* incidental one; higher favours pages that contain all the specific words.
|
|
270
|
+
* Measured on tests/scenarios.json with scripts/eval-workflow.ts: every value
|
|
271
|
+
* from 4 to 10 ends with the same questions found by the route the skill
|
|
272
|
+
* gives, and the rest moves by a question or two either way.
|
|
273
|
+
*/
|
|
274
|
+
const MATCH_BONUS = 5;
|
|
275
|
+
/** How many candidates to consider per pool; only `limit` are returned. */
|
|
276
|
+
const POOL = 50;
|
|
277
|
+
/**
|
|
278
|
+
* Rank pages for a free-text query.
|
|
279
|
+
*
|
|
280
|
+
* 1. Drop filler words, so a typed question behaves like the keywords in it.
|
|
281
|
+
* 2. Collect two pools by text relevance: pages that contain every specific
|
|
282
|
+
* term, and pages that contain any term. A question often carries an
|
|
283
|
+
* incidental word ("bug") that the page named after the technique does not
|
|
284
|
+
* use, so matching everything is not required of the best answer.
|
|
285
|
+
* 3. Rank the combined pool by name credit, a likelihood ratio on how few
|
|
286
|
+
* pages name each query term in their title or path (by stem, and only
|
|
287
|
+
* for terms that are not in half of the pages, see NAME_SHARE), plus a
|
|
288
|
+
* bonus for holding every specific term. That puts the page named after
|
|
289
|
+
* the technique above hub pages that merely contain the words.
|
|
290
|
+
*
|
|
291
|
+
* Measured by scripts/eval.ts and scripts/eval-workflow.ts; the numbers and
|
|
292
|
+
* the ideas that were rejected are in docs/development.md.
|
|
293
|
+
*/
|
|
90
294
|
export function searchPages(db, query, category, limit) {
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
const boostSql = rawTerms
|
|
99
|
-
.map((t) => {
|
|
100
|
-
const variants = [t, ...(ALIASES[t.toLowerCase()]?.split(" ") ?? [])];
|
|
101
|
-
const cond = variants
|
|
102
|
-
.map((v) => `lower(p.title || ' ' || p.path) LIKE '%' || ? || '%'`)
|
|
103
|
-
.join(" OR ");
|
|
104
|
-
return `(CASE WHEN ${cond} THEN 1 ELSE 0 END)`;
|
|
295
|
+
// A term absent from the index can neither match nor say anything about a page.
|
|
296
|
+
// Its rarity is judged as typed: "ssrf" stays specific even though its
|
|
297
|
+
// expansion includes words as common as "server".
|
|
298
|
+
const terms = queryTerms(query)
|
|
299
|
+
.map((term) => {
|
|
300
|
+
const own = pagesMatching(db, quote(term));
|
|
301
|
+
return { term, pages: own > 0 ? own : pagesMatching(db, termExpr(term)) };
|
|
105
302
|
})
|
|
106
|
-
.
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
303
|
+
.filter((t) => t.pages > 0);
|
|
304
|
+
if (terms.length === 0)
|
|
305
|
+
return [];
|
|
306
|
+
const total = pageCount(db);
|
|
307
|
+
// Name credit, reported per term. A page about a term usually names it, so a
|
|
308
|
+
// term is worth more in a title the fewer pages name it ("capabilities" is
|
|
309
|
+
// in hundreds of page bodies but a handful of titles). An abbreviation counts
|
|
310
|
+
// by its own spelling first ("privesc" outranks the common words it expands
|
|
311
|
+
// to), and a term with separators needs all of its parts ("ld.so.conf").
|
|
312
|
+
// Terms that are everywhere are left out unless pages that contain them
|
|
313
|
+
// name them often enough to be what the page is about.
|
|
314
|
+
const named = terms.filter((t) => t.pages < total * NAME_SHARE || pagesNaming(db, [nameKey(t.term)]) >= t.pages * TITLE_RATE);
|
|
315
|
+
const creditSql = [];
|
|
316
|
+
const creditParams = [];
|
|
317
|
+
named.forEach(({ term }, i) => {
|
|
318
|
+
const alias = ALIASES[term.toLowerCase()];
|
|
319
|
+
const spellings = alias
|
|
320
|
+
? [term, ...alias.split(" ")].map((word) => [nameKey(word)])
|
|
321
|
+
: [term.split(/[^\w]+/).filter(Boolean).map(nameKey)];
|
|
322
|
+
const weighted = spellings
|
|
323
|
+
.map((words) => ({ words, naming: pagesNaming(db, words) }))
|
|
324
|
+
.map((s) => ({ ...s, weight: s.naming > 0 ? Math.log((NAMING_RATE * total) / s.naming) : 0 }))
|
|
325
|
+
.filter((s) => s.weight > 0)
|
|
326
|
+
.sort((a, b) => b.weight - a.weight);
|
|
327
|
+
creditParams.push(...weighted.flatMap((s) => [...s.words, s.weight]));
|
|
328
|
+
// A term no page names can earn no credit anywhere.
|
|
329
|
+
creditSql.push(weighted.length === 0
|
|
330
|
+
? `0 AS c${i}`
|
|
331
|
+
: `(CASE ${weighted.map((s) => `WHEN ${s.words.map(() => TERM_IN_NAME_SQL).join(" AND ")} THEN ?`).join(" ")} ELSE 0 END) AS c${i}`);
|
|
332
|
+
});
|
|
333
|
+
// Each query term a page does not name counts against it, so a title that
|
|
334
|
+
// covers the query beats one naming a single rare word of it.
|
|
335
|
+
const creditOf = (row) => {
|
|
336
|
+
let credit = Math.log(1 - NAMING_RATE) * named.length;
|
|
337
|
+
for (let i = 0; i < named.length; i++)
|
|
338
|
+
credit += Number(row[`c${i}`]);
|
|
339
|
+
return credit;
|
|
340
|
+
};
|
|
341
|
+
// Snippets are the expensive part of a row, so candidates are fetched without
|
|
342
|
+
// them and computed only for the rows returned. Those that hold every
|
|
343
|
+
// specific term are also taken by name credit, not just by relevance: a long
|
|
344
|
+
// canonical page can rank low on relevance (bm25) while clearly naming the
|
|
345
|
+
// topic.
|
|
346
|
+
const candidates = (expr, alsoByCredit = false) => {
|
|
347
|
+
const select = (order) => `
|
|
348
|
+
SELECT p.page_id, p.book, p.path, p.title, p.category, p.url, p.wiki, length(p.content) AS chars,
|
|
349
|
+
bm25(pages_fts, 10.0, 8.0, 5.0, 1.0) AS relevance${creditSql.length ? `, ${creditSql.join(", ")}` : ""}
|
|
117
350
|
FROM pages_fts JOIN pages p ON p.page_id = pages_fts.rowid
|
|
118
351
|
WHERE pages_fts MATCH ?
|
|
119
352
|
${category ? "AND lower(p.category) LIKE lower(?)" : ""}
|
|
120
|
-
ORDER BY ${
|
|
353
|
+
ORDER BY ${order}
|
|
121
354
|
LIMIT ?`;
|
|
122
|
-
|
|
355
|
+
// Bound in the order the placeholders appear in the SQL text.
|
|
356
|
+
const params = [...creditParams, expr];
|
|
123
357
|
if (category)
|
|
124
358
|
params.push(`%${category}%`);
|
|
125
|
-
params.push(
|
|
126
|
-
|
|
359
|
+
params.push(POOL);
|
|
360
|
+
const toHit = (row) => ({
|
|
361
|
+
page_id: Number(row.page_id),
|
|
362
|
+
book: String(row.book),
|
|
363
|
+
path: String(row.path),
|
|
364
|
+
title: String(row.title),
|
|
365
|
+
category: String(row.category),
|
|
366
|
+
url: String(row.url),
|
|
367
|
+
wiki: String(row.wiki),
|
|
368
|
+
chars: Number(row.chars),
|
|
369
|
+
relevance: Number(row.relevance),
|
|
370
|
+
boost: creditOf(row),
|
|
371
|
+
});
|
|
372
|
+
const byRelevance = db.prepare(select("relevance")).all(...params).map(toHit);
|
|
373
|
+
if (!alsoByCredit)
|
|
374
|
+
return byRelevance;
|
|
375
|
+
const seen = new Set(byRelevance.map((h) => h.page_id));
|
|
376
|
+
// A query whose every term is too common for name credit has no credit to order by.
|
|
377
|
+
const byCreditOrder = creditSql.length ? `(${creditSql.map((_, i) => `(c${i})`).join(" + ")}) DESC` : "relevance";
|
|
378
|
+
const byCredit = db.prepare(select(byCreditOrder)).all(...params).map(toHit);
|
|
379
|
+
return [...byRelevance, ...byCredit.filter((h) => !seen.has(h.page_id))];
|
|
127
380
|
};
|
|
128
|
-
const
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
381
|
+
const anyExpr = terms.map((t) => termExpr(t.term)).join(" OR ");
|
|
382
|
+
const specific = terms.filter((t) => t.pages <= total * SPECIFIC_FRACTION);
|
|
383
|
+
const complete = specific.length > 0 ? candidates(specific.map((t) => termExpr(t.term)).join(" AND "), true) : [];
|
|
384
|
+
const held = new Set(complete.map((h) => h.page_id));
|
|
385
|
+
const pool = [
|
|
386
|
+
...complete.map((hit, rank) => ({ hit, rank, score: MATCH_BONUS + hit.boost })),
|
|
387
|
+
...candidates(anyExpr)
|
|
388
|
+
.filter((hit) => !held.has(hit.page_id))
|
|
389
|
+
.map((hit, rank) => ({ hit, rank, score: hit.boost })),
|
|
390
|
+
];
|
|
391
|
+
// Ties go to the better text relevance (bm25 is lower for better matches).
|
|
392
|
+
const ranked = pool
|
|
393
|
+
.sort((a, b) => b.score - a.score || a.hit.relevance - b.hit.relevance || a.rank - b.rank)
|
|
394
|
+
.slice(0, limit);
|
|
395
|
+
if (ranked.length === 0)
|
|
396
|
+
return [];
|
|
397
|
+
const snippetSql = `
|
|
398
|
+
SELECT p.page_id, snippet(pages_fts, 3, '**', '**', ' … ', 24) AS snippet
|
|
399
|
+
FROM pages_fts JOIN pages p ON p.page_id = pages_fts.rowid
|
|
400
|
+
WHERE pages_fts MATCH ? AND p.page_id IN (${ranked.map(() => "?").join(", ")})`;
|
|
401
|
+
const snippets = new Map(db.prepare(snippetSql).all(anyExpr, ...ranked.map((r) => r.hit.page_id)).map((row) => [row.page_id, row.snippet]));
|
|
402
|
+
return ranked.map(({ hit: { boost, relevance, ...hit } }) => ({
|
|
403
|
+
...hit,
|
|
404
|
+
snippet: snippets.get(hit.page_id) ?? "",
|
|
405
|
+
}));
|
|
406
|
+
}
|
|
407
|
+
function pagesMatching(db, expr) {
|
|
408
|
+
return db.prepare("SELECT count(*) AS n FROM pages_fts WHERE pages_fts MATCH ?").get(expr)
|
|
409
|
+
.n;
|
|
132
410
|
}
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
411
|
+
/**
|
|
412
|
+
* Find a page by path. `book` settles the few paths that exist in both books
|
|
413
|
+
* (README.md); without it the main book wins.
|
|
414
|
+
*/
|
|
415
|
+
export function getPage(db, pagePath, book) {
|
|
416
|
+
const only = book ? "AND book = ?" : "";
|
|
417
|
+
const scope = book ? [book] : [];
|
|
418
|
+
const exact = db
|
|
419
|
+
.prepare(`SELECT * FROM pages WHERE path = ? ${only} ORDER BY book LIMIT 1`)
|
|
420
|
+
.get(pagePath, ...scope);
|
|
421
|
+
if (exact)
|
|
422
|
+
return exact;
|
|
139
423
|
// Convenience: allow suffix matches like "kerberoast" or "ntlm/README.md"
|
|
140
424
|
const like = db
|
|
141
|
-
.prepare(`SELECT * FROM pages WHERE path LIKE ? ORDER BY length(path) LIMIT 1`)
|
|
142
|
-
.get(`%${pagePath.replace(/%/g, "")}
|
|
425
|
+
.prepare(`SELECT * FROM pages WHERE path LIKE ? ${only} ORDER BY length(path), book LIMIT 1`)
|
|
426
|
+
.get(`%${pagePath.replace(/%/g, "")}%`, ...scope);
|
|
143
427
|
return like ?? null;
|
|
144
428
|
}
|
|
429
|
+
/** Page counts per book and category, in the order the table of contents lists them. */
|
|
145
430
|
export function listCategories(db) {
|
|
146
431
|
return db
|
|
147
|
-
.prepare(`SELECT category, count(*) AS pages FROM pages GROUP BY category ORDER BY
|
|
432
|
+
.prepare(`SELECT book, category, count(*) AS pages FROM pages GROUP BY book, category ORDER BY min(page_id)`)
|
|
148
433
|
.all();
|
|
149
434
|
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
export const KUBERNETES_GRANT_SYNTAX = '"verb resource[.group][/subresource]", "verb *" or "verb /url", for example "create pods", "get secrets", "create deployments.apps", "create pods/exec"';
|
|
2
|
+
export function parseKubernetesGrant(text) {
|
|
3
|
+
const parts = text.trim().split(/\s+/);
|
|
4
|
+
if (parts.length !== 2)
|
|
5
|
+
return null;
|
|
6
|
+
const [verb, target] = parts;
|
|
7
|
+
// A verb can carry a scope, as in "impersonate:user-info".
|
|
8
|
+
if (!/^[a-z*:-]+$/i.test(verb))
|
|
9
|
+
return null;
|
|
10
|
+
const lower = verb.toLowerCase();
|
|
11
|
+
if (target.startsWith("/"))
|
|
12
|
+
return { verb: lower, resource: "*", group: "*", subresource: "", url: target };
|
|
13
|
+
const match = /^([a-z0-9*-]+)(?:\.([a-z0-9.*-]+))?(?:\/([a-z0-9*-]+))?$/i.exec(target);
|
|
14
|
+
if (!match)
|
|
15
|
+
return null;
|
|
16
|
+
return {
|
|
17
|
+
verb: lower,
|
|
18
|
+
resource: match[1].toLowerCase(),
|
|
19
|
+
group: match[2]?.toLowerCase() ?? "",
|
|
20
|
+
subresource: match[3]?.toLowerCase() ?? "",
|
|
21
|
+
url: "",
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/** The grant a requirement leaf names, in the notation above. */
|
|
25
|
+
export function grantText(leaf) {
|
|
26
|
+
if (typeof leaf.verb !== "string" && typeof leaf.verb_prefix !== "string")
|
|
27
|
+
return "";
|
|
28
|
+
// "verb_prefix" and "resource_match" have matching rules of their own; they are shown by what they stand for.
|
|
29
|
+
const any = leaf.resource_match === "any";
|
|
30
|
+
const resource = any ? "*" : typeof leaf.resource === "string" ? leaf.resource : "*";
|
|
31
|
+
const group = !any && typeof leaf.api_group === "string" && leaf.api_group !== "" ? `.${leaf.api_group}` : "";
|
|
32
|
+
const subresource = !any && typeof leaf.subresource === "string" && leaf.subresource !== "" ? `/${leaf.subresource}` : "";
|
|
33
|
+
const verb = typeof leaf.verb === "string" ? leaf.verb : `${String(leaf.verb_prefix).endsWith(":") ? leaf.verb_prefix : `${leaf.verb_prefix}:`}*`;
|
|
34
|
+
return `${verb} ${resource}${group}${subresource}`;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Does any held grant cover the grant a requirement leaf names? A leaf with a
|
|
38
|
+
* key that has matching rules of its own is left to those rules: unknown.
|
|
39
|
+
*/
|
|
40
|
+
export function holdsKubernetes(leaf, grants) {
|
|
41
|
+
if (typeof leaf.verb !== "string")
|
|
42
|
+
return null;
|
|
43
|
+
if ("verb_prefix" in leaf || "resource_match" in leaf || "non_resource_url" in leaf)
|
|
44
|
+
return null;
|
|
45
|
+
if (leaf.resource !== undefined && typeof leaf.resource !== "string")
|
|
46
|
+
return null;
|
|
47
|
+
const need = {
|
|
48
|
+
verb: leaf.verb.toLowerCase(),
|
|
49
|
+
resource: typeof leaf.resource === "string" ? leaf.resource.toLowerCase() : "*",
|
|
50
|
+
group: typeof leaf.api_group === "string" ? leaf.api_group.toLowerCase() : "",
|
|
51
|
+
subresource: typeof leaf.subresource === "string" ? leaf.subresource.toLowerCase() : "",
|
|
52
|
+
url: "",
|
|
53
|
+
};
|
|
54
|
+
return grants.some((held) => grantCovers(held, need));
|
|
55
|
+
}
|
|
56
|
+
function grantCovers(held, need) {
|
|
57
|
+
// "impersonate" covers the scoped "impersonate:user-info"; "create" does not cover "create:token".
|
|
58
|
+
const verbs = need.verb.includes(":") ? [need.verb, need.verb.split(":")[0]] : [need.verb];
|
|
59
|
+
if (held.verb !== "*" && !verbs.includes(held.verb))
|
|
60
|
+
return false;
|
|
61
|
+
if (held.resource !== "*" && held.resource !== need.resource)
|
|
62
|
+
return false;
|
|
63
|
+
// "pods" does not grant "pods/exec", and "pods/exec" does not grant "pods".
|
|
64
|
+
if (held.subresource !== "*" && held.subresource !== need.subresource)
|
|
65
|
+
return false;
|
|
66
|
+
if (need.group === "")
|
|
67
|
+
return held.group === "" || held.group === "*";
|
|
68
|
+
return held.group === "" || held.group === "*" || held.group === need.group;
|
|
69
|
+
}
|
|
70
|
+
/** The first rule that matches a grant decides its severity. */
|
|
71
|
+
export function rateKubernetesGrant(rules, grant) {
|
|
72
|
+
for (const rule of rules) {
|
|
73
|
+
if (typeof rule.match !== "object" || rule.match === null || !ruleMatch(rule.match, grant))
|
|
74
|
+
continue;
|
|
75
|
+
let severity = typeof rule.severity === "string" ? rule.severity : "not rated";
|
|
76
|
+
const when = rule.severity_when;
|
|
77
|
+
if (typeof when === "object" && when !== null && ruleMatch(when.match, grant)) {
|
|
78
|
+
severity = typeof when.severity === "string" ? when.severity : severity;
|
|
79
|
+
}
|
|
80
|
+
return { severity: severity, description: fillIn(String(rule.description ?? ""), grant) };
|
|
81
|
+
}
|
|
82
|
+
return { severity: "not rated", description: "" };
|
|
83
|
+
}
|
|
84
|
+
/** A rule's description names the grant it matched in placeholders such as `{verb}` and `{non_resource_url}`. */
|
|
85
|
+
function fillIn(description, grant) {
|
|
86
|
+
const context = contextOf(grant);
|
|
87
|
+
return description.replace(/\{(\w+)\}/g, (placeholder, field) => context[field] ?? placeholder);
|
|
88
|
+
}
|
|
89
|
+
/** The values of a grant the rules compare: fields `verb`, `resource`, `group`, `subresource`, `full`, `non_resource_url`, `path`. */
|
|
90
|
+
function contextOf(grant) {
|
|
91
|
+
return {
|
|
92
|
+
verb: grant.verb,
|
|
93
|
+
resource: grant.resource,
|
|
94
|
+
group: grant.group,
|
|
95
|
+
subresource: grant.subresource,
|
|
96
|
+
full: grant.subresource ? `${grant.resource}/${grant.subresource}` : grant.resource,
|
|
97
|
+
non_resource_url: grant.url,
|
|
98
|
+
path: grant.url,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
function ruleMatch(match, grant) {
|
|
102
|
+
const context = contextOf(grant);
|
|
103
|
+
if ("all" in match)
|
|
104
|
+
return (Array.isArray(match.all) ? match.all : []).every((part) => ruleMatch(asMapping(part), grant));
|
|
105
|
+
if ("any" in match)
|
|
106
|
+
return (Array.isArray(match.any) ? match.any : []).some((part) => ruleMatch(asMapping(part), grant));
|
|
107
|
+
if ("not" in match)
|
|
108
|
+
return !ruleMatch(asMapping(match.not), grant);
|
|
109
|
+
const value = context[String(match.field)];
|
|
110
|
+
if (value === undefined)
|
|
111
|
+
return false;
|
|
112
|
+
return compare(value, String(match.op ?? ""), match.value);
|
|
113
|
+
}
|
|
114
|
+
function asMapping(node) {
|
|
115
|
+
return node !== null && typeof node === "object" && !Array.isArray(node) ? node : {};
|
|
116
|
+
}
|
|
117
|
+
/** `eq`, `ne`, `in`, `contains`, `prefix`, `suffix`, `truthy`; a list value stands for any of its items. */
|
|
118
|
+
function compare(value, op, expected) {
|
|
119
|
+
const items = (Array.isArray(expected) ? expected : [expected]).map(String);
|
|
120
|
+
switch (op) {
|
|
121
|
+
case "eq":
|
|
122
|
+
return items.includes(value);
|
|
123
|
+
case "ne":
|
|
124
|
+
return !items.includes(value);
|
|
125
|
+
case "in":
|
|
126
|
+
return Array.isArray(expected) && items.includes(value);
|
|
127
|
+
case "contains":
|
|
128
|
+
return items.some((item) => value.includes(item));
|
|
129
|
+
case "prefix":
|
|
130
|
+
return items.some((item) => value.startsWith(item));
|
|
131
|
+
case "suffix":
|
|
132
|
+
return items.some((item) => value.endsWith(item));
|
|
133
|
+
case "truthy":
|
|
134
|
+
return value.length > 0;
|
|
135
|
+
default:
|
|
136
|
+
return false;
|
|
137
|
+
}
|
|
138
|
+
}
|
package/dist/markdown.js
CHANGED
|
@@ -61,6 +61,18 @@ export function extractSection(content, section) {
|
|
|
61
61
|
}
|
|
62
62
|
return lines.slice(match.line, end).join("\n").trim();
|
|
63
63
|
}
|
|
64
|
+
/**
|
|
65
|
+
* Length in characters of each heading's section, cut the way extractSection
|
|
66
|
+
* cuts it: from the heading to the next one of the same or higher level. Lets
|
|
67
|
+
* a caller pick a section before reading any of the page.
|
|
68
|
+
*/
|
|
69
|
+
export function sectionLengths(content, outline) {
|
|
70
|
+
const lines = content.split("\n");
|
|
71
|
+
return outline.map((h, i) => {
|
|
72
|
+
const next = outline.slice(i + 1).find((n) => n.level <= h.level);
|
|
73
|
+
return lines.slice(h.line, next?.line ?? lines.length).join("\n").length;
|
|
74
|
+
});
|
|
75
|
+
}
|
|
64
76
|
/** Extract only fenced code blocks (commands/payloads) from a document. */
|
|
65
77
|
export function extractCodeBlocks(content) {
|
|
66
78
|
const blocks = [];
|