@cosmicdrift/kumiko-guards 0.414.0 → 0.415.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cosmicdrift/kumiko-guards",
3
- "version": "0.414.0",
3
+ "version": "0.415.0",
4
4
  "description": "AST-based security guards for Kumiko repos: direct-fs/fetch, tenant escalation, admin-API, escape hatches and related checks, run over a shared ts-morph project.",
5
5
  "license": "MIT",
6
6
  "author": "Marc Frost <marc@cosmicdriftgamestudio.com>",
@@ -36,7 +36,7 @@
36
36
  "kumiko-pre-push": "./src/pre-push.sh"
37
37
  },
38
38
  "dependencies": {
39
- "@cosmicdrift/kumiko-types": "0.414.0",
39
+ "@cosmicdrift/kumiko-types": "0.415.0",
40
40
  "ts-morph": "^28.0.0",
41
41
  "zod": "^4.6.7"
42
42
  },
@@ -52,7 +52,7 @@
52
52
  "LICENSE"
53
53
  ],
54
54
  "peerDependencies": {
55
- "@cosmicdrift/kumiko-framework": "0.414.0"
55
+ "@cosmicdrift/kumiko-framework": "0.415.0"
56
56
  },
57
57
  "peerDependenciesMeta": {
58
58
  "@cosmicdrift/kumiko-framework": {
@@ -60,6 +60,6 @@
60
60
  }
61
61
  },
62
62
  "devDependencies": {
63
- "@cosmicdrift/kumiko-framework": "0.414.0"
63
+ "@cosmicdrift/kumiko-framework": "0.415.0"
64
64
  }
65
65
  }
