@rafter-security/cli 0.11.6 → 0.12.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.
Files changed (52) hide show
  1. package/dist/commands/agent/auto-update.js +171 -0
  2. package/dist/commands/agent/components.js +50 -176
  3. package/dist/commands/agent/enable.js +11 -1
  4. package/dist/commands/agent/index.js +2 -0
  5. package/dist/commands/agent/init.js +654 -764
  6. package/dist/commands/agent/install-files.js +689 -0
  7. package/dist/commands/agent/instruction-block.js +82 -40
  8. package/dist/commands/agent/scan.js +70 -21
  9. package/dist/commands/agent/status.js +11 -0
  10. package/dist/commands/agent/update.js +179 -0
  11. package/dist/commands/agent/verify.js +11 -0
  12. package/dist/commands/backend/get.js +5 -10
  13. package/dist/commands/backend/run.js +10 -20
  14. package/dist/commands/backend/scan-status.js +16 -3
  15. package/dist/commands/backend/usage.js +3 -6
  16. package/dist/commands/brief.js +6 -12
  17. package/dist/commands/counters.js +146 -0
  18. package/dist/commands/gates.js +36 -0
  19. package/dist/commands/hook/pretool.js +22 -9
  20. package/dist/commands/mcp/server.js +1 -1
  21. package/dist/commands/skill/registry.js +48 -0
  22. package/dist/core/risk-rules.js +240 -34
  23. package/dist/core/usage-counters.js +439 -0
  24. package/dist/index.js +36 -0
  25. package/dist/scanners/gate-scanner.js +721 -0
  26. package/dist/scanners/regex-scanner.js +26 -25
  27. package/dist/utils/skill-manager.js +8 -338
  28. package/package.json +1 -1
  29. package/resources/continue-rules/rafter-code-review.md +6 -6
  30. package/resources/continue-rules/rafter-secure-design.md +3 -4
  31. package/resources/continue-rules/rafter-skill-review.md +4 -4
  32. package/resources/continue-rules/rafter.md +2 -2
  33. package/resources/cursor-rules/rafter-code-review.mdc +6 -6
  34. package/resources/cursor-rules/rafter-secure-design.mdc +3 -4
  35. package/resources/cursor-rules/rafter-skill-review.mdc +4 -4
  36. package/resources/cursor-rules/rafter.mdc +2 -2
  37. package/resources/rafter-security-skill.md +1 -1
  38. package/resources/shipped-hashes.json +332 -0
  39. package/resources/skills/rafter/SKILL.md +7 -7
  40. package/resources/skills/rafter/docs/cli-reference.md +37 -10
  41. package/resources/skills/rafter/docs/finding-triage.md +1 -1
  42. package/resources/skills/rafter/docs/guardrails.md +2 -2
  43. package/resources/skills/rafter/docs/shift-left.md +4 -4
  44. package/resources/skills/rafter-code-review/SKILL.md +43 -14
  45. package/resources/skills/rafter-code-review/docs/llm.md +2 -2
  46. package/resources/skills/rafter-code-review/docs/security-gates.md +53 -0
  47. package/resources/skills/rafter-secure-design/SKILL.md +1 -0
  48. package/resources/skills/rafter-skill-review/SKILL.md +1 -0
  49. package/resources/windsurf-rules/rafter-code-review.md +6 -6
  50. package/resources/windsurf-rules/rafter-secure-design.md +3 -4
  51. package/resources/windsurf-rules/rafter-skill-review.md +4 -4
  52. package/resources/windsurf-rules/rafter.md +2 -2
