@cosmicdrift/kumiko-guards 0.413.0 → 0.414.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/README.md +15 -9
  2. package/package.json +4 -4
  3. package/src/_lib/agent-docs-api-nodes.ts +9 -2
  4. package/src/_lib/agent-docs-api-render.ts +31 -10
  5. package/src/_lib/agent-docs-api.ts +13 -9
  6. package/src/_lib/agent-docs-feature-imports.ts +12 -1
  7. package/src/_lib/baseline-compare.ts +1 -2
  8. package/src/_lib/doc-status.ts +8 -4
  9. package/src/_lib/dockerfile.ts +28 -5
  10. package/src/_lib/escaped-literal.ts +26 -0
  11. package/src/_lib/npm-registry.ts +2 -2
  12. package/src/_lib/run-slots.ts +4 -6
  13. package/src/_lib/security-audit.ts +22 -6
  14. package/src/_lib/test-es-raw-writes.ts +5 -3
  15. package/src/changes.json +44 -0
  16. package/src/check-security.ts +4 -3
  17. package/src/guard-app-dockerfile.ts +29 -12
  18. package/src/guard-ignore-tag-reason.ts +18 -4
  19. package/src/guard-internal-subpath-imports.ts +35 -25
  20. package/src/guard-rls-session-settings.ts +48 -6
  21. package/src/guard-schema-cli-features.ts +22 -1
  22. package/src/guard-test-es-row-writes.ts +2 -1
  23. package/src/guard-unsafe-array-param.ts +4 -7
  24. package/src/pre-push.sh +46 -6
  25. package/src/run-guards.ts +0 -28
  26. package/src/run-repo-checks.ts +0 -6
  27. package/src/run-steps-parallel.ts +4 -4
  28. package/src/run-ui-guards.ts +1 -15
  29. package/src/_lib/german-test-title.ts +0 -94
  30. package/src/_lib/primitives-access.ts +0 -23
  31. package/src/check-predicates.ts +0 -244
  32. package/src/guard-admin-api.ts +0 -138
  33. package/src/guard-direct-fetch.ts +0 -161
  34. package/src/guard-error-reasons.ts +0 -210
  35. package/src/guard-event-store-writes.ts +0 -124
  36. package/src/guard-i18n-locale-terminology.ts +0 -134
  37. package/src/guard-no-custom-primitives.ts +0 -193
  38. package/src/guard-no-date-api.ts +0 -183
  39. package/src/guard-no-direct-fs.ts +0 -346
  40. package/src/guard-no-direct-process-env.ts +0 -127
  41. package/src/guard-no-inline-styles.ts +0 -64
  42. package/src/guard-no-raw-hooks.ts +0 -80
  43. package/src/guard-no-temporal-polyfill-import.ts +0 -131
  44. package/src/guard-primitives-discipline.ts +0 -357
  45. package/src/guard-raw-classname.ts +0 -117
  46. package/src/guard-raw-interactive-elements.ts +0 -164
  47. package/src/guard-restricted-symbols.ts +0 -155
  48. package/src/guard-silent-skip.ts +0 -186
  49. package/src/guard-test-es-fixtures.ts +0 -85
  50. package/src/guard-test-title.ts +0 -159
  51. package/src/guard-thin-wrappers.ts +0 -471
  52. package/src/guard-unsafe-json-parse.ts +0 -87