package/src/changes.json CHANGED
@@ -1,4 +1,11 @@
1
1
  [
2
+ {
3
+ "version": "0.415.0",
4
+ "type": "breaking",
5
+ "title": "security-plugin-suppression guard rejects biome-ignore on the security Biome plugins",
6
+ "detail": "`biome-ignore lint/plugin` covers every plugin, so a reason of three words silenced the SSRF (`no-direct-fetch`), path-traversal (`no-direct-fs`), event-store write (`es-literal-writes`, `es-literal-writes-tests`, `restricted-event-store-symbols`) and `admin-api` checks. The new guard `security-plugin-suppression` re-runs Biome over every file with such a comment, in a temp copy with those comments neutralised and only the security plugins from the preset enabled. Each remaining diagnostic is a finding. UI plugins (raw-ui, raw-hooks, ...) and browser-side fetch in `web/**/*.tsx` stay suppressible. A Biome answer that cannot be parsed fails the guard. The guard needs `@biomejs/biome` and the `biome-rules` preset in the repo and does nothing without them.",
7
+ "migration": "Replace each suppressed call with the safe API (`egress(policy)` instead of `fetch`, `FileStorageProvider` or `readBundledAsset` instead of `node:fs`, the event-store API instead of literal writes). A reviewed exception that cannot move is frozen once with `kumiko-guards guards --write-baseline --guard=security-plugin-suppression` into `.kumiko-security-plugin-suppression-baseline.json`; without that file the guard fails closed."
8
+ },
2
9
  {
3
10
  "version": "0.414.0",
4
11
  "type": "fix",
@@ -0,0 +1,368 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Security-Plugin-Suppression Guard: `// biome-ignore lint/plugin: <reason>` must not silence the security Biome plugins
4
+ * (admin API, event-store literal writes, restricted event-store symbols, direct fs, server-side direct fetch).
5
+ * The category `lint/plugin` covers every plugin, so a three-word reason would pass the ignore-tag-reason guard and still switch off
6
+ * an SSRF, path-traversal or event-store check. The guard re-runs Biome over the files that carry such a comment, in a temp copy
7
+ * with those comments neutralised and only the security plugins (taken from the preset, `includes` untouched) enabled.
8
+ * Every remaining diagnostic is a suppressed security finding. Exceptions live in the reviewed
9
+ * `.kumiko-security-plugin-suppression-baseline.json`; without it the guard fails closed. UI plugins (raw-ui, raw-hooks, ...)
10
+ * and browser-side fetch stay suppressible.
11
+ */
12
+
13
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
14
+ import { tmpdir } from "node:os";
15
+ import path from "node:path";
16
+ import { isPlainObject } from "@cosmicdrift/kumiko-types/type-guards";
17
+ import type { SourceFile } from "ts-morph";
18
+ import { scanCommentTrivia } from "./_lib/comment-trivia";
19
+ import {
20
+ ALL_REPO_KINDS,
21
+ type AstGuard,
22
+ baselineRatchet,
23
+ buildSharedProject,
24
+ filesForGuard,
25
+ findRepoRootFor,
26
+ type GuardViolation,
27
+ isLocalFinding,
28
+ relFromRepoRoot,
29
+ runStandalone,
30
+ type ScanSpec,
31
+ } from "./_lib/guard-kit";
32
+ import { type RepoRoot, resolveRepoRoots } from "./_lib/roots";
33
+
34
+ const ROOT = process.cwd();
35
+ const GUARD_NAME = "security-plugin-suppression";
36
+
37
+ const SCAN: ScanSpec = {
38
+ scope: "source+tests",
39
+ kinds: ALL_REPO_KINDS,
40
+ extensions: ["ts", "tsx"],
41
+ };
42
+
43
+ const EXCLUDE = /(\.d\.(ts|tsx)$|\/dist\/)/;
44
+
45
+ const SECURITY_PLUGIN_NAMES: ReadonlySet<string> = new Set([
46
+ "admin-api",
47
+ "es-literal-writes",
48
+ "es-literal-writes-tests",
49
+ "restricted-event-store-symbols",
50
+ "no-direct-fs",
51
+ "no-direct-fetch",
52
+ ]);
53
+ // no-direct-fetch has a second preset entry for browser code, which is no SSRF path.
54
+ const BROWSER_ONLY_INCLUDE = "**/web/**/*.tsx";
55
+
56
+ const PLUGIN_SUPPRESSION_RE = /biome-ignore(?:-all|-start)?\s+lint\/plugin\S*/;
57
+ // Same length as the original, so line and column numbers of the diagnostics stay valid.
58
+ const NEUTRALIZE_RE = /biome-ignore(?=(?:-all|-start)?\s+lint\/plugin)/g;
59
+ const NEUTRALIZED = "biome_ignore";
60
+
61
+ const PRESET_REPO_PATH = "packages/framework/presets/biome-rules.json";
62
+ const PRESET_PACKAGE_PATH = "@cosmicdrift/kumiko-framework/biome-rules";
63
+
64
+ type PresetPlugin = {
65
+ readonly path: string;
66
+ readonly resolutionKind?: string;
67
+ readonly includes?: readonly string[];
68
+ };
69
+
70
+ type PluginFinding = { readonly count: number; readonly firstLine: number };
71
+
72
+ export type SecurityPluginScan = {
73
+ readonly findings: Readonly<Record<string, PluginFinding>>;
74
+ readonly failures: readonly string[];
75
+ };
76
+
77
+ export function hasPluginSuppression(fullText: string): boolean {
78
+ if (!fullText.includes("lint/plugin")) return false;
79
+ return scanCommentTrivia(fullText).some((comment) => PLUGIN_SUPPRESSION_RE.test(comment.text));
80
+ }
81
+
82
+ export function neutralizePluginSuppressions(fullText: string): string {
83
+ let result = "";
84
+ let copiedUpTo = 0;
85
+ for (const comment of scanCommentTrivia(fullText)) {
86
+ const neutralized = comment.text.replace(NEUTRALIZE_RE, NEUTRALIZED);
87
+ if (neutralized === comment.text) continue;
88
+ result += fullText.slice(copiedUpTo, comment.start) + neutralized;
89
+ copiedUpTo = comment.start + comment.text.length;
90
+ }
91
+ return result + fullText.slice(copiedUpTo);
92
+ }
93
+
94
+ function isPresetPlugin(value: unknown): value is PresetPlugin {
95
+ return (
96
+ typeof value === "object" &&
97
+ value !== null &&
98
+ "path" in value &&
99
+ typeof value.path === "string" &&
100
+ (!("includes" in value) ||
101
+ (Array.isArray(value.includes) && value.includes.every((item) => typeof item === "string")))
102
+ );
103
+ }
104
+
105
+ function resolvePresetPath(repoRoot: string): string | undefined {
106
+ const inRepo = path.join(repoRoot, PRESET_REPO_PATH);
107
+ if (existsSync(inRepo)) return inRepo;
108
+ try {
109
+ return Bun.resolveSync(PRESET_PACKAGE_PATH, repoRoot);
110
+ } catch {
111
+ return undefined;
112
+ }
113
+ }
114
+
115
+ function resolveBiomeBin(repoRoot: string): string | undefined {
116
+ try {
117
+ return path.join(
118
+ path.dirname(Bun.resolveSync("@biomejs/biome/package.json", repoRoot)),
119
+ "bin",
120
+ "biome",
121
+ );
122
+ } catch {
123
+ return undefined;
124
+ }
125
+ }
126
+
127
+ function pluginName(pluginPath: string): string {
128
+ return path.basename(pluginPath, ".grit");
129
+ }
130
+
131
+ function securityPluginEntries(presetPath: string): PresetPlugin[] | string {
132
+ let parsed: unknown;
133
+ try {
134
+ parsed = JSON.parse(readFileSync(presetPath, "utf-8"));
135
+ } catch (error) {
136
+ return `cannot read Biome preset ${presetPath}: ${error instanceof Error ? error.message : String(error)}`;
137
+ }
138
+ const plugins =
139
+ typeof parsed === "object" && parsed !== null && "plugins" in parsed
140
+ ? parsed.plugins
141
+ : undefined;
142
+ if (!Array.isArray(plugins) || !plugins.every(isPresetPlugin)) {
143
+ return `Biome preset ${presetPath} has no valid "plugins" list`;
144
+ }
145
+ const baseDir = path.dirname(presetPath);
146
+ const entries = plugins
147
+ .filter((entry) => SECURITY_PLUGIN_NAMES.has(pluginName(entry.path)))
148
+ .filter((entry) => !(entry.includes ?? []).includes(BROWSER_ONLY_INCLUDE))
149
+ .map((entry) => ({ ...entry, path: path.resolve(baseDir, entry.path) }));
150
+ const found = new Set(entries.map((entry) => pluginName(entry.path)));
151
+ const missing = [...SECURITY_PLUGIN_NAMES].filter((name) => !found.has(name));
152
+ return missing.length > 0
153
+ ? `Biome preset ${presetPath} lacks security plugin(s): ${missing.join(", ")}`
154
+ : entries;
155
+ }
156
+
157
+ type BiomeDiagnostic = {
158
+ readonly severity: string;
159
+ readonly category: string;
160
+ readonly message: string;
161
+ readonly path: string | undefined;
162
+ readonly line: number;
163
+ };
164
+
165
+ export function parseBiomeDiagnostics(stdout: string): BiomeDiagnostic[] | undefined {
166
+ const jsonLine = stdout.split("\n").find((line) => line.startsWith("{"));
167
+ if (jsonLine === undefined) return undefined;
168
+ let parsed: unknown;
169
+ try {
170
+ parsed = JSON.parse(jsonLine);
171
+ } catch {
172
+ return undefined;
173
+ }
174
+ const raw = isPlainObject(parsed) ? parsed["diagnostics"] : undefined;
175
+ if (!Array.isArray(raw)) return undefined;
176
+ const diagnostics: BiomeDiagnostic[] = [];
177
+ for (const item of raw) {
178
+ const diagnostic = toBiomeDiagnostic(item);
179
+ if (diagnostic === undefined) return undefined;
180
+ diagnostics.push(diagnostic);
181
+ }
182
+ return diagnostics;
183
+ }
184
+
185
+ function diagnosticLocation(location: unknown): { path: string | undefined; line: number } {
186
+ if (!isPlainObject(location)) return { path: undefined, line: 1 };
187
+ const { path: locPath, start } = location;
188
+ const line = isPlainObject(start) && typeof start["line"] === "number" ? start["line"] : 1;
189
+ return { path: typeof locPath === "string" ? locPath : undefined, line };
190
+ }
191
+
192
+ function toBiomeDiagnostic(item: unknown): BiomeDiagnostic | undefined {
193
+ if (!isPlainObject(item)) return undefined;
194
+ const { severity, category, message, location } = item;
195
+ if (typeof severity !== "string" || typeof category !== "string") return undefined;
196
+ return {
197
+ severity,
198
+ category,
199
+ message: typeof message === "string" ? message : "",
200
+ ...diagnosticLocation(location),
201
+ };
202
+ }
203
+
204
+ function runBiomeInTempRepo(
205
+ biomeBin: string,
206
+ tempDir: string,
207
+ plugins: readonly PresetPlugin[],
208
+ ): { diagnostics: BiomeDiagnostic[] } | { failure: string } {
209
+ writeFileSync(
210
+ path.join(tempDir, "biome.json"),
211
+ JSON.stringify({
212
+ root: true,
213
+ vcs: { enabled: false },
214
+ formatter: { enabled: false },
215
+ assist: { enabled: false },
216
+ linter: { enabled: true, rules: { preset: "none" } },
217
+ plugins,
218
+ }),
219
+ );
220
+ const proc = Bun.spawnSync(
221
+ ["bun", biomeBin, "lint", "--reporter=json", "--max-diagnostics=none", "."],
222
+ { cwd: tempDir, stdout: "pipe", stderr: "pipe" },
223
+ );
224
+ const diagnostics = parseBiomeDiagnostics(proc.stdout.toString());
225
+ // Exit 1 is Biome's "diagnostics found"; anything else, or an unreadable answer, is a crash.
226
+ if (diagnostics === undefined || (proc.exitCode !== 0 && proc.exitCode !== 1)) {
227
+ return {
228
+ failure: `Biome did not answer with a readable lint report (exit ${proc.exitCode}): ${proc.stderr.toString().trim().slice(0, 300)}`,
229
+ };
230
+ }
231
+ const broken = diagnostics.find((d) => d.severity === "error" && d.category !== "plugin");
232
+ if (broken !== undefined) {
233
+ return { failure: `Biome reported a non-plugin error (${broken.category}): ${broken.message}` };
234
+ }
235
+ return { diagnostics: diagnostics.filter((d) => d.category === "plugin") };
236
+ }
237
+
238
+ export function scanSecurityPluginSuppressions(
239
+ repoRoot: string,
240
+ filesByRelPath: ReadonlyMap<string, string>,
241
+ ): SecurityPluginScan {
242
+ const suppressed = new Map([...filesByRelPath].filter(([, text]) => hasPluginSuppression(text)));
243
+ if (suppressed.size === 0) return { findings: {}, failures: [] };
244
+ const presetPath = resolvePresetPath(repoRoot);
245
+ const biomeBin = resolveBiomeBin(repoRoot);
246
+ if (presetPath === undefined || biomeBin === undefined) {
247
+ return {
248
+ findings: {},
249
+ failures: [
250
+ `cannot resolve Biome preset/binary from ${repoRoot} to check plugin suppressions`,
251
+ ],
252
+ };
253
+ }
254
+ const plugins = securityPluginEntries(presetPath);
255
+ if (typeof plugins === "string") return { findings: {}, failures: [plugins] };
256
+
257
+ const tempDir = mkdtempSync(path.join(tmpdir(), "kumiko-security-plugin-suppression-"));
258
+ try {
259
+ for (const [rel, text] of suppressed) {
260
+ const target = path.join(tempDir, rel);
261
+ mkdirSync(path.dirname(target), { recursive: true });
262
+ writeFileSync(target, neutralizePluginSuppressions(text));
263
+ }
264
+ const result = runBiomeInTempRepo(biomeBin, tempDir, plugins);
265
+ if ("failure" in result) return { findings: {}, failures: [result.failure] };
266
+ const findings: Record<string, PluginFinding> = {};
267
+ for (const diagnostic of result.diagnostics) {
268
+ if (diagnostic.path === undefined) continue;
269
+ const previous = findings[diagnostic.path];
270
+ findings[diagnostic.path] = {
271
+ count: (previous?.count ?? 0) + 1,
272
+ firstLine: previous?.firstLine ?? diagnostic.line,
273
+ };
274
+ }
275
+ return { findings, failures: [] };
276
+ } catch (error) {
277
+ return {
278
+ findings: {},
279
+ failures: [
280
+ `security plugin scan crashed: ${error instanceof Error ? error.message : String(error)}`,
281
+ ],
282
+ };
283
+ } finally {
284
+ rmSync(tempDir, { recursive: true, force: true });
285
+ }
286
+ }
287
+
288
+ function scanRepo(
289
+ files: readonly SourceFile[],
290
+ roots: readonly RepoRoot[],
291
+ ): { counts: Record<string, number>; firstLine: Record<string, number>; failures: string[] } {
292
+ const byRoot = new Map<string, Map<string, string>>();
293
+ for (const sf of files) {
294
+ const filePath = sf.getFilePath();
295
+ if (EXCLUDE.test(filePath)) continue;
296
+ const root = findRepoRootFor(filePath, roots);
297
+ if (root === undefined) continue;
298
+ const rel = relFromRepoRoot(filePath, roots);
299
+ if (!isLocalFinding({ file: rel })) continue;
300
+ const bucket = byRoot.get(root.absPath) ?? new Map<string, string>();
301
+ bucket.set(rel, sf.getFullText());
302
+ byRoot.set(root.absPath, bucket);
303
+ }
304
+ const counts: Record<string, number> = {};
305
+ const firstLine: Record<string, number> = {};
306
+ const failures: string[] = [];
307
+ for (const [repoRoot, bucket] of byRoot) {
308
+ const scan = scanSecurityPluginSuppressions(repoRoot, bucket);
309
+ failures.push(...scan.failures);
310
+ for (const [file, finding] of Object.entries(scan.findings)) {
311
+ counts[file] = finding.count;
312
+ firstLine[file] = finding.firstLine;
313
+ }
314
+ }
315
+ return { counts, firstLine, failures };
316
+ }
317
+
318
+ function suppressionBaselineFor(baselineRoot: string) {
319
+ return baselineRatchet({
320
+ file: path.join(baselineRoot, ".kumiko-security-plugin-suppression-baseline.json"),
321
+ formatVersion: 1,
322
+ unit: "suppressed security plugin finding(s)",
323
+ failClosed: true,
324
+ });
325
+ }
326
+
327
+ const REMEDIATION =
328
+ "A biome-ignore on lint/plugin cannot silence the security plugins (egress/SSRF, direct fs, event-store writes, admin API). Fix the call: egress(policy), FileStorageProvider, the event-store API. An unavoidable exception needs a reviewed baseline entry.";
329
+
330
+ export function createGuard(options: { readonly baselineRoot?: string } = {}): AstGuard {
331
+ const suppressionBaseline = suppressionBaselineFor(options.baselineRoot ?? ROOT);
332
+ return {
333
+ name: GUARD_NAME,
334
+ scan: SCAN,
335
+ hint: `reviewed exceptions only: \`kumiko-guards guards --write-baseline --guard=${GUARD_NAME}\``,
336
+ run: (files, roots = resolveRepoRoots()) => {
337
+ const { counts, firstLine, failures } = scanRepo(files, roots);
338
+ const failureViolations: GuardViolation[] = failures.map((message) => ({
339
+ file: ".",
340
+ line: 1,
341
+ message: `security plugin scan failed closed: ${message}`,
342
+ }));
343
+ return {
344
+ violations: [
345
+ ...failureViolations,
346
+ ...suppressionBaseline.check(counts, REMEDIATION, {
347
+ formatDriftRemediation: `Run \`kumiko-guards guards --write-baseline --guard=${GUARD_NAME}\` once.`,
348
+ resolveLine: (file) => firstLine[file] ?? 1,
349
+ }),
350
+ ],
351
+ };
352
+ },
353
+ writeBaseline: (files, roots = resolveRepoRoots()) => {
354
+ suppressionBaseline.write(scanRepo(files, roots).counts);
355
+ },
356
+ };
357
+ }
358
+
359
+ export const guard: AstGuard = createGuard();
360
+
361
+ if (import.meta.main) {
362
+ if (process.argv.slice(2).includes("--write-baseline")) {
363
+ const project = buildSharedProject([guard]);
364
+ guard.writeBaseline?.(filesForGuard(project, guard));
365
+ process.exit(0);
366
+ }
367
+ runStandalone(guard);
368
+ }
package/src/run-guards.ts CHANGED
@@ -38,6 +38,7 @@ import { guard as libTestCoverage } from "./guard-lib-test-coverage";
38
38
  import { guard as noLogicInViews } from "./guard-no-logic-in-views";
39
39
  import { guard as rlsSessionSettings } from "./guard-rls-session-settings";
40
40
  import { guard as screenConventions } from "./guard-screen-conventions";
41
+ import { guard as securityPluginSuppression } from "./guard-security-plugin-suppression";
41
42
  import { guard as tenantEscalation } from "./guard-tenant-escalation";
42
43
  import { guard as testEsRowWrites } from "./guard-test-es-row-writes";
43
44
  import { guard as testTemplateDrift } from "./guard-test-template-drift";
@@ -68,6 +69,7 @@ export const GUARDS = [
68
69
  fileSize,
69
70
  commentIssueRefOnly,
70
71
  ignoreTagReason,
72
+ securityPluginSuppression,
71
73
  ];
72
74
 
73
75
  export const GUARD_FLAGS = [