@@ -0,0 +1,721 @@
1
+ /**
2
+ * Static map of a codebase's security gates: the functions whose names say
3
+ * they decide whether something is allowed, ranked by likely security
4
+ * weight, plus "twin" groups of gates that implement the same contract and
5
+ * the guard calls each twin makes. Line-based and regex-only: no parsing, no
6
+ * network, no LLM.
7
+ *
8
+ * Keep in step with python/rafter_cli/scanners/gate_scanner.py. Both runtimes
9
+ * must produce identical output for the same tree (see CLI_SPEC.md).
10
+ */
11
+ import fs from "fs";
12
+ import path from "path";
13
+ import { DEFAULT_EXCLUDE, filterGitIgnored } from "./regex-scanner.js";
14
+ // ── Text helpers ─────────────────────────────────────────────────────
15
+ // ASCII whitespace and code-point lengths and order, as in Python's re.ASCII
16
+ // patterns and str: JS \s, trim() and String#length differ on U+00A0, U+FEFF
17
+ // and non-BMP characters, and output must match byte for byte.
18
+ const WS = " \t\n\r\f\v";
19
+ function trimStartA(s) {
20
+ let i = 0;
21
+ while (i < s.length && WS.includes(s[i]))
22
+ i++;
23
+ return s.slice(i);
24
+ }
25
+ function trimEndA(s) {
26
+ let j = s.length;
27
+ while (j > 0 && WS.includes(s[j - 1]))
28
+ j--;
29
+ return s.slice(0, j);
30
+ }
31
+ function trimA(s) {
32
+ return trimEndA(trimStartA(s));
33
+ }
34
+ const SURROGATE_RE = /[\uD800-\uDFFF]/;
35
+ function cpLength(s) {
36
+ return SURROGATE_RE.test(s) ? Array.from(s).length : s.length;
37
+ }
38
+ function cpSlice(s, n) {
39
+ return SURROGATE_RE.test(s) ? Array.from(s).slice(0, n).join("") : s.slice(0, n);
40
+ }
41
+ /** Compare by code point, as Python compares str. */
42
+ function cmp(a, b) {
43
+ if (a === b)
44
+ return 0;
45
+ let i = 0;
46
+ while (i < a.length && i < b.length && a.charCodeAt(i) === b.charCodeAt(i))
47
+ i++;
48
+ if (i === a.length || i === b.length)
49
+ return a.length - b.length;
50
+ if (i > 0 && /[\uD800-\uDBFF]/.test(a[i - 1]))
51
+ i--;
52
+ return a.codePointAt(i) - b.codePointAt(i);
53
+ }
54
+ // ── File selection ───────────────────────────────────────────────────
55
+ /** Extension as Python's os.path.splitext sees it: leading dots belong to the name. */
56
+ function extOf(p) {
57
+ const name = path.basename(p).replace(/^\.+/, "");
58
+ const i = name.lastIndexOf(".");
59
+ return i < 0 ? "" : name.slice(i);
60
+ }
61
+ /** A name that is not valid UTF-8 can't be printed the same way by both runtimes; skip it. */
62
+ function utf8Name(raw) {
63
+ const name = raw.toString("utf8");
64
+ return Buffer.from(name, "utf8").equals(raw) ? name : null;
65
+ }
66
+ const LANG_BY_EXT = {
67
+ ".go": "go",
68
+ ".py": "python",
69
+ ".js": "javascript", ".jsx": "javascript", ".mjs": "javascript", ".cjs": "javascript",
70
+ ".ts": "typescript", ".tsx": "typescript", ".mts": "typescript", ".cts": "typescript",
71
+ ".java": "java",
72
+ ".rb": "ruby",
73
+ };
74
+ /** Directories that hold tests, docs, examples, vendored or generated code. */
75
+ const GATE_EXCLUDE_DIRS = new Set([
76
+ ...DEFAULT_EXCLUDE,
77
+ "test", "tests", "__tests__", "__mocks__", "spec", "specs", "testdata", "testutil",
78
+ "testutils", "testing", "fixtures", "mocks", "e2e", "docs", "doc", "examples", "example",
79
+ "samples", "sample", "third_party", "thirdparty", "site-packages", "generated",
80
+ "benchmarks",
81
+ ]);
82
+ const MAX_DEPTH = 40;
83
+ const MAX_FILE_BYTES = 1024 * 1024;
84
+ const TEST_FILE_RE = /(_test\.go|_test\.py|_test\.rb|_spec\.rb|\.(test|spec)\.[cm]?[jt]sx?|Tests?\.java|IT\.java)$/;
85
+ const PY_TEST_RE = /^(test_[^\n]*|conftest)\.py$/;
86
+ const GENERATED_NAME_RE = /(\.pb\.go|\.pb\.gw\.go|_generated\.go|\.gen\.go|_gen\.go|_pb2\.py|_pb2_grpc\.py|\.min\.js|\.bundle\.js|\.d\.ts|\.d\.mts|\.d\.cts)$|^zz_generated/;
87
+ // "DO NOT EDIT" alone covers Go's "Code generated ... DO NOT EDIT" header; a `.*` between
88
+ // the two would make the test quadratic on a hostile first line.
89
+ const GENERATED_MARK_RE = /DO NOT EDIT|@generated|autogenerated/i;
90
+ function isSkippedFile(name) {
91
+ return TEST_FILE_RE.test(name) || PY_TEST_RE.test(name) || GENERATED_NAME_RE.test(name);
92
+ }
93
+ function walk(dir, depth, out) {
94
+ if (depth >= MAX_DEPTH)
95
+ return;
96
+ let raw;
97
+ try {
98
+ raw = fs.readdirSync(dir, { withFileTypes: true, encoding: "buffer" });
99
+ }
100
+ catch {
101
+ return;
102
+ }
103
+ const entries = [];
104
+ for (const e of raw) {
105
+ const name = utf8Name(e.name);
106
+ if (name !== null)
107
+ entries.push([name, e]);
108
+ }
109
+ entries.sort((a, b) => cmp(a[0], b[0]));
110
+ for (const [name, entry] of entries) {
111
+ if (entry.isSymbolicLink())
112
+ continue;
113
+ const full = path.join(dir, name);
114
+ if (entry.isDirectory()) {
115
+ if (name.startsWith(".") || GATE_EXCLUDE_DIRS.has(name))
116
+ continue;
117
+ walk(full, depth + 1, out);
118
+ }
119
+ else if (entry.isFile()) {
120
+ if (!LANG_BY_EXT[extOf(name)] || isSkippedFile(name))
121
+ continue;
122
+ out.push(full);
123
+ }
124
+ }
125
+ }
126
+ // ── Names ────────────────────────────────────────────────────────────
127
+ const WORD_RE = /[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+|\d+/g;
128
+ /** Split an identifier into lowercase words: camelCase, snake_case, kebab. */
129
+ export function splitWords(name) {
130
+ const words = [];
131
+ for (const part of name.split(/[^A-Za-z0-9]+/)) {
132
+ for (const w of part.match(WORD_RE) ?? [])
133
+ words.push(w.toLowerCase());
134
+ }
135
+ return words;
136
+ }
137
+ /** Leading verb → weight. The name decides if its first word is one of these. */
138
+ const VERBS = new Map(Object.entries({
139
+ authorize: 4, authorise: 4, authenticate: 4, authz: 4, authn: 4,
140
+ allow: 3, allows: 3, permit: 3, permits: 3, deny: 3, denies: 3, can: 2, may: 2,
141
+ verify: 3, enforce: 3, guard: 3, auth: 2,
142
+ check: 1, validate: 1, ensure: 1, require: 1, requires: 1, match: 1, matches: 1,
143
+ sanitize: 2, sanitise: 2, escape: 2, quote: 1, clean: 1, safe: 1, secure: 1, assert: 1,
144
+ }));
145
+ /** `is*` gates: one of these must follow. */
146
+ const IS_WORDS = new Set([
147
+ "allowed", "authorized", "authorised", "authenticated", "valid", "trusted", "safe", "admin",
148
+ "owner", "permitted", "granted", "blocked", "denied", "forbidden", "expired", "revoked",
149
+ "verified", "secure", "private", "internal", "loopback", "whitelisted", "blacklisted",
150
+ "allowlisted", "denylisted", "member", "superuser", "staff", "root", "same", "local",
151
+ ]);
152
+ /** `has*` gates: one of these must follow. */
153
+ const HAS_WORDS = new Set([
154
+ "permission", "permissions", "perm", "perms", "role", "roles", "scope", "scopes", "access",
155
+ "privilege", "privileges", "right", "rights", "capability", "capabilities", "grant", "grants",
156
+ "claim", "claims",
157
+ ]);
158
+ /** Words that make a name a gate wherever they appear. */
159
+ const ROLE_WORDS = new Map(Object.entries({
160
+ middleware: 3, guard: 3, interceptor: 3, authorizer: 3, authenticator: 3,
161
+ validator: 1, verifier: 2, sanitizer: 2, required: 1,
162
+ }));
163
+ /** First words that mark accessors and plumbing, not decisions: never a gate. */
164
+ const NON_DECIDING = new Set([
165
+ "get", "set", "load", "list", "delete", "remove", "update", "save", "print", "log", "format",
166
+ "render", "fetch", "write", "read", "to", "from", "parse", "test", "mock", "fake", "default",
167
+ "register", "add", "with", "on", "handle", "init", "reset", "clear", "create", "find",
168
+ "map", "export", "merge", "compute", "resolve", "build", "run", "show", "count",
169
+ ]);
170
+ /** Security tokens in a name: a token matches a word that starts with it. */
171
+ const STRONG_NAME_TOKENS = [
172
+ ["authoriz", 3], ["authoris", 3], ["authent", 3], ["permission", 3], ["privilege", 3],
173
+ ["rbac", 3], ["acl", 3], ["policy", 2], ["csrf", 3], ["xsrf", 3], ["admin", 2], ["owner", 2],
174
+ ["role", 1], ["scope", 1], ["access", 2], ["token", 2], ["jwt", 2], ["session", 2],
175
+ ["signature", 2], ["hmac", 2], ["cert", 2], ["tls", 2], ["oauth", 2], ["saml", 2],
176
+ ["oidc", 2], ["password", 2], ["credential", 2], ["login", 2], ["origin", 2],
177
+ ["redirect", 2], ["host", 1], ["domain", 1], ["url", 1], ["path", 1], ["cors", 2],
178
+ ["trusted", 2], ["mfa", 2], ["otp", 2], ["nonce", 2], ["secret", 2], ["key", 1],
179
+ ];
180
+ /** Security-ish path words (directory or file stem); one +2 per path. */
181
+ const PATH_TOKENS = [
182
+ "auth", "authz", "authn", "acl", "policy", "policies", "permission", "session", "token",
183
+ "oauth", "oidc", "saml", "jwt", "crypto", "tls", "cert", "middleware", "guard", "security",
184
+ "access", "login", "rbac", "iam", "sso", "csrf", "sanitiz", "escape", "secure",
185
+ ];
186
+ function isAuthorWord(w) {
187
+ return w.startsWith("author") && !w.startsWith("authoriz") && !w.startsWith("authoris");
188
+ }
189
+ function nameWeight(words, kind) {
190
+ if (words.length === 0)
191
+ return 0;
192
+ let first = words[0];
193
+ if (NON_DECIDING.has(first))
194
+ return 0;
195
+ // aauthenticate, acheck_password: the a-prefixed async variant of a verb.
196
+ if (!VERBS.has(first) && first.length > 3 && first.startsWith("a") && VERBS.has(first.slice(1)))
197
+ first = first.slice(1);
198
+ let verb = 0;
199
+ if (kind !== "type") {
200
+ if (VERBS.has(first))
201
+ verb = VERBS.get(first);
202
+ else if (first === "is" && words.slice(1).some((w) => IS_WORDS.has(w)))
203
+ verb = 2;
204
+ else if (first === "has" && words.slice(1).some((w) => HAS_WORDS.has(w)))
205
+ verb = 3;
206
+ else if (words.length > 1 && (words[words.length - 1] === "match" || words[words.length - 1] === "matches" || words[words.length - 1] === "matcher"))
207
+ verb = 1;
208
+ }
209
+ let role = 0;
210
+ for (const w of words) {
211
+ const r = ROLE_WORDS.get(w) ?? 0;
212
+ if (r > role)
213
+ role = r;
214
+ }
215
+ if (kind === "type" && role < 2)
216
+ return 0; // a type is a gate only by its role word
217
+ return Math.max(verb, role);
218
+ }
219
+ function tokenWeight(words) {
220
+ const ws = words.filter((w) => !isAuthorWord(w));
221
+ let total = 0;
222
+ for (const [tok, w] of STRONG_NAME_TOKENS) {
223
+ if (ws.some((x) => x.startsWith(tok)))
224
+ total += w;
225
+ }
226
+ return Math.min(total, 6);
227
+ }
228
+ function pathWeight(rel) {
229
+ const segs = rel.split("/");
230
+ segs[segs.length - 1] = segs[segs.length - 1].replace(/\.[^.]*$/, "");
231
+ for (const seg of segs) {
232
+ for (const w of splitWords(seg)) {
233
+ if (isAuthorWord(w))
234
+ continue;
235
+ if (PATH_TOKENS.some((t) => w.startsWith(t)))
236
+ return 2;
237
+ }
238
+ }
239
+ return 0;
240
+ }
241
+ const GO_FUNC = /^[ \t\n\r\f\v]*func[ \t\n\r\f\v]+(\([^)]*\)[ \t\n\r\f\v]*)?([A-Za-z_]\w*)[ \t\n\r\f\v]*(\[[^\]]*\][ \t\n\r\f\v]*)?\(/;
242
+ const GO_TYPE = /^[ \t\n\r\f\v]*type[ \t\n\r\f\v]+([A-Za-z_]\w*)[ \t\n\r\f\v]+(struct|interface|func)\b/;
243
+ const PY_DEF = /^([ \t\n\r\f\v]*)(async[ \t\n\r\f\v]+)?def[ \t\n\r\f\v]+([A-Za-z_]\w*)[ \t\n\r\f\v]*\(/;
244
+ const PY_CLASS = /^[ \t\n\r\f\v]*class[ \t\n\r\f\v]+([A-Za-z_]\w*)/;
245
+ const JS_FUNC = /^[ \t\n\r\f\v]*(export[ \t\n\r\f\v]+)?(default[ \t\n\r\f\v]+)?(async[ \t\n\r\f\v]+)?function[ \t\n\r\f\v]*(?:\*[ \t\n\r\f\v]*)?([A-Za-z_$][\w$]*)[ \t\n\r\f\v]*[<(]/;
246
+ const JS_VAR = /^[ \t\n\r\f\v]*(export[ \t\n\r\f\v]+)?(const|let|var)[ \t\n\r\f\v]+([A-Za-z_$][\w$]*)[ \t\n\r\f\v]*(:[^=]+)?=[ \t\n\r\f\v]*(async[ \t\n\r\f\v]+)?(function\b|[A-Za-z_$][\w$]*[ \t\n\r\f\v]*=>|\()/;
247
+ const JS_PROP = /^[ \t\n\r\f\v]*([A-Za-z_$][\w$]*)[ \t\n\r\f\v]*:[ \t\n\r\f\v]*(async[ \t\n\r\f\v]+)?(function\b|[A-Za-z_$][\w$]*[ \t\n\r\f\v]*=>|\()/;
248
+ const JS_EXPORTS = /^[ \t\n\r\f\v]*(module\.)?exports\.([A-Za-z_$][\w$]*)[ \t\n\r\f\v]*=[ \t\n\r\f\v]*(async[ \t\n\r\f\v]+)?(function\b|[A-Za-z_$][\w$]*[ \t\n\r\f\v]*=>|\()/;
249
+ const JS_PROTO = /^[ \t\n\r\f\v]*[\w$.]+\.prototype\.([A-Za-z_$][\w$]*)[ \t\n\r\f\v]*=[ \t\n\r\f\v]*(async[ \t\n\r\f\v]+)?function\b/;
250
+ const JS_METHOD = /^[ \t\n\r\f\v]+((public|private|protected|static|async|override|readonly)[ \t\n\r\f\v]+)*([A-Za-z_$][\w$]*)[ \t\n\r\f\v]*(<[^>]*>)?[ \t\n\r\f\v]*\([^\n]*\)[ \t\n\r\f\v]*(:[^{;=]+)?\{[ \t\n\r\f\v]*$/;
251
+ const JS_CLASS = /^[ \t\n\r\f\v]*(export[ \t\n\r\f\v]+)?(default[ \t\n\r\f\v]+)?(abstract[ \t\n\r\f\v]+)?class[ \t\n\r\f\v]+([A-Za-z_$][\w$]*)/;
252
+ const JAVA_METHOD = /^[ \t\n\r\f\v]*(@\w+[ \t\n\r\f\v]+)*((public|private|protected|static|final|synchronized|abstract|default|native)[ \t\n\r\f\v]+)*(<[^>]+>[ \t\n\r\f\v]+)?[\w$.<>\[\],? ]*?[\w$>\]][ \t\n\r\f\v]+([a-z_$][\w$]*)[ \t\n\r\f\v]*\(/;
253
+ const JAVA_CLASS = /^[ \t\n\r\f\v]*((public|private|protected|static|final|abstract)[ \t\n\r\f\v]+)*(class|interface|enum|record)[ \t\n\r\f\v]+([A-Za-z_$][\w$]*)/;
254
+ const RB_DEF = /^[ \t\n\r\f\v]*def[ \t\n\r\f\v]+(self\.)?([A-Za-z_]\w*[?!]?)/;
255
+ const RB_CLASS = /^[ \t\n\r\f\v]*class[ \t\n\r\f\v]+([A-Z]\w*)/;
256
+ const KEYWORDS = new Set([
257
+ "if", "for", "while", "switch", "catch", "function", "return", "else", "do", "try", "with",
258
+ "new", "throw", "case", "typeof", "await", "yield", "delete", "void", "super", "this",
259
+ "elif", "except", "lambda", "not", "and", "or", "in", "is", "assert", "print", "def",
260
+ "class", "import", "from", "raise", "pass", "select", "go", "defer", "range", "func",
261
+ "make", "len", "cap", "append", "panic", "recover", "sizeof", "constructor",
262
+ ]);
263
+ function matchDef(lang, line) {
264
+ let m;
265
+ switch (lang) {
266
+ case "go":
267
+ if ((m = line.match(GO_FUNC)))
268
+ return { name: m[2], kind: m[1] ? "method" : "function" };
269
+ if ((m = line.match(GO_TYPE)))
270
+ return { name: m[1], kind: "type" };
271
+ return null;
272
+ case "python":
273
+ if ((m = line.match(PY_DEF)))
274
+ return { name: m[3], kind: m[1].length > 0 ? "method" : "function" };
275
+ if ((m = line.match(PY_CLASS)))
276
+ return { name: m[1], kind: "type" };
277
+ return null;
278
+ case "javascript":
279
+ case "typescript": {
280
+ const t = trimEndA(line);
281
+ if ((m = line.match(JS_FUNC)))
282
+ return t.endsWith(";") ? null : { name: m[4], kind: "function" };
283
+ if ((m = line.match(JS_VAR)))
284
+ return arrowOk(m[6], t) ? { name: m[3], kind: "function" } : null;
285
+ if ((m = line.match(JS_EXPORTS)))
286
+ return arrowOk(m[4], t) ? { name: m[2], kind: "function" } : null;
287
+ if ((m = line.match(JS_PROTO)))
288
+ return { name: m[1], kind: "method" };
289
+ if ((m = line.match(JS_CLASS)))
290
+ return { name: m[4], kind: "type" };
291
+ if ((m = line.match(JS_PROP)))
292
+ return arrowOk(m[3], t) ? { name: m[1], kind: "method" } : null;
293
+ if ((m = line.match(JS_METHOD)))
294
+ return KEYWORDS.has(m[3]) ? null : { name: m[3], kind: "method" };
295
+ return null;
296
+ }
297
+ case "java": {
298
+ if ((m = line.match(JAVA_CLASS)))
299
+ return { name: m[4], kind: "type" };
300
+ const t = trimEndA(line);
301
+ if (t.endsWith(";"))
302
+ return null;
303
+ if ((m = line.match(JAVA_METHOD))) {
304
+ const firstWord = trimA(line).split(/[ \t\n\r\f\v(]/)[0];
305
+ if (KEYWORDS.has(firstWord) || KEYWORDS.has(m[5]))
306
+ return null;
307
+ return { name: m[5], kind: "method" };
308
+ }
309
+ return null;
310
+ }
311
+ case "ruby":
312
+ if ((m = line.match(RB_DEF)))
313
+ return { name: m[2].replace(/[?!]$/, ""), kind: m[1] ? "function" : "method" };
314
+ if ((m = line.match(RB_CLASS)))
315
+ return { name: m[1], kind: "type" };
316
+ return null;
317
+ }
318
+ return null;
319
+ }
320
+ /** A `(` after `=` is a function only if an arrow follows on the line or the params continue. */
321
+ function arrowOk(head, line) {
322
+ if (head !== "(")
323
+ return true;
324
+ return line.includes("=>") || line.endsWith("(") || line.endsWith(",");
325
+ }
326
+ // ── Bodies and guard calls ───────────────────────────────────────────
327
+ const MAX_BODY_LINES = 400;
328
+ function indentOf(line) {
329
+ return line.length - trimStartA(line).length;
330
+ }
331
+ /**
332
+ * Remove string literals and line comments so braces inside them don't count.
333
+ * Each closed literal becomes `""`; an unclosed quote is kept and the scan
334
+ * goes on after it. One linear pass: a regex for this backtracks
335
+ * quadratically on a long line with an unclosed quote. Once a quote is
336
+ * unclosed, every later quote of that kind is too (its scan would fall into
337
+ * step with the first one), so each kind is scanned to the end at most once.
338
+ */
339
+ function stripCode(line, hashComments = false) {
340
+ let out = "";
341
+ let unclosed = "";
342
+ let i = 0;
343
+ while (i < line.length) {
344
+ const ch = line[i];
345
+ if ((ch === '"' || ch === "'" || ch === "`") && !unclosed.includes(ch)) {
346
+ let j = i + 1;
347
+ while (j < line.length && line[j] !== ch)
348
+ j += line[j] === "\\" ? 2 : 1;
349
+ if (j < line.length) {
350
+ out += '""';
351
+ i = j + 1;
352
+ continue;
353
+ }
354
+ unclosed += ch;
355
+ }
356
+ else if ((ch === "/" && line[i + 1] === "/") || (hashComments && ch === "#")) {
357
+ break;
358
+ }
359
+ out += ch;
360
+ i++;
361
+ }
362
+ return out;
363
+ }
364
+ /** Indexes of the lines in the body of the definition at `start`. */
365
+ function bodyLines(lang, lines, code, start) {
366
+ const end = Math.min(lines.length, start + MAX_BODY_LINES);
367
+ if (lang === "python" || lang === "ruby") {
368
+ const base = indentOf(lines[start]);
369
+ const body = [start];
370
+ for (let i = start + 1; i < end; i++) {
371
+ const l = lines[i];
372
+ if (trimA(l) === "")
373
+ continue;
374
+ if (indentOf(l) <= base) {
375
+ if (lang === "ruby" && trimA(l).startsWith("end"))
376
+ break;
377
+ if (lang === "python" && /^[ \t\n\r\f\v]*[)\]]/.test(l)) {
378
+ body.push(i);
379
+ continue;
380
+ }
381
+ break;
382
+ }
383
+ body.push(i);
384
+ }
385
+ return body;
386
+ }
387
+ // Brace languages.
388
+ let depth = 0;
389
+ let opened = false;
390
+ const body = [];
391
+ for (let i = start; i < end; i++) {
392
+ body.push(i);
393
+ for (const ch of code[i]) {
394
+ if (ch === "{") {
395
+ depth++;
396
+ opened = true;
397
+ }
398
+ else if (ch === "}")
399
+ depth--;
400
+ }
401
+ if (opened && depth <= 0)
402
+ break;
403
+ if (!opened && i - start >= 3)
404
+ break;
405
+ if (!opened && trimEndA(code[i]).endsWith(";"))
406
+ break;
407
+ }
408
+ return body;
409
+ }
410
+ // The lookbehind starts a match only at the head of an identifier, so a long
411
+ // run of identifier characters is scanned once instead of once per character.
412
+ const CALL_RE = /(?<![\w$])([A-Za-z_$][\w$]*)[ \t\n\r\f\v]*\(/g;
413
+ /**
414
+ * Guard categories, matched against the called name lowercased with
415
+ * underscores removed, with the
416
+ * weight a missing one carries when ranking twin groups. Order is output order.
417
+ */
418
+ const GUARD_CATEGORIES = [
419
+ ["escape", /escape|quote|sanitiz|sanitis|purify|striptags|encodeuri|htmlspecialchars/, 3],
420
+ ["normalize", /clean|normaliz|normalis|normpath|realpath|abspath|evalsymlinks|canonical/, 3],
421
+ ["containment", /^(rel|relpath|relative)$|hasprefix|startswith|hassuffix|endswith|islink|lstat|within|containspath|isrelativeto/, 3],
422
+ ["constant_time", /constanttimecompare|comparedigest|timingsafeequal|securecompare|constanttimeeq|safeequal|^equal$/, 3],
423
+ ["expiry", /expir|revok|notbefore|notafter/, 3],
424
+ ["authz", /authoriz|authoris|permi|allow|deny|forbid|access/, 2],
425
+ ["authn", /authent|login|password/, 2],
426
+ ["limit", /limit|max|bound|truncat|throttle/, 2],
427
+ ["verify", /verif/, 1],
428
+ ["validate", /valid/, 1],
429
+ ["check", /check/, 1],
430
+ ];
431
+ const CATEGORY_WEIGHT = new Map(GUARD_CATEGORIES.map(([c, , w]) => [c, w]));
432
+ /** Calls ending in these words construct a value; they are not guards. */
433
+ const VALUE_WORDS = new Set(["result", "results", "error", "errors", "exception", "options", "config", "info", "type"]);
434
+ const CALL_KEYWORDS = new Set([...KEYWORDS, "require", "import"]);
435
+ function guardCalls(code, body, selfName) {
436
+ const found = {};
437
+ // Drop the definition's own name from its first line.
438
+ const text = body.map((li, i) => (i === 0 ? code[li].replace(selfName, "") : code[li])).join("\n");
439
+ CALL_RE.lastIndex = 0;
440
+ let m;
441
+ while ((m = CALL_RE.exec(text)) !== null) {
442
+ const id = m[1];
443
+ const low = id.toLowerCase().replace(/_/g, "");
444
+ if (low === selfName.toLowerCase().replace(/_/g, "") || CALL_KEYWORDS.has(id))
445
+ continue;
446
+ if (low.startsWith("un"))
447
+ continue; // unquote, unescape: the reverse of a guard
448
+ const idWords = splitWords(id);
449
+ if (idWords.length && VALUE_WORDS.has(idWords[idWords.length - 1]))
450
+ continue;
451
+ for (const [cat, re] of GUARD_CATEGORIES) {
452
+ if (cat === "constant_time" && low === "equal") {
453
+ const before = text.slice(Math.max(0, m.index - 8), m.index);
454
+ if (!/(hmac|subtle)\.$/.test(before))
455
+ continue;
456
+ }
457
+ if (re.test(low)) {
458
+ (found[cat] ?? (found[cat] = new Set())).add(id);
459
+ break;
460
+ }
461
+ }
462
+ }
463
+ const out = {};
464
+ for (const [cat] of GUARD_CATEGORIES) {
465
+ if (found[cat])
466
+ out[cat] = [...found[cat]].sort();
467
+ }
468
+ return out;
469
+ }
470
+ // ── Twins ────────────────────────────────────────────────────────────
471
+ /** Variant markers: async/sync pairs, implementations, versions. Dropped anywhere. */
472
+ const VARIANT_WORDS = new Set(["async", "sync", "impl", "internal", "inner", "v"]);
473
+ /** Backend-ish words: dropped anywhere when what remains still names a contract. */
474
+ const BACKEND_WORDS = new Set([
475
+ "legacy", "old", "new", "default", "sql", "sqlite", "postgres", "pg", "mysql", "mongo",
476
+ "redis", "ldap", "local", "memory", "mem", "db", "file", "fs", "http", "grpc", "rest", "ws",
477
+ "s3", "gcs", "azure", "remote",
478
+ ]);
479
+ const SECURITY_WORDS = new Set([
480
+ ...VERBS.keys(), ...IS_WORDS, ...HAS_WORDS, ...ROLE_WORDS.keys(), "is", "has",
481
+ ]);
482
+ /**
483
+ * The contract a gate implements, from its name: `ldapAuthenticate` in
484
+ * ldap.go, `authenticate_async` and `AuthenticateV2` all key to
485
+ * "authenticate". Words naming the file or its directory are dropped from
486
+ * either end of the name. A key reduced to one weak verb ("check") is too
487
+ * generic to pair on, so the unstripped name is used instead.
488
+ */
489
+ function twinKey(name, rel) {
490
+ let base = splitWords(name).filter((w) => !/^\d+$/.test(w) && !VARIANT_WORDS.has(w));
491
+ if (base.length > 1 && base[0] === "do")
492
+ base = base.slice(1);
493
+ if (base.length === 0)
494
+ return "";
495
+ const ctx = new Set();
496
+ const segs = rel.split("/");
497
+ for (const w of splitWords(segs[segs.length - 1].replace(/\.[^.]*$/, "")))
498
+ ctx.add(w);
499
+ if (segs.length > 1)
500
+ for (const w of splitWords(segs[segs.length - 2]))
501
+ ctx.add(w);
502
+ const strippable = (w) => ctx.has(w) && !SECURITY_WORDS.has(w);
503
+ let kept = base.filter((w) => !BACKEND_WORDS.has(w));
504
+ if (kept.length > 1 && strippable(kept[0]))
505
+ kept = kept.slice(1);
506
+ if (kept.length > 1 && strippable(kept[kept.length - 1]))
507
+ kept = kept.slice(0, -1);
508
+ const strongBare = kept.length === 1 && (VERBS.get(kept[0]) ?? 0) >= 3;
509
+ if (kept.length === 0 || (kept.length === 1 && !strongBare && base.length > 1))
510
+ kept = base;
511
+ return kept.join("");
512
+ }
513
+ const MAX_TWIN_GROUP = 8;
514
+ function buildTwins(gates) {
515
+ const candidates = gates.filter((g) => g.kind !== "type");
516
+ const keys = candidates.map((g) => twinKey(g.name, g.file));
517
+ const keySet = new Set(keys);
518
+ const groups = new Map();
519
+ candidates.forEach((g, i) => {
520
+ let k = keys[i];
521
+ // aauthenticate / acheck_password: an a-prefixed async twin.
522
+ if (k.length > 2 && k.startsWith("a") && keySet.has(k.slice(1)))
523
+ k = k.slice(1);
524
+ // A bare weak verb (`Check`, `Validate` on unrelated types) names no shared contract.
525
+ if (!k || (VERBS.get(k) ?? 2) < 2)
526
+ return;
527
+ const list = groups.get(k);
528
+ if (list)
529
+ list.push(g);
530
+ else
531
+ groups.set(k, [g]);
532
+ });
533
+ const scored = [];
534
+ for (const [key, members] of groups) {
535
+ if (members.length < 2 || members.length > MAX_TWIN_GROUP)
536
+ continue;
537
+ const present = new Set();
538
+ for (const m of members)
539
+ for (const c of Object.keys(m.guards))
540
+ present.add(c);
541
+ const cats = GUARD_CATEGORIES.map(([c]) => c).filter((c) => present.has(c));
542
+ const missing = cats.filter((c) => members.some((m) => !m.guards[c]));
543
+ const t = {
544
+ key,
545
+ flagged: missing.length > 0,
546
+ missing,
547
+ members: members.map((m) => ({
548
+ file: m.file,
549
+ line: m.line,
550
+ name: m.name,
551
+ guards: m.guards,
552
+ lacks: missing.filter((c) => !m.guards[c]),
553
+ })),
554
+ };
555
+ const severity = Math.max(0, ...missing.map((c) => CATEGORY_WEIGHT.get(c)));
556
+ scored.push({ t, sev: severity, w: Math.max(...members.map((m) => m.score)) });
557
+ }
558
+ scored.sort((a, b) => b.sev - a.sev ||
559
+ b.w - a.w ||
560
+ b.t.missing.length - a.t.missing.length ||
561
+ cmp(a.t.key, b.t.key));
562
+ return scored.map((s) => s.t);
563
+ }
564
+ // ── Entry point ──────────────────────────────────────────────────────
565
+ const MAX_SIGNATURE = 90;
566
+ // Longer lines are minified or data, not definitions; skipping them also
567
+ // bounds regex backtracking.
568
+ const MAX_DEF_LINE = 400;
569
+ // Body text read per file, in characters summed over its gates. Bodies
570
+ // overlap, so a file of unclosed definitions above a long line costs
571
+ // definitions x line length. The largest real file seen (kubernetes
572
+ // validation.go) reads 312,000; a file past this is data, and is skipped like
573
+ // an oversize file.
574
+ const MAX_BODY_WORK = 2000000;
575
+ function scanFile(abs, rel, lang, out) {
576
+ let content;
577
+ try {
578
+ const st = fs.statSync(abs);
579
+ if (st.size > MAX_FILE_BYTES)
580
+ return false;
581
+ content = fs.readFileSync(abs, "utf-8");
582
+ }
583
+ catch {
584
+ return false;
585
+ }
586
+ if (content.startsWith("\uFEFF"))
587
+ content = content.slice(1);
588
+ const lines = content.split("\n").map((l) => (l.endsWith("\r") ? l.slice(0, -1) : l));
589
+ if (GENERATED_MARK_RE.test(lines.slice(0, 5).join("\n")))
590
+ return false;
591
+ // Each line stripped once; bodies overlap, so per-gate stripping is quadratic.
592
+ const code = lines.map((l) => stripCode(l, lang === "python" || lang === "ruby"));
593
+ const pw = pathWeight(rel);
594
+ let bodyWork = 0;
595
+ const found = [];
596
+ for (let i = 0; i < lines.length; i++) {
597
+ if (cpLength(lines[i]) > MAX_DEF_LINE)
598
+ continue;
599
+ const def = matchDef(lang, lines[i]);
600
+ if (!def)
601
+ continue;
602
+ const words = splitWords(def.name);
603
+ const nw = nameWeight(words, def.kind);
604
+ if (nw === 0)
605
+ continue;
606
+ let guards = {};
607
+ if (def.kind !== "type") {
608
+ const body = bodyLines(lang, lines, code, i);
609
+ for (const li of body)
610
+ bodyWork += code[li].length + 1;
611
+ if (bodyWork > MAX_BODY_WORK)
612
+ return false;
613
+ guards = guardCalls(code, body, def.name);
614
+ }
615
+ let sig = trimA(lines[i]);
616
+ if (cpLength(sig) > MAX_SIGNATURE)
617
+ sig = cpSlice(sig, MAX_SIGNATURE - 3) + "...";
618
+ found.push({
619
+ file: rel,
620
+ line: i + 1,
621
+ name: def.name,
622
+ kind: def.kind,
623
+ language: lang,
624
+ score: nw + tokenWeight(words) + pw,
625
+ signature: sig,
626
+ guards,
627
+ });
628
+ }
629
+ for (const g of found)
630
+ out.push(g);
631
+ return true;
632
+ }
633
+ /** Map the security gates under `target` (a directory or a single file). */
634
+ export function mapGates(target, opts) {
635
+ const root = path.resolve(target);
636
+ const st = fs.statSync(root);
637
+ let files;
638
+ let base;
639
+ if (st.isDirectory()) {
640
+ files = [];
641
+ walk(root, 0, files);
642
+ if (opts.respectGitignore !== false)
643
+ files = filterGitIgnored(files, root);
644
+ base = root;
645
+ }
646
+ else {
647
+ files = LANG_BY_EXT[extOf(root)] ? [root] : [];
648
+ base = path.dirname(root);
649
+ }
650
+ const gates = [];
651
+ let scanned = 0;
652
+ for (const abs of files) {
653
+ const rel = path.relative(base, abs).split(path.sep).join("/");
654
+ if (scanFile(abs, rel, LANG_BY_EXT[extOf(abs)], gates))
655
+ scanned++;
656
+ }
657
+ gates.sort((a, b) => b.score - a.score || cmp(a.file, b.file) || a.line - b.line);
658
+ const twins = buildTwins(gates);
659
+ const shown = gates.slice(0, opts.limit).map(({ guards, ...g }) => g);
660
+ return {
661
+ stats: {
662
+ files_scanned: scanned,
663
+ gates_found: gates.length,
664
+ gates_shown: shown.length,
665
+ twin_groups: twins.length,
666
+ flagged_groups: twins.filter((t) => t.flagged).length,
667
+ },
668
+ gates: shown,
669
+ twins,
670
+ };
671
+ }
672
+ // ── Text ─────────────────────────────────────────────────────────────
673
+ const MAX_FLAGGED_TEXT = 10;
674
+ const MAX_MEMBERS_TEXT = 5;
675
+ const MAX_OTHER_TEXT = 8;
676
+ function guardSummary(guards) {
677
+ const parts = Object.entries(guards).map(([c, ids]) => `${c}: ${ids.slice(0, 2).join(", ")}`);
678
+ return parts.length ? parts.join("; ") : "no guard calls";
679
+ }
680
+ export function formatGateMap(map) {
681
+ const s = map.stats;
682
+ const out = [];
683
+ out.push(`rafter gates: ${s.files_scanned} files scanned, ${s.gates_found} gates found, ${s.twin_groups} twin groups, ${s.flagged_groups} flagged`);
684
+ out.push("");
685
+ out.push(`Gates (top ${s.gates_shown} of ${s.gates_found}, ranked by likely security weight; score file:line signature):`);
686
+ for (const g of map.gates)
687
+ out.push(` ${g.score} ${g.file}:${g.line} ${g.signature}`);
688
+ if (s.gates_shown < s.gates_found)
689
+ out.push(` ... ${s.gates_found - s.gates_shown} more (--limit N or --json)`);
690
+ const flagged = map.twins.filter((t) => t.flagged);
691
+ const other = map.twins.filter((t) => !t.flagged);
692
+ out.push("");
693
+ out.push("Flagged twin groups (same contract; a member lacks a guard its twins call):");
694
+ if (flagged.length === 0)
695
+ out.push(" none");
696
+ for (const t of flagged.slice(0, MAX_FLAGGED_TEXT)) {
697
+ out.push(` ${t.key} (${t.members.length}): missing ${t.missing.join(", ")}`);
698
+ for (const m of t.members.slice(0, MAX_MEMBERS_TEXT)) {
699
+ const lacks = m.lacks.length ? ` lacks: ${m.lacks.join(", ")}` : "";
700
+ out.push(` ${m.file}:${m.line} ${m.name} [${guardSummary(m.guards)}]${lacks}`);
701
+ }
702
+ if (t.members.length > MAX_MEMBERS_TEXT)
703
+ out.push(` ... ${t.members.length - MAX_MEMBERS_TEXT} more members (--json)`);
704
+ }
705
+ if (flagged.length > MAX_FLAGGED_TEXT)
706
+ out.push(` ... ${flagged.length - MAX_FLAGGED_TEXT} more flagged groups (--json)`);
707
+ out.push("");
708
+ out.push("Other twin groups:");
709
+ if (other.length === 0)
710
+ out.push(" none");
711
+ for (const t of other.slice(0, MAX_OTHER_TEXT)) {
712
+ const ms = t.members.slice(0, 4).map((m) => `${m.file}:${m.line}`).join(", ");
713
+ const more = t.members.length > 4 ? `, +${t.members.length - 4}` : "";
714
+ out.push(` ${t.key} (${t.members.length}): ${ms}${more}`);
715
+ }
716
+ if (other.length > MAX_OTHER_TEXT)
717
+ out.push(` ... ${other.length - MAX_OTHER_TEXT} more (--json)`);
718
+ out.push("");
719
+ out.push("Next: read each gate, state its contract, and name an input it should reject but accepts (rafter-code-review, section 0).");
720
+ return out.join("\n") + "\n";
721
+ }