@@ -1,94 +0,0 @@
1
- import { isGermanComment } from "../guard-comment-lang";
2
-
3
- // German words that essentially never occur in an English test title. Words that are also
4
- // English (die, was, am, an, in, so, man, also, will, bin, war, hat, all) are left out on purpose.
5
- const GERMAN_TITLE_WORDS: ReadonlySet<string> = new Set([
6
- "der",
7
- "das",
8
- "den",
9
- "dem",
10
- "des",
11
- "ein",
12
- "eine",
13
- "einen",
14
- "einem",
15
- "kann",
16
- "wird",
17
- "werden",
18
- "nicht",
19
- "wenn",
20
- "oder",
21
- "und",
22
- "mit",
23
- "ohne",
24
- "bei",
25
- "ist",
26
- "sind",
27
- "auf",
28
- "zu",
29
- "von",
30
- "vom",
31
- "zum",
32
- "zur",
33
- "im",
34
- "vor",
35
- "aus",
36
- "als",
37
- "sich",
38
- "wie",
39
- "auch",
40
- "noch",
41
- "nur",
42
- "kein",
43
- "keine",
44
- "keinen",
45
- "gibt",
46
- "darf",
47
- "muss",
48
- "soll",
49
- "liefert",
50
- "wirft",
51
- "setzt",
52
- "zeigt",
53
- "gewinnt",
54
- "leer",
55
- "leere",
56
- "leerer",
57
- "bleibt",
58
- "macht",
59
- "fehlt",
60
- "schreibt",
61
- "liest",
62
- "sammelt",
63
- "nennt",
64
- "akzeptiert",
65
- "ueber",
66
- "uber",
67
- "fuer",
68
- "gegen",
69
- "nach",
70
- "dann",
71
- "weil",
72
- "statt",
73
- "sowie",
74
- "jede",
75
- "jeder",
76
- "jedes",
77
- ]);
78
-
79
- const QUOTED_OR_CODE_RE = /`[^`]*`|"[^"]*"|'[^']*'/g;
80
- const WORD_RE = /[\p{L}]+/gu;
81
-
82
- function isUpperCaseAcronym(word: string): boolean {
83
- return word.length > 1 && word === word.toUpperCase();
84
- }
85
-
86
- // Test titles are short, so one unambiguous German word is enough, unlike comments which
87
- // need an umlaut or two markers. Quoted text and code in backticks are fixture or identifier names.
88
- export function isGermanTestTitle(title: string): boolean {
89
- if (isGermanComment(title)) return true;
90
- const prose = title.replace(QUOTED_OR_CODE_RE, " ");
91
- return (prose.match(WORD_RE) ?? []).some(
92
- (word) => !isUpperCaseAcronym(word) && GERMAN_TITLE_WORDS.has(word.toLowerCase()),
93
- );
94
- }
@@ -1,23 +0,0 @@
1
- import type { SourceFile } from "ts-morph";
2
-
3
- const RENDERER_WEB_MODULES: ReadonlySet<string> = new Set([
4
- "@cosmicdrift/kumiko-renderer/web",
5
- "@cosmicdrift/kumiko-renderer-web",
6
- ]);
7
-
8
- // Shared by every "raw HTML tag instead of framework primitive" guard
9
- // (guard-no-custom-primitives, guard-raw-interactive-elements): proves the
10
- // primitive set was reachable in this file — either an import from
11
- // @cosmicdrift/kumiko-renderer/web (any symbol; the deprecated
12
- // @cosmicdrift/kumiko-renderer-web shim counts too), or a `usePrimitives`
13
- // named import, which lives in the shared layer of @cosmicdrift/kumiko-renderer,
14
- // not only in /web (see kumiko-enterprise/packages/ai-agent/src/web/turn-cards.tsx).
15
- export function hasPrimitivesAccess(sf: SourceFile): boolean {
16
- for (const imp of sf.getImportDeclarations()) {
17
- if (RENDERER_WEB_MODULES.has(imp.getModuleSpecifierValue())) return true;
18
- if (imp.getNamedImports().some((named) => named.getName() === "usePrimitives")) {
19
- return true;
20
- }
21
- }
22
- return false;
23
- }
@@ -1,244 +0,0 @@
1
- #!/usr/bin/env bun
2
- /**
3
- * Predicate-extraction check (WARNING, no fail).
4
- *
5
- * Finds two kinds of candidates for predicate extraction:
6
- * 1. Fat predicates — `if`/`while`/ternary conditions with >=3 logical
7
- * operators (&&/||) OR condition text >80 characters.
8
- * 2. Duplicates — the same (normalized) condition >=2x in the scan scope,
9
- * with >=2 operators (to exclude trivial `!x` checks).
10
- *
11
- * Output: warning with file:line + a pointer to the rule. Exit code is always 0.
12
- *
13
- * Usage:
14
- * bun guards/check-predicates.ts
15
- *
16
- * Rule: ~/.claude/rules/coding-standards.md → "Predicate Extraction"
17
- */
18
-
19
- import * as path from "node:path";
20
- import { type Node, type SourceFile, SyntaxKind } from "ts-morph";
21
- import { type AstGuard, runStandalone, type ScanSpec } from "./_lib/guard-kit";
22
-
23
- const ROOT = process.cwd();
24
-
25
- const SCAN: ScanSpec = {
26
- scope: "source",
27
- extensions: ["ts"],
28
- frameworkWithin: ["packages/*/src/**"],
29
- };
30
-
31
- const EXCLUDE = /(__tests__|\.test\.ts$|\.integration\.ts$|\.d\.ts$)/;
32
-
33
- const OPERATOR_THRESHOLD = 3;
34
- const LENGTH_THRESHOLD = 80;
35
- const DUP_MIN_OPERATORS = 2;
36
-
37
- interface Site {
38
- file: string;
39
- line: number;
40
- text: string;
41
- operators: number;
42
- ands: number;
43
- ors: number;
44
- }
45
-
46
- function normalize(text: string): string {
47
- return text.replace(/\s+/g, " ").trim();
48
- }
49
-
50
- // Keywords/primitives we keep literal when building the structural shape.
51
- // Everything else that looks like an identifier or property access collapses to `_`,
52
- // so `toKebab(x) !== x` and `toKebab(y) !== y` share the same shape.
53
- const SHAPE_KEEP = new Set([
54
- "typeof",
55
- "instanceof",
56
- "in",
57
- "of",
58
- "new",
59
- "void",
60
- "delete",
61
- "await",
62
- "true",
63
- "false",
64
- "null",
65
- "undefined",
66
- "string",
67
- "number",
68
- "object",
69
- "boolean",
70
- "symbol",
71
- "bigint",
72
- "function",
73
- ]);
74
-
75
- function structuralShape(text: string): string {
76
- return text.replace(/\b[a-zA-Z_$][\w$]*(\.[a-zA-Z_$][\w$]*)*\b/g, (match) => {
77
- const dot = match.indexOf(".");
78
- const head = dot === -1 ? match : match.slice(0, dot);
79
- return SHAPE_KEEP.has(head) ? match : "_";
80
- });
81
- }
82
-
83
- function countOperators(text: string): { ands: number; ors: number } {
84
- const ands = (text.match(/&&/g) ?? []).length;
85
- const ors = (text.match(/\|\|/g) ?? []).length;
86
- return { ands, ors };
87
- }
88
-
89
- function collectConditions(sf: SourceFile): Site[] {
90
- const sites: Site[] = [];
91
- const file = path.relative(ROOT, sf.getFilePath());
92
-
93
- const push = (node: Node, conditionNode: Node | undefined): void => {
94
- // skip: a missing condition (e.g. `for (;;)`) has nothing to extract
95
- if (!conditionNode) return;
96
- const raw = conditionNode.getText();
97
- const text = normalize(raw);
98
- const { ands, ors } = countOperators(text);
99
- const operators = ands + ors;
100
- // skip: a short condition without logical operators needs no named predicate
101
- if (operators === 0 && text.length < LENGTH_THRESHOLD) return;
102
- sites.push({
103
- file,
104
- line: node.getStartLineNumber(),
105
- text,
106
- operators,
107
- ands,
108
- ors,
109
- });
110
- };
111
-
112
- for (const ifNode of sf.getDescendantsOfKind(SyntaxKind.IfStatement)) {
113
- push(ifNode, ifNode.getExpression());
114
- }
115
- for (const whileNode of sf.getDescendantsOfKind(SyntaxKind.WhileStatement)) {
116
- push(whileNode, whileNode.getExpression());
117
- }
118
- for (const tern of sf.getDescendantsOfKind(SyntaxKind.ConditionalExpression)) {
119
- push(tern, tern.getCondition());
120
- }
121
- return sites;
122
- }
123
-
124
- type TextDuplicateGroup = [Site, Site, ...Site[]];
125
- type ShapeDuplicateGroup = { shape: string; sites: Site[] };
126
-
127
- function bucketDuplicateCandidates(allSites: readonly Site[]): {
128
- byText: Map<string, Site[]>;
129
- byShape: Map<string, Site[]>;
130
- } {
131
- const byText = new Map<string, Site[]>();
132
- const byShape = new Map<string, Site[]>();
133
- for (const s of allSites) {
134
- // Count as duplicate candidate if either >=2 operators OR text long enough
135
- // that repetition is still worth extracting (covers 1-operator but lengthy
136
- // domain checks like kebab-case validation).
137
- if (s.operators < DUP_MIN_OPERATORS && s.text.length < LENGTH_THRESHOLD) continue;
138
- const textBucket = byText.get(s.text) ?? [];
139
- textBucket.push(s);
140
- byText.set(s.text, textBucket);
141
- const shape = structuralShape(s.text);
142
- const shapeBucket = byShape.get(shape) ?? [];
143
- shapeBucket.push(s);
144
- byShape.set(shape, shapeBucket);
145
- }
146
- return { byText, byShape };
147
- }
148
-
149
- function findTextDuplicates(byText: ReadonlyMap<string, Site[]>): TextDuplicateGroup[] {
150
- const textDups: TextDuplicateGroup[] = [];
151
- for (const bucket of byText.values()) {
152
- if (bucket.length < 2) continue;
153
- const [first, second, ...rest] = bucket;
154
- if (first !== undefined && second !== undefined) textDups.push([first, second, ...rest]);
155
- }
156
- return textDups;
157
- }
158
-
159
- function findShapeDuplicates(byShape: ReadonlyMap<string, Site[]>): ShapeDuplicateGroup[] {
160
- const shapeDups: ShapeDuplicateGroup[] = [];
161
- for (const [shape, bucket] of byShape.entries()) {
162
- if (bucket.length < 2) continue;
163
- // Skip when sites are already covered by exact-text duplicate group.
164
- const firstText = bucket[0]?.text;
165
- const allSame = bucket.every((s) => s.text === firstText);
166
- if (allSame) continue;
167
- shapeDups.push({ shape, sites: bucket });
168
- }
169
- return shapeDups;
170
- }
171
-
172
- const snip = (text: string): string => (text.length > 90 ? `${text.slice(0, 87)}...` : text);
173
-
174
- function printFatPredicates(fatSites: readonly Site[]): void {
175
- console.log(`\n Fat-predicate candidates:`);
176
- for (const s of fatSites) {
177
- const hint = s.ands === 0 && s.ors >= 3 ? " (Array.includes/Set?)" : "";
178
- console.log(` ${s.file}:${s.line} [${s.ands}&& ${s.ors}||] ${snip(s.text)}${hint}`);
179
- }
180
- }
181
-
182
- function printTextDuplicates(textDups: readonly TextDuplicateGroup[]): void {
183
- console.log(`\n Exact duplicates:`);
184
- for (const group of textDups) {
185
- const [first] = group;
186
- console.log(` ${group.length}x ${snip(first.text)}`);
187
- for (const s of group) console.log(` - ${s.file}:${s.line}`);
188
- }
189
- }
190
-
191
- function printShapeDuplicates(shapeDups: readonly ShapeDuplicateGroup[]): void {
192
- console.log(`\n Structural duplicates:`);
193
- for (const { shape, sites } of shapeDups) {
194
- console.log(` ${sites.length}x shape: ${snip(shape)}`);
195
- for (const s of sites) console.log(` - ${s.file}:${s.line} ${snip(s.text)}`);
196
- }
197
- }
198
-
199
- // Warning-only check: never blocks (always returns 0 violations). The
200
- // findings are printed via console; the runner shows `✓` as long as nothing throws.
201
- export const guard: AstGuard = {
202
- name: "Predicate Extraction Check",
203
- scan: SCAN,
204
- run(files) {
205
- const allSites: Site[] = [];
206
- let scanned = 0;
207
- for (const sf of files) {
208
- if (EXCLUDE.test(sf.getFilePath())) continue;
209
- scanned++;
210
- allSites.push(...collectConditions(sf));
211
- }
212
-
213
- const fatSites = allSites.filter(
214
- (s) => s.operators >= OPERATOR_THRESHOLD || s.text.length >= LENGTH_THRESHOLD,
215
- );
216
- const { byText, byShape } = bucketDuplicateCandidates(allSites);
217
- const textDups = findTextDuplicates(byText);
218
- const shapeDups = findShapeDuplicates(byShape);
219
-
220
- console.log(`Predicate-Extraction Check: ${scanned} files checked.`);
221
- console.log(
222
- ` Fat predicates (>=${OPERATOR_THRESHOLD} ops or >${LENGTH_THRESHOLD} chars): ${fatSites.length}`,
223
- );
224
- console.log(` Exact duplicates: ${textDups.length}`);
225
- console.log(` Structural duplicates (same pattern, different names): ${shapeDups.length}`);
226
-
227
- if (fatSites.length === 0 && textDups.length === 0 && shapeDups.length === 0) {
228
- console.log(" Nothing to report.");
229
- return { violations: [] };
230
- }
231
-
232
- if (fatSites.length > 0) printFatPredicates(fatSites);
233
- if (textDups.length > 0) printTextDuplicates(textDups);
234
- if (shapeDups.length > 0) printShapeDuplicates(shapeDups);
235
-
236
- console.log(
237
- "\n Rule: extract as a named function (isX/hasY/canZ) when the condition has a stable name.",
238
- );
239
- console.log(" Warning, no fail.");
240
- return { violations: [] };
241
- },
242
- };
243
-
244
- if (import.meta.main) runStandalone(guard);
@@ -1,138 +0,0 @@
1
- #!/usr/bin/env bun
2
- /**
3
- * Guard: blocks calls to the event-store admin API (`appendRaw`/`appendRawBatch`)
4
- * outside allowed paths.
5
- *
6
- * The admin API is a Marten bypass for legacy data imports. It BYPASSES the
7
- * pipeline — no projections, no postSave hooks, no SSE/search/audit. Used
8
- * accidentally from application code, that causes state inconsistencies that
9
- * surface very late (at the next projection rebuild, or never).
10
- *
11
- * Second line of defense next to the deep-import path: even if someone pulls
12
- * `@kubiko/framework/event-store/admin-api` directly, this guard catches it
13
- * at the next `bun kumiko check`.
14
- *
15
- * Usage:
16
- * bun guards/guard-admin-api.ts
17
- *
18
- * Exit 1 if violations found, 0 if clean.
19
- */
20
-
21
- import * as path from "node:path";
22
- import { type CallExpression, type SourceFile, SyntaxKind } from "ts-morph";
23
- import { findRepoRootFor } from "./_lib/baseline-compare";
24
- import { ALL_REPO_KINDS, type AstGuard, runStandalone, type ScanSpec } from "./_lib/guard-kit";
25
- import { type RepoRoot, resolveRepoRoots } from "./_lib/roots";
26
-
27
- const ROOT = process.cwd();
28
-
29
- const SCAN: ScanSpec = { kinds: ALL_REPO_KINDS, scope: "source", extensions: ["ts"] };
30
-
31
- // Test files may use the API freely — they are the primary verifiers.
32
- // App code is never shipped through tests.
33
- const EXCLUDE = /(__tests__|\.test\.ts$|\.integration\.ts$|\.d\.ts$)/;
34
-
35
- // Allowed callers: migration runners (sample-local, src/ and bin/) +
36
- // admin scripts + the definition itself.
37
- const ALLOWLIST: readonly RegExp[] = [
38
- /^samples\/[^/]+\/src\/migration\//,
39
- /^scripts\/migrations\//,
40
- /^packages\/framework\/src\/event-store\/admin-api\.ts$/,
41
- ];
42
-
43
- const GUARDED_CALLS = new Set(["appendRaw", "appendRawBatch"]);
44
-
45
- export interface Violation {
46
- file: string;
47
- line: number;
48
- functionName: string;
49
- enclosingFunction: string;
50
- }
51
-
52
- function collectViolations(sourceFile: SourceFile, roots: readonly RepoRoot[]): Violation[] {
53
- const violations: Violation[] = [];
54
- const filePath = sourceFile.getFilePath();
55
- // Allowlist is repo-root-relative; the reported path stays cwd-relative for the security baseline.
56
- const repoRoot = findRepoRootFor(filePath, roots);
57
- const allowlistPath = path.relative(repoRoot?.absPath ?? ROOT, filePath);
58
- const relativePath = path.relative(ROOT, filePath);
59
- if (isAllowed(allowlistPath)) return violations;
60
-
61
- const calls = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression);
62
- for (const call of calls) {
63
- const fnName = getCalleeName(call);
64
- if (!fnName || !GUARDED_CALLS.has(fnName)) continue;
65
- violations.push({
66
- file: relativePath,
67
- line: call.getStartLineNumber(),
68
- functionName: fnName,
69
- enclosingFunction: findEnclosingName(call),
70
- });
71
- }
72
- return violations;
73
- }
74
-
75
- function isAllowed(relativePath: string): boolean {
76
- return ALLOWLIST.some((re) => re.test(relativePath));
77
- }
78
-
79
- // Extract the called name. Handles:
80
- // appendRaw(...) → "appendRaw" (Identifier)
81
- // someNamespace.appendRaw(...) → "appendRaw" (PropertyAccessExpression)
82
- // Any other callee shape returns null — we only want bare-name / qualified-name
83
- // references to the known function names.
84
- function getCalleeName(call: CallExpression): string | null {
85
- const expr = call.getExpression();
86
- if (expr.isKind(SyntaxKind.Identifier)) {
87
- return expr.getText();
88
- }
89
- if (expr.getKind() === SyntaxKind.PropertyAccessExpression) {
90
- const name = expr.asKindOrThrow(SyntaxKind.PropertyAccessExpression).getName();
91
- return name;
92
- }
93
- return null;
94
- }
95
-
96
- function findEnclosingName(call: CallExpression): string {
97
- let cur = call.getParent();
98
- while (cur) {
99
- if (cur.isKind(SyntaxKind.FunctionDeclaration) || cur.isKind(SyntaxKind.MethodDeclaration)) {
100
- return cur.getName() ?? "<anonymous>";
101
- }
102
- if (cur.isKind(SyntaxKind.FunctionExpression) || cur.isKind(SyntaxKind.ArrowFunction)) {
103
- const parent = cur.getParent();
104
- if (parent?.isKind(SyntaxKind.VariableDeclaration)) return parent.getName();
105
- if (parent?.isKind(SyntaxKind.PropertyAssignment)) return parent.getName();
106
- return "<anonymous>";
107
- }
108
- cur = cur.getParent();
109
- }
110
- return "<top-level>";
111
- }
112
-
113
- export const guard: AstGuard = {
114
- name: "Admin-API Guard",
115
- scan: SCAN,
116
- // App repos are not exempt — appendRaw/appendRawBatch bypasses the pipeline.
117
- security: true,
118
- hint: "Admin API (appendRaw/appendRawBatch) bypasses the pipeline — only allowed in samples/*/migration/ or scripts/migrations/. For domain events: ctx.events.append / write handler.",
119
- run(files, roots: readonly RepoRoot[] = resolveRepoRoots()) {
120
- const violations: Array<{ file: string; line: number; message: string }> = [];
121
-
122
- for (const sf of files) {
123
- const file = sf.getFilePath();
124
- if (EXCLUDE.test(file)) continue;
125
- for (const v of collectViolations(sf, roots)) {
126
- violations.push({
127
- file: v.file,
128
- line: v.line,
129
- message: `${v.functionName}(...) in ${v.enclosingFunction}`,
130
- });
131
- }
132
- }
133
-
134
- return { violations };
135
- },
136
- };
137
-
138
- if (import.meta.main) runStandalone(guard);
@@ -1,161 +0,0 @@
1
- #!/usr/bin/env bun
2
- /**
3
- * Guard: finds raw `fetch(` calls in server code outside the client-scoped
4
- * exceptions.
5
- *
6
- * `egress(policy)` (@cosmicdrift/kumiko-framework/http) is
7
- * the single exported way for server code to speak outward — it enforces an
8
- * SSRF policy (external/internal/tenant-supplied) at the call site instead
9
- * of leaving that to convention. This guard fails on raw `fetch(` in server
10
- * code so a new call site can't silently skip the policy.
11
- *
12
- * Scoping: client code legitimately calls `fetch(` against its own origin
13
- * (browser same-origin, not server egress) — excluded via path (`web/`,
14
- * `public/`). Server scans are `*.ts` only (`SCAN`).
15
- *
16
- * Usage:
17
- * bun guards/guard-direct-fetch.ts
18
- *
19
- * Exit 1 on violations in non-allowlisted files, 0 when clean.
20
- */
21
-
22
- import { relative as pathRelative } from "node:path";
23
- import { type CallExpression, type Node, type SourceFile, SyntaxKind } from "ts-morph";
24
- import { isGenericReason, literalReasonText } from "./_lib/generic-reason";
25
- import {
26
- ALL_REPO_KINDS,
27
- type AstGuard,
28
- findRepoRootFor,
29
- isAllowlisted,
30
- relFromRepoRoot,
31
- runStandalone,
32
- type ScanSpec,
33
- } from "./_lib/guard-kit";
34
- import { lineHasIgnoreTag } from "./_lib/ignore-tag";
35
- import { type RepoRoot, resolveRepoRoots } from "./_lib/roots";
36
-
37
- const SCAN: ScanSpec = {
38
- kinds: ALL_REPO_KINDS,
39
- scope: "source",
40
- extensions: ["ts"],
41
- frameworkWithin: ["packages/*/src/**", "samples/**"],
42
- };
43
-
44
- const EXCLUDE =
45
- /(__tests__|\.test\.ts$|\.integration\.ts$|\.d\.ts$|(?:^|\/)web\/|(?:^|\/)public\/)/;
46
-
47
- // Prefixed by RepoRoot.name (not kind): kind "app" is shared across
48
- // unregistered repos.
49
-
50
- // packages/framework/src/http/egress.ts IS the egress() implementation.
51
- const ALLOWLIST = [/^kumiko-framework\/packages\/framework\/src\/http\/egress\.ts$/];
52
- const IGNORE_TAG = "kumiko-lint-ignore direct-fetch";
53
- const IGNORE_TAG_WITH_REASON_RE =
54
- /kumiko-lint-ignore\s+(?:[\w-]+,)*direct-fetch(?:,[\w-]+)*(?=\s|$)(.*)$/;
55
-
56
- interface Violation {
57
- line: number;
58
- snippet: string;
59
- }
60
-
61
- // `self` omitted: Worker globals live under web/public (excluded); a local
62
- // `const self = this` binding was a systematic FP.
63
- const GLOBAL_FETCH_RECEIVERS = new Set(["globalThis", "window"]);
64
-
65
- // The marker is a per-line skip for a security guard, so it only counts with a
66
- // non-generic reason after it — a bare marker still reports the finding.
67
- function hasIgnoreTagWithReason(sf: SourceFile, line: number): boolean {
68
- const lines = sf.getFullText().split("\n");
69
- const idx = line - 1;
70
- return [lines[idx] ?? "", lines[idx - 1] ?? ""].some((text) => {
71
- if (!lineHasIgnoreTag(text, IGNORE_TAG)) return false;
72
- const reason = (IGNORE_TAG_WITH_REASON_RE.exec(text)?.[1] ?? "")
73
- .replace(/^\s*(?:—|–|-|:)\s*/, "")
74
- .trim();
75
- return !isGenericReason(reason);
76
- });
77
- }
78
-
79
- /** Same-origin path literal (`"/api/..."`, '`/demo`') — not an SSRF risk. */
80
- function isSameOriginLiteralArg(expr: CallExpression): boolean {
81
- const arg = expr.getArguments()[0];
82
- if (!arg) return false;
83
-
84
- const template = arg.asKind(SyntaxKind.TemplateExpression);
85
- if (template) {
86
- const head = template.getHead().getLiteralText();
87
- // A lone "/" head lets the first interpolation open with another "/",
88
- // producing a protocol-relative "//evil.example" — require at least one
89
- // static character after the leading slash so no interpolation can
90
- // change the origin.
91
- return head.startsWith("/") && !head.startsWith("//") && head.length >= 2;
92
- }
93
-
94
- // Runtime value, not source text: "/\/attacker.example" is "//attacker.example".
95
- const path = literalReasonText(arg);
96
- if (path === undefined) return false;
97
- // Reject protocol-relative URLs ("//evil.example") — not same-origin.
98
- return path.startsWith("/") && !path.startsWith("//");
99
- }
100
-
101
- function isGlobalFetchAccess(callee: Node): boolean {
102
- const pae = callee.asKind(SyntaxKind.PropertyAccessExpression);
103
- if (pae?.getName() !== "fetch") return false;
104
- const receiver = pae.getExpression();
105
- return (
106
- receiver.getKind() === SyntaxKind.Identifier && GLOBAL_FETCH_RECEIVERS.has(receiver.getText())
107
- );
108
- }
109
-
110
- function findRawFetchCalls(sf: SourceFile): Violation[] {
111
- const violations: Violation[] = [];
112
- for (const expr of sf.getDescendantsOfKind(SyntaxKind.CallExpression)) {
113
- const callee = expr.getExpression();
114
- const isBareFetch = callee.getKind() === SyntaxKind.Identifier && callee.getText() === "fetch";
115
- if (!(isBareFetch || isGlobalFetchAccess(callee))) continue;
116
- if (isSameOriginLiteralArg(expr)) continue;
117
- violations.push({
118
- line: expr.getStartLineNumber(),
119
- snippet: expr.getText().slice(0, 120),
120
- });
121
- }
122
- return violations;
123
- }
124
-
125
- export const guard: AstGuard = {
126
- name: "Direct-Fetch Guard",
127
- scan: SCAN,
128
- security: true,
129
- hint:
130
- "Replace raw fetch(...) with egress(policy)(...) from @cosmicdrift/kumiko-framework/http (framework#2147). " +
131
- 'Same-origin path literal (`"/api/..."`) is allowed; otherwise put `// kumiko-lint-ignore direct-fetch <specific reason>` on the line above (a bare marker does not count). ' +
132
- "Local bindings named fetch are flagged (false positive — unblock via that marker). " +
133
- 'Known gap: bracket access (globalThis["fetch"](...)).',
134
- run(files, roots: readonly RepoRoot[] = resolveRepoRoots()) {
135
- const violations: Array<{ file: string; line: number; message: string }> = [];
136
-
137
- for (const sf of files) {
138
- const file = sf.getFilePath();
139
- const rel = relFromRepoRoot(file, roots);
140
- if (EXCLUDE.test(rel)) continue;
141
- const root = findRepoRootFor(file, roots);
142
- const key =
143
- root === undefined ? undefined : `${root.name}/${pathRelative(root.absPath, file)}`;
144
- if (key !== undefined && isAllowlisted(key, ALLOWLIST)) continue;
145
- for (const v of findRawFetchCalls(sf)) {
146
- if (hasIgnoreTagWithReason(sf, v.line)) continue;
147
- violations.push({
148
- // cwd-relative, not repo-relative `rel` — the security baseline
149
- // needs an unambiguous path to resolve back to (repo, relPath).
150
- file: pathRelative(process.cwd(), file),
151
- line: v.line,
152
- message: `raw fetch() call: ${v.snippet}`,
153
- });
154
- }
155
- }
156
-
157
- return { violations };
158
- },
159
- };
160
-
161
- if (import.meta.main) runStandalone(guard);