@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.
- package/README.md +15 -9
- package/package.json +4 -4
- package/src/_lib/agent-docs-api-nodes.ts +9 -2
- package/src/_lib/agent-docs-api-render.ts +31 -10
- package/src/_lib/agent-docs-api.ts +13 -9
- package/src/_lib/agent-docs-feature-imports.ts +12 -1
- package/src/_lib/baseline-compare.ts +1 -2
- package/src/_lib/doc-status.ts +8 -4
- package/src/_lib/dockerfile.ts +28 -5
- package/src/_lib/escaped-literal.ts +26 -0
- package/src/_lib/npm-registry.ts +2 -2
- package/src/_lib/run-slots.ts +4 -6
- package/src/_lib/security-audit.ts +22 -6
- package/src/_lib/test-es-raw-writes.ts +5 -3
- package/src/changes.json +44 -0
- package/src/check-security.ts +4 -3
- package/src/guard-app-dockerfile.ts +29 -12
- package/src/guard-ignore-tag-reason.ts +18 -4
- package/src/guard-internal-subpath-imports.ts +35 -25
- package/src/guard-rls-session-settings.ts +48 -6
- package/src/guard-schema-cli-features.ts +22 -1
- package/src/guard-test-es-row-writes.ts +2 -1
- package/src/guard-unsafe-array-param.ts +4 -7
- package/src/pre-push.sh +46 -6
- package/src/run-guards.ts +0 -28
- package/src/run-repo-checks.ts +0 -6
- package/src/run-steps-parallel.ts +4 -4
- package/src/run-ui-guards.ts +1 -15
- package/src/_lib/german-test-title.ts +0 -94
- package/src/_lib/primitives-access.ts +0 -23
- package/src/check-predicates.ts +0 -244
- package/src/guard-admin-api.ts +0 -138
- package/src/guard-direct-fetch.ts +0 -161
- package/src/guard-error-reasons.ts +0 -210
- package/src/guard-event-store-writes.ts +0 -124
- package/src/guard-i18n-locale-terminology.ts +0 -134
- package/src/guard-no-custom-primitives.ts +0 -193
- package/src/guard-no-date-api.ts +0 -183
- package/src/guard-no-direct-fs.ts +0 -346
- package/src/guard-no-direct-process-env.ts +0 -127
- package/src/guard-no-inline-styles.ts +0 -64
- package/src/guard-no-raw-hooks.ts +0 -80
- package/src/guard-no-temporal-polyfill-import.ts +0 -131
- package/src/guard-primitives-discipline.ts +0 -357
- package/src/guard-raw-classname.ts +0 -117
- package/src/guard-raw-interactive-elements.ts +0 -164
- package/src/guard-restricted-symbols.ts +0 -155
- package/src/guard-silent-skip.ts +0 -186
- package/src/guard-test-es-fixtures.ts +0 -85
- package/src/guard-test-title.ts +0 -159
- package/src/guard-thin-wrappers.ts +0 -471
- package/src/guard-unsafe-json-parse.ts +0 -87
package/src/guard-no-date-api.ts
DELETED
|
@@ -1,183 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env bun
|
|
2
|
-
/**
|
|
3
|
-
* Guard: finds Date-API patterns in production code where they are banned.
|
|
4
|
-
*
|
|
5
|
-
* Checked patterns (all Date-specific, Temporal has its own equivalents):
|
|
6
|
-
* - `new Date(...)` → Temporal.Now.instant() / Temporal.Instant.from
|
|
7
|
-
* - `.toISOString()` → Temporal.Instant.toString() (canonical ISO)
|
|
8
|
-
* - `.getTime()` → Temporal.Instant.epochMilliseconds
|
|
9
|
-
*
|
|
10
|
-
* `Date.now()` and `Date.parse()` are NOT checked — Date.now() is the
|
|
11
|
-
* idiomatic way to measure a duration (`Date.now() - startedAt`), and
|
|
12
|
-
* Temporal.Now.instant().epochMilliseconds is 4x longer for no benefit.
|
|
13
|
-
*
|
|
14
|
-
* Background: kumiko has a Temporal-based time API via `ctx.tz`. Feature
|
|
15
|
-
* code should use wall-clock + IANA-TZ via ctx.tz.parse / ctx.tz.now /
|
|
16
|
-
* ctx.tz.fromLocatedJson, NOT `new Date(...)` directly — that's the JS-Date
|
|
17
|
-
* trap (implicit local-TZ conversion in the browser, Hermes lacked
|
|
18
|
-
* Temporal for a long time, etc.). Sprint F carried this through
|
|
19
|
-
* atomically.
|
|
20
|
-
*
|
|
21
|
-
* Allowlist: paths that legitimately need the Date API (HTTP header specs,
|
|
22
|
-
* polyfill detection, Date↔Temporal bridges, JSON wire-format backwards
|
|
23
|
-
* compat). Test files are generally allowed.
|
|
24
|
-
*
|
|
25
|
-
* Usage:
|
|
26
|
-
* bun guards/guard-no-date-api.ts
|
|
27
|
-
*
|
|
28
|
-
* Exit 1 on violations in non-allowlisted files, 0 when clean.
|
|
29
|
-
*/
|
|
30
|
-
|
|
31
|
-
import * as path from "node:path";
|
|
32
|
-
import { type SourceFile, SyntaxKind } from "ts-morph";
|
|
33
|
-
import { type AstGuard, runStandalone, type ScanSpec } from "./_lib/guard-kit";
|
|
34
|
-
|
|
35
|
-
const ROOT = process.cwd();
|
|
36
|
-
|
|
37
|
-
const SCAN: ScanSpec = {
|
|
38
|
-
scope: "source",
|
|
39
|
-
extensions: ["ts"],
|
|
40
|
-
frameworkWithin: ["packages/*/src/**", "samples/**"],
|
|
41
|
-
};
|
|
42
|
-
|
|
43
|
-
// Files that are NOT checked — tests, type defs, generated code.
|
|
44
|
-
const EXCLUDE = /(__tests__|\.test\.ts$|\.integration\.ts$|\.d\.ts$|\.g\.ts$)/;
|
|
45
|
-
|
|
46
|
-
// Framework internals are still allowed to `new Date()`: they implement the
|
|
47
|
-
// TZ layer themselves or hang off the DB driver where Date is the native
|
|
48
|
-
// wire format. Migration plan: paths get removed from this allowlist per
|
|
49
|
-
// feature/sample as they migrate to ctx.tz. Goal: the allowlist shrinks.
|
|
50
|
-
const ALLOWLIST = [
|
|
51
|
-
// Framework time layer itself
|
|
52
|
-
/packages\/framework\/src\/time\//,
|
|
53
|
-
// DB layer: drizzle column wrapper, migration tooling — Date is a
|
|
54
|
-
// primitive wire format there
|
|
55
|
-
/packages\/framework\/src\/db\//,
|
|
56
|
-
// Event-store internals: createdAt stamps, snapshot time, archive time
|
|
57
|
-
/packages\/framework\/src\/event-store\//,
|
|
58
|
-
// Pipeline: system hooks, idempotency cache (low-level timestamps)
|
|
59
|
-
/packages\/framework\/src\/pipeline\//,
|
|
60
|
-
// Errors: timestamp in the error body
|
|
61
|
-
/packages\/framework\/src\/errors\//,
|
|
62
|
-
// Jobs: job-run timestamps (the job runner is a time source for cron)
|
|
63
|
-
/packages\/framework\/src\/jobs\//,
|
|
64
|
-
// API layer: request timestamps in logs
|
|
65
|
-
/packages\/framework\/src\/api\//,
|
|
66
|
-
// Logging
|
|
67
|
-
/packages\/framework\/src\/logging\//,
|
|
68
|
-
// i18n
|
|
69
|
-
/packages\/framework\/src\/i18n\//,
|
|
70
|
-
// Observability
|
|
71
|
-
/packages\/framework\/src\/observability\//,
|
|
72
|
-
// Engine internals (factories, registry, config) — when they need Date
|
|
73
|
-
// it's defaults/audit stamps working together with the DB layer.
|
|
74
|
-
/packages\/framework\/src\/engine\/(types|registry|config-helpers|create-app|define-feature|state-machine|access|field-access|boot-validator|qualified-name)\.ts$/,
|
|
75
|
-
// Testing helpers
|
|
76
|
-
/packages\/testing\/src\/helpers\//,
|
|
77
|
-
// Search adapter internals
|
|
78
|
-
/packages\/framework\/src\/search\//,
|
|
79
|
-
// File storage (coming in Gap-04)
|
|
80
|
-
/packages\/framework\/src\/files\//,
|
|
81
|
-
|
|
82
|
-
// Sprint F's atomic switch migrated bundled-features + samples to
|
|
83
|
-
// Temporal.Now.instant() — no blanket allowlist anymore. Beammycar's
|
|
84
|
-
// migration reads legacy-DB Date columns (V2 schema, no Temporal): the
|
|
85
|
-
// `pg` driver rows arrive as JS `Date`, the `dateToInstant` helper
|
|
86
|
-
// bridges them to `Temporal.Instant` via `.getTime()`. A pure bridge
|
|
87
|
-
// layer.
|
|
88
|
-
/samples\/showcases\/beammycar\/src\/migration\//,
|
|
89
|
-
|
|
90
|
-
// === Legitimate Date-API spots ===
|
|
91
|
-
// Polyfill detection: typeof globalThis.Temporal vs new Date(0) — no
|
|
92
|
-
// Temporal available because we're checking if it's there right now.
|
|
93
|
-
/packages\/framework\/src\/time\/polyfill\.ts$/,
|
|
94
|
-
// HTTP Date headers (RFC 7231): Last-Modified / Expires / signed-URL
|
|
95
|
-
// expiresAt are Date-typed in the HTTP spec, not a Temporal format.
|
|
96
|
-
/packages\/framework\/src\/files\/file-routes\.ts$/,
|
|
97
|
-
// Error serialization: timestamp in the JSON wire body for backwards
|
|
98
|
-
// compat with every client that has expected an ISO string since Sprint A.
|
|
99
|
-
/packages\/framework\/src\/errors\/serialize\.ts$/,
|
|
100
|
-
// Entity cache: parsing arbitrary input (could be Date or ISO string),
|
|
101
|
-
// Number.isNaN(d.getTime()) as a validity check.
|
|
102
|
-
/packages\/framework\/src\/pipeline\/entity-cache\.ts$/,
|
|
103
|
-
// Event-store insertSubsequentEvent: raw SQL row.created_at can be Date|string
|
|
104
|
-
// (driver-config dependent), normalised to Temporal.Instant via
|
|
105
|
-
// .getTime() bridge.
|
|
106
|
-
/packages\/framework\/src\/event-store\/event-store\.ts$/,
|
|
107
|
-
// HTTP Last-Modified/ETag header: Bun/Node Response API expects a native
|
|
108
|
-
// Date object from fs.Stats.mtimeMs — wire boundary, not a Temporal format.
|
|
109
|
-
/packages\/server-runtime\/src\/run-prod-app-static-files\.ts$/,
|
|
110
|
-
// timestamptz columns arrive as native Date (driver wire format,
|
|
111
|
-
// same reason as packages/framework/src/db/ above).
|
|
112
|
-
/packages\/publish\/src\/rollback\.ts$/,
|
|
113
|
-
];
|
|
114
|
-
|
|
115
|
-
interface Violation {
|
|
116
|
-
file: string;
|
|
117
|
-
line: number;
|
|
118
|
-
snippet: string;
|
|
119
|
-
pattern: "new Date" | ".toISOString" | ".getTime";
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
function isAllowlisted(filePath: string): boolean {
|
|
123
|
-
const rel = path.relative(ROOT, filePath);
|
|
124
|
-
return ALLOWLIST.some((re) => re.test(rel));
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
function findDateApiUsages(sf: SourceFile): Omit<Violation, "file">[] {
|
|
128
|
-
const result: Omit<Violation, "file">[] = [];
|
|
129
|
-
|
|
130
|
-
// Pattern 1: `new Date(...)`
|
|
131
|
-
for (const expr of sf.getDescendantsOfKind(SyntaxKind.NewExpression)) {
|
|
132
|
-
if (expr.getExpression().getText() === "Date") {
|
|
133
|
-
result.push({
|
|
134
|
-
line: expr.getStartLineNumber(),
|
|
135
|
-
snippet: expr.getText(),
|
|
136
|
-
pattern: "new Date",
|
|
137
|
-
});
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
// Pattern 2: `.toISOString()` and `.getTime()` — property access in a call.
|
|
142
|
-
// Temporal.Instant has neither method, so any hit is a Date-API call.
|
|
143
|
-
for (const expr of sf.getDescendantsOfKind(SyntaxKind.CallExpression)) {
|
|
144
|
-
const callee = expr.getExpression();
|
|
145
|
-
if (callee.getKind() !== SyntaxKind.PropertyAccessExpression) continue;
|
|
146
|
-
const name = callee.asKindOrThrow(SyntaxKind.PropertyAccessExpression).getName();
|
|
147
|
-
if (name === "toISOString" || name === "getTime") {
|
|
148
|
-
result.push({
|
|
149
|
-
line: expr.getStartLineNumber(),
|
|
150
|
-
snippet: expr.getText(),
|
|
151
|
-
pattern: name === "toISOString" ? ".toISOString" : ".getTime",
|
|
152
|
-
});
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
return result;
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
export const guard: AstGuard = {
|
|
160
|
-
name: "No-Date-API Guard",
|
|
161
|
-
scan: SCAN,
|
|
162
|
-
hint: "Replace with Temporal.Now.instant() / Temporal.Instant.from / .toString() / .epochMilliseconds — see docs/plans/architecture/timezones.md.",
|
|
163
|
-
run(files) {
|
|
164
|
-
const violations: Array<{ file: string; line: number; message: string }> = [];
|
|
165
|
-
|
|
166
|
-
for (const sf of files) {
|
|
167
|
-
const file = sf.getFilePath();
|
|
168
|
-
if (EXCLUDE.test(file)) continue;
|
|
169
|
-
if (isAllowlisted(file)) continue;
|
|
170
|
-
for (const usage of findDateApiUsages(sf)) {
|
|
171
|
-
violations.push({
|
|
172
|
-
file: path.relative(ROOT, file),
|
|
173
|
-
line: usage.line,
|
|
174
|
-
message: `[${usage.pattern}] ${usage.snippet}`,
|
|
175
|
-
});
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
return { violations };
|
|
180
|
-
},
|
|
181
|
-
};
|
|
182
|
-
|
|
183
|
-
if (import.meta.main) runStandalone(guard);
|
|
@@ -1,346 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env bun
|
|
2
|
-
/**
|
|
3
|
-
* Guard: finds direct `node:fs`/`fs` imports outside an allowlist.
|
|
4
|
-
*
|
|
5
|
-
* Background: several path-traversal bugs happened because request-input
|
|
6
|
-
* paths were passed straight to `node:fs` instead of through the one
|
|
7
|
-
* guarded place (`packages/framework/src/files/local-provider.ts` —
|
|
8
|
-
* `resolveContainedPath()` resolves against `basePath` and rejects anything
|
|
9
|
-
* outside it). New runtime code should use `FileStorageProvider` instead of
|
|
10
|
-
* wiring up `fs` itself again.
|
|
11
|
-
*
|
|
12
|
-
* Scans every packages/<pkg>/src directory (each root, like guard-no-date-api
|
|
13
|
-
* / guard-restricted-symbols) — the traversal risk isn't limited to one repo.
|
|
14
|
-
* Build/CLI/script/e2e tooling is filtered out via an EXCLUDE directory
|
|
15
|
-
* pattern rather than a file-by-file allowlist; everything else under src
|
|
16
|
-
* stays checked, including in app repos (e.g. marketing render jobs).
|
|
17
|
-
*
|
|
18
|
-
* Allowlist entries are repo-scoped (repo name or "*") so a path justified in
|
|
19
|
-
* one repo cannot silently free node:fs in another under the same relative
|
|
20
|
-
* path.
|
|
21
|
-
*
|
|
22
|
-
* Repo-local exception for a justified import (tooling, build-time reads):
|
|
23
|
-
* // kumiko-lint-ignore direct-fs <reason>
|
|
24
|
-
* on the import line or the line directly above. A bare tag without a reason
|
|
25
|
-
* does not count. The marker suppresses only while its `<file>::<reason>` pair
|
|
26
|
-
* is frozen in `.kumiko-direct-fs-baseline.json` at the repo root — fail-closed:
|
|
27
|
-
* no file, an unreadable file, a changed reason or more markers than frozen
|
|
28
|
-
* all make the guard fail. Freeze with:
|
|
29
|
-
* kumiko-guards guards --write-baseline --guard="No-Direct-Fs Guard"
|
|
30
|
-
*
|
|
31
|
-
* Usage:
|
|
32
|
-
* bun guards/guard-no-direct-fs.ts
|
|
33
|
-
*
|
|
34
|
-
* Exit 1 on violations in non-allowlisted files, 0 when clean.
|
|
35
|
-
*/
|
|
36
|
-
|
|
37
|
-
import { existsSync } from "node:fs";
|
|
38
|
-
import { join, relative as pathRelative } from "node:path";
|
|
39
|
-
import { Node, type SourceFile, SyntaxKind } from "ts-morph";
|
|
40
|
-
import {
|
|
41
|
-
ALL_REPO_KINDS,
|
|
42
|
-
type AstGuard,
|
|
43
|
-
baselineRatchet,
|
|
44
|
-
findRepoRootFor,
|
|
45
|
-
type GuardViolation,
|
|
46
|
-
relFromRepoRoot,
|
|
47
|
-
runStandalone,
|
|
48
|
-
type ScanSpec,
|
|
49
|
-
} from "./_lib/guard-kit";
|
|
50
|
-
import { type RepoRoot, resolveRepoRoots } from "./_lib/roots";
|
|
51
|
-
|
|
52
|
-
const SCAN: ScanSpec = {
|
|
53
|
-
kinds: ALL_REPO_KINDS,
|
|
54
|
-
scope: "source",
|
|
55
|
-
extensions: ["ts"],
|
|
56
|
-
frameworkWithin: ["packages/*/src/**", "samples/**"],
|
|
57
|
-
};
|
|
58
|
-
|
|
59
|
-
// Tests + build/CLI/script/e2e tooling: no request input as a path.
|
|
60
|
-
// (^|/) so relative paths like `tools/docgen/...` match — a leading-slash-
|
|
61
|
-
// only pattern only worked when relFromRepoRoot fell back to absolute paths.
|
|
62
|
-
const EXCLUDE =
|
|
63
|
-
/(__tests__|\.test\.ts$|\.integration\.ts$|\.spec\.ts$|\.d\.ts$|(^|\/)(scripts|e2e|tools|bin)\/)/;
|
|
64
|
-
|
|
65
|
-
const FS_MODULES = new Set(["fs", "node:fs", "fs/promises", "node:fs/promises"]);
|
|
66
|
-
|
|
67
|
-
// Closed union (not `string | "*"`, which collapses to `string`): a typo in an
|
|
68
|
-
// allowlist repo name must fail to compile instead of silently never matching.
|
|
69
|
-
export type AllowlistRepoName = "kumiko-framework" | "kumiko-enterprise";
|
|
70
|
-
|
|
71
|
-
export type AllowEntry = {
|
|
72
|
-
readonly repo: AllowlistRepoName | "*";
|
|
73
|
-
readonly pattern: RegExp;
|
|
74
|
-
};
|
|
75
|
-
|
|
76
|
-
const ALLOWLIST: readonly AllowEntry[] = [
|
|
77
|
-
// The one guarded place: path-traversal check via resolveContainedPath().
|
|
78
|
-
{ repo: "kumiko-framework", pattern: /^packages\/framework\/src\/files\/local-provider\.ts$/ },
|
|
79
|
-
|
|
80
|
-
// Dev-server: CLI/scaffolding/codegen, runs locally on the developer's
|
|
81
|
-
// machine, no request input as a path.
|
|
82
|
-
{ repo: "kumiko-framework", pattern: /^packages\/dev-server\/src\// },
|
|
83
|
-
|
|
84
|
-
// Guard runner + repo-manifest loader: read the scanned repo tree at dev/CI time, no request input as path.
|
|
85
|
-
{ repo: "kumiko-framework", pattern: /^packages\/guards\/src\// },
|
|
86
|
-
|
|
87
|
-
// CLI (@cosmicdrift/kumiko-cli): local dev/CI tooling reading the repo tree, no request input as path.
|
|
88
|
-
{ repo: "kumiko-framework", pattern: /^packages\/cli\/src\// },
|
|
89
|
-
|
|
90
|
-
// Framework: migrations/schema tooling, DB codegen, boot validator —
|
|
91
|
-
// CLI/build time, no request input.
|
|
92
|
-
{ repo: "kumiko-framework", pattern: /^packages\/framework\/src\/migrations\/kumiko-drift\.ts$/ },
|
|
93
|
-
{ repo: "kumiko-framework", pattern: /^packages\/framework\/src\/schema-cli(\.ts|\/[^/]+\.ts)$/ },
|
|
94
|
-
// same CLI-tooling pattern as schema-cli.ts — repo-tree/node_modules walking for the upgrade command, not app-level file storage
|
|
95
|
-
{ repo: "kumiko-framework", pattern: /^packages\/framework\/src\/upgrade-cli(-internals)?\.ts$/ },
|
|
96
|
-
{ repo: "kumiko-framework", pattern: /^packages\/framework\/src\/es-ops\/runner\.ts$/ },
|
|
97
|
-
{ repo: "kumiko-framework", pattern: /^packages\/framework\/src\/db\/migrate-generator\.ts$/ },
|
|
98
|
-
{ repo: "kumiko-framework", pattern: /^packages\/framework\/src\/db\/migrate-runner\.ts$/ },
|
|
99
|
-
{ repo: "kumiko-framework", pattern: /^packages\/framework\/src\/db\/rebuild-marker\.ts$/ },
|
|
100
|
-
{
|
|
101
|
-
repo: "kumiko-framework",
|
|
102
|
-
pattern: /^packages\/framework\/src\/engine\/boot-validator\/custom-screen-write-qns\.ts$/,
|
|
103
|
-
},
|
|
104
|
-
{
|
|
105
|
-
repo: "kumiko-framework",
|
|
106
|
-
pattern: /^packages\/feature-ast\/src\/codemod\/pipeline-codemod\.ts$/,
|
|
107
|
-
},
|
|
108
|
-
|
|
109
|
-
// server-runtime: prod bundle build + static asset delivery from the
|
|
110
|
-
// build output (no user-controlled path). bundled-assets.ts reads declared
|
|
111
|
-
// read-only assets, name-pattern + containment checked.
|
|
112
|
-
{ repo: "kumiko-framework", pattern: /^packages\/server-runtime\/src\/build-prod-bundle\.ts$/ },
|
|
113
|
-
{ repo: "kumiko-framework", pattern: /^packages\/server-runtime\/src\/bundled-assets\.ts$/ },
|
|
114
|
-
{
|
|
115
|
-
repo: "kumiko-framework",
|
|
116
|
-
pattern: /^packages\/server-runtime\/src\/run-prod-app-static-files\.ts$/,
|
|
117
|
-
},
|
|
118
|
-
// Writes app build output (static HTML pages) under the caller's outDir; page paths are traversal-checked.
|
|
119
|
-
{ repo: "kumiko-framework", pattern: /^packages\/server-runtime\/src\/static-html-pages\.ts$/ },
|
|
120
|
-
// Package lookup for the build and the dev server: existence check for
|
|
121
|
-
// node_modules/<pkg>/package.json above a directory, no request input as a path.
|
|
122
|
-
{
|
|
123
|
-
repo: "kumiko-framework",
|
|
124
|
-
pattern: /^packages\/server-runtime\/src\/resolve-installed-package\.ts$/,
|
|
125
|
-
},
|
|
126
|
-
|
|
127
|
-
// create-kumiko-app: Scaffolding-CLI.
|
|
128
|
-
{ repo: "kumiko-framework", pattern: /^packages\/create-kumiko-app\/src\/manifest\.ts$/ },
|
|
129
|
-
|
|
130
|
-
// Sample apps: codegen/screenshot-mount helper, no request input.
|
|
131
|
-
{
|
|
132
|
-
repo: "kumiko-framework",
|
|
133
|
-
pattern: /^samples\/apps\/showcase\/src\/app\/mount-public-screenshots\.ts$/,
|
|
134
|
-
},
|
|
135
|
-
|
|
136
|
-
// kumiko-enterprise: ai-cli reads/writes locally on the developer's
|
|
137
|
-
// machine (--api-key/KUMIKO_CORPUS_PATH), no server request path.
|
|
138
|
-
{ repo: "kumiko-enterprise", pattern: /^packages\/ai-cli\/src\/index\.ts$/ },
|
|
139
|
-
// Few-shot corpus loader: reads docs/few-shot-corpus.json via an upward
|
|
140
|
-
// walk from cwd, no user input as a path.
|
|
141
|
-
{ repo: "kumiko-enterprise", pattern: /^packages\/ai-foundation\/src\/prompt\/corpus\.ts$/ },
|
|
142
|
-
|
|
143
|
-
// kumiko-enterprise publish pipeline: materialize.ts is the guarded
|
|
144
|
-
// place (writeMaterializedTree — resolve()+startsWith(root+sep) check,
|
|
145
|
-
// same pattern as local-provider.ts). build.ts/feature.ts/validate.ts
|
|
146
|
-
// now only touch fs for tempdir housekeeping (mkdtemp/rm, fixed
|
|
147
|
-
// suffixes) and a static package.json upwalk — no user path, no direct
|
|
148
|
-
// write anymore.
|
|
149
|
-
{ repo: "kumiko-enterprise", pattern: /^packages\/publish\/src\/materialize\.ts$/ },
|
|
150
|
-
{ repo: "kumiko-enterprise", pattern: /^packages\/publish\/src\/build\.ts$/ },
|
|
151
|
-
{ repo: "kumiko-enterprise", pattern: /^packages\/publish\/src\/feature\.ts$/ },
|
|
152
|
-
{ repo: "kumiko-enterprise", pattern: /^packages\/publish\/src\/validate\.ts$/ },
|
|
153
|
-
|
|
154
|
-
// testing: `kumiko-testing integration` CLI resolves positional test-file
|
|
155
|
-
// args against the developer's cwd, local dev/CI tooling reading paths
|
|
156
|
-
// the developer typed — no server request input.
|
|
157
|
-
{ repo: "kumiko-framework", pattern: /^packages\/testing\/src\/integration-runner\.ts$/ },
|
|
158
|
-
];
|
|
159
|
-
|
|
160
|
-
export function isRepoAllowlisted(
|
|
161
|
-
repoName: string | undefined,
|
|
162
|
-
relPath: string,
|
|
163
|
-
allowlist: readonly AllowEntry[] = ALLOWLIST,
|
|
164
|
-
): boolean {
|
|
165
|
-
// Fail-closed without a resolved root: only "*" entries can match, so a
|
|
166
|
-
// synthetic in-memory path cannot hitch a ride on a framework/enterprise
|
|
167
|
-
// justification (same hole guard-direct-fetch closed).
|
|
168
|
-
return allowlist.some(
|
|
169
|
-
(e) =>
|
|
170
|
-
(e.repo === "*" || (repoName !== undefined && e.repo === repoName)) &&
|
|
171
|
-
e.pattern.test(relPath),
|
|
172
|
-
);
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
interface Violation {
|
|
176
|
-
line: number;
|
|
177
|
-
moduleSpecifier: string;
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
const BASELINE_FILE = ".kumiko-direct-fs-baseline.json";
|
|
181
|
-
// Must sit in a // comment, so a string literal describing the marker does not suppress.
|
|
182
|
-
const MARKER_WITH_REASON_RE = /(^|\s)\/\/\s*kumiko-lint-ignore direct-fs\s+(\S.*)$/;
|
|
183
|
-
|
|
184
|
-
const MARKER_REMEDIATION =
|
|
185
|
-
"New, reworded or unfrozen direct-fs marker. Prefer FileStorageProvider or readBundledAsset; " +
|
|
186
|
-
'otherwise freeze the exception with `kumiko-guards guards --write-baseline --guard="No-Direct-Fs Guard"` ' +
|
|
187
|
-
"so the baseline diff shows up in review.";
|
|
188
|
-
|
|
189
|
-
type RootMarkers = {
|
|
190
|
-
readonly root: RepoRoot;
|
|
191
|
-
/** `<file>::<reason>` -> distinct marker lines (1-based). */
|
|
192
|
-
readonly linesByKey: Map<string, Set<number>>;
|
|
193
|
-
};
|
|
194
|
-
|
|
195
|
-
function ratchetFor(root: RepoRoot) {
|
|
196
|
-
return baselineRatchet({
|
|
197
|
-
file: join(root.absPath, BASELINE_FILE),
|
|
198
|
-
formatVersion: 1,
|
|
199
|
-
unit: "direct-fs marker(s)",
|
|
200
|
-
failClosed: true,
|
|
201
|
-
});
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
function markerFor(
|
|
205
|
-
lines: readonly string[],
|
|
206
|
-
importLine: number,
|
|
207
|
-
): { readonly reason: string; readonly line: number } | undefined {
|
|
208
|
-
const sameLine = MARKER_WITH_REASON_RE.exec(lines[importLine - 1] ?? "")?.[2];
|
|
209
|
-
if (sameLine !== undefined) return { reason: sameLine.trim(), line: importLine };
|
|
210
|
-
const above = MARKER_WITH_REASON_RE.exec(lines[importLine - 2] ?? "")?.[2];
|
|
211
|
-
return above === undefined ? undefined : { reason: above.trim(), line: importLine - 1 };
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
function countsOf(markers: RootMarkers): Record<string, number> {
|
|
215
|
-
return Object.fromEntries([...markers.linesByKey].map(([key, lines]) => [key, lines.size]));
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
function collect(
|
|
219
|
-
files: readonly SourceFile[],
|
|
220
|
-
roots: readonly RepoRoot[],
|
|
221
|
-
): { readonly unsuppressed: GuardViolation[]; readonly markers: Map<string, RootMarkers> } {
|
|
222
|
-
const unsuppressed: GuardViolation[] = [];
|
|
223
|
-
const markers = new Map<string, RootMarkers>();
|
|
224
|
-
|
|
225
|
-
for (const sf of files) {
|
|
226
|
-
const file = sf.getFilePath();
|
|
227
|
-
const rel = relFromRepoRoot(file, roots);
|
|
228
|
-
if (EXCLUDE.test(rel)) continue;
|
|
229
|
-
const root = findRepoRootFor(file, roots);
|
|
230
|
-
if (isRepoAllowlisted(root?.name, rel)) continue;
|
|
231
|
-
const lines = sf.getFullText().split("\n");
|
|
232
|
-
for (const v of findDirectFsImports(sf)) {
|
|
233
|
-
const marker = root === undefined ? undefined : markerFor(lines, v.line);
|
|
234
|
-
if (root !== undefined && marker !== undefined) {
|
|
235
|
-
const entry = markers.get(root.absPath) ?? { root, linesByKey: new Map() };
|
|
236
|
-
const key = `${rel}::${marker.reason}`;
|
|
237
|
-
const set = entry.linesByKey.get(key) ?? new Set<number>();
|
|
238
|
-
set.add(marker.line);
|
|
239
|
-
entry.linesByKey.set(key, set);
|
|
240
|
-
markers.set(root.absPath, entry);
|
|
241
|
-
continue;
|
|
242
|
-
}
|
|
243
|
-
unsuppressed.push({
|
|
244
|
-
// cwd-relative, not repo-relative `rel` — the security baseline
|
|
245
|
-
// needs an unambiguous path to resolve back to (repo, relPath).
|
|
246
|
-
file: pathRelative(process.cwd(), file),
|
|
247
|
-
line: v.line,
|
|
248
|
-
message: `[${v.moduleSpecifier}] direct fs import outside allowlist`,
|
|
249
|
-
});
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
return { unsuppressed, markers };
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
function markerViolations(markers: ReadonlyMap<string, RootMarkers>): GuardViolation[] {
|
|
256
|
-
return [...markers.values()].flatMap((m) =>
|
|
257
|
-
ratchetFor(m.root)
|
|
258
|
-
.check(countsOf(m), MARKER_REMEDIATION, {
|
|
259
|
-
resolveLine: (key) => [...(m.linesByKey.get(key) ?? [])].sort((a, b) => a - b)[0] ?? 1,
|
|
260
|
-
})
|
|
261
|
-
.map((v) => {
|
|
262
|
-
const [relFile] = v.file.split("::");
|
|
263
|
-
const isMarkerKey = v.file.includes("::") && relFile !== undefined;
|
|
264
|
-
return {
|
|
265
|
-
...v,
|
|
266
|
-
file: isMarkerKey ? pathRelative(process.cwd(), join(m.root.absPath, relFile)) : v.file,
|
|
267
|
-
// A frozen security baseline must never excuse an unfrozen marker.
|
|
268
|
-
neverFrozen: true,
|
|
269
|
-
};
|
|
270
|
-
}),
|
|
271
|
-
);
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
function findDynamicFsRequires(sf: SourceFile): Violation[] {
|
|
275
|
-
const violations: Violation[] = [];
|
|
276
|
-
|
|
277
|
-
// Dynamic `import("fs")` and CommonJS `require("fs")` bypass the static
|
|
278
|
-
// import/export declarations — both are CallExpressions in the AST.
|
|
279
|
-
for (const call of sf.getDescendantsOfKind(SyntaxKind.CallExpression)) {
|
|
280
|
-
const callee = call.getExpression();
|
|
281
|
-
const isRequireCall =
|
|
282
|
-
callee.getKind() === SyntaxKind.Identifier && callee.getText() === "require";
|
|
283
|
-
const isDynamicImport = callee.getKind() === SyntaxKind.ImportKeyword;
|
|
284
|
-
if (!isRequireCall && !isDynamicImport) continue;
|
|
285
|
-
const arg = call.getArguments()[0];
|
|
286
|
-
if (arg && Node.isStringLiteral(arg) && FS_MODULES.has(arg.getLiteralValue())) {
|
|
287
|
-
violations.push({ line: call.getStartLineNumber(), moduleSpecifier: arg.getLiteralValue() });
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
return violations;
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
function findDirectFsImports(sf: SourceFile): Violation[] {
|
|
294
|
-
const violations: Violation[] = [];
|
|
295
|
-
|
|
296
|
-
for (const decl of sf.getImportDeclarations()) {
|
|
297
|
-
const spec = decl.getModuleSpecifierValue();
|
|
298
|
-
if (FS_MODULES.has(spec)) {
|
|
299
|
-
violations.push({ line: decl.getStartLineNumber(), moduleSpecifier: spec });
|
|
300
|
-
}
|
|
301
|
-
}
|
|
302
|
-
for (const decl of sf.getExportDeclarations()) {
|
|
303
|
-
const spec = decl.getModuleSpecifierValue();
|
|
304
|
-
if (spec && FS_MODULES.has(spec)) {
|
|
305
|
-
violations.push({ line: decl.getStartLineNumber(), moduleSpecifier: spec });
|
|
306
|
-
}
|
|
307
|
-
}
|
|
308
|
-
for (const importEqualsDecl of sf.getDescendantsOfKind(SyntaxKind.ImportEqualsDeclaration)) {
|
|
309
|
-
const ref = importEqualsDecl.getModuleReference();
|
|
310
|
-
if (!Node.isExternalModuleReference(ref)) continue;
|
|
311
|
-
const arg = ref.getExpression();
|
|
312
|
-
if (arg && Node.isStringLiteral(arg) && FS_MODULES.has(arg.getLiteralValue())) {
|
|
313
|
-
violations.push({
|
|
314
|
-
line: importEqualsDecl.getStartLineNumber(),
|
|
315
|
-
moduleSpecifier: arg.getLiteralValue(),
|
|
316
|
-
});
|
|
317
|
-
}
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
violations.push(...findDynamicFsRequires(sf));
|
|
321
|
-
|
|
322
|
-
return violations;
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
export const guard: AstGuard = {
|
|
326
|
-
name: "No-Direct-Fs Guard",
|
|
327
|
-
scan: SCAN,
|
|
328
|
-
security: true,
|
|
329
|
-
hint: 'Direct node:fs import outside the allowlist — use FileStorageProvider (packages/framework/src/files/) instead of wiring fs yourself; the path-traversal guard (resolveContainedPath) only exists there. Read-only files your own build ships: declare them under package.json `kumiko.assets` and use readBundledAsset(name) from @cosmicdrift/kumiko-server-runtime. Legitimate tooling exception: mark the import with `// kumiko-lint-ignore direct-fs <reason>` and freeze it with `kumiko-guards guards --write-baseline --guard="No-Direct-Fs Guard"` (.kumiko-direct-fs-baseline.json, reviewed as a diff).',
|
|
330
|
-
run(files, roots: readonly RepoRoot[] = resolveRepoRoots()) {
|
|
331
|
-
const { unsuppressed, markers } = collect(files, roots);
|
|
332
|
-
return { violations: [...unsuppressed, ...markerViolations(markers)] };
|
|
333
|
-
},
|
|
334
|
-
writeBaseline(files, roots: readonly RepoRoot[] = resolveRepoRoots()) {
|
|
335
|
-
const { markers } = collect(files, roots);
|
|
336
|
-
for (const m of markers.values()) ratchetFor(m.root).write(countsOf(m));
|
|
337
|
-
// A repo whose last marker is gone keeps a stale baseline unless it is shrunk too.
|
|
338
|
-
for (const root of roots) {
|
|
339
|
-
if (!markers.has(root.absPath) && existsSync(join(root.absPath, BASELINE_FILE))) {
|
|
340
|
-
ratchetFor(root).write({});
|
|
341
|
-
}
|
|
342
|
-
}
|
|
343
|
-
},
|
|
344
|
-
};
|
|
345
|
-
|
|
346
|
-
if (import.meta.main) runStandalone(guard);
|
|
@@ -1,127 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env bun
|
|
2
|
-
/**
|
|
3
|
-
* No-Direct-Process-Env Guard.
|
|
4
|
-
*
|
|
5
|
-
* Apps with composed env-schemas (`bin/env.ts`) must read runtime config from
|
|
6
|
-
* the validated `env` export — not scattered `process.env.X` in prod paths.
|
|
7
|
-
*
|
|
8
|
-
* Scans bin/main.ts, other bin ts files incl. subfolders such as bin/ops/ (excl. allowlist), and src (excl. tests)
|
|
9
|
-
* in every repo that ships `bin/env.ts`. Allowed raw process.env:
|
|
10
|
-
* - bin/env.ts — sole parseEnv input
|
|
11
|
-
* - bin/server.ts — dev entrypoint (runDevApp)
|
|
12
|
-
* - bin/kumiko.ts — schema/migrate CLI (DATABASE_URL, INIT_CWD)
|
|
13
|
-
*/
|
|
14
|
-
import { existsSync } from "node:fs";
|
|
15
|
-
import { join } from "node:path";
|
|
16
|
-
import { Glob } from "bun";
|
|
17
|
-
import { type RepoCheck, reportResults, runRepoChecks } from "./_lib/guard-kit";
|
|
18
|
-
import { type RepoRoot, resolveRepoRoots } from "./_lib/roots";
|
|
19
|
-
import { scanLinesForPredicate } from "./_lib/scan-lines";
|
|
20
|
-
|
|
21
|
-
// .tsx deliberately excluded — client screens have no runtime process.env
|
|
22
|
-
// access (bundler boundary), only .ts server/bin code reads process.env
|
|
23
|
-
// directly. Add .tsx here if that ever stops being true.
|
|
24
|
-
const SCAN_PATTERNS: ReadonlyArray<string> = ["bin/**/*.ts", "src/**/*.ts"];
|
|
25
|
-
|
|
26
|
-
/** bin ts paths that may read process.env directly (see header). */
|
|
27
|
-
export const ALLOWED_BIN_FILES: ReadonlySet<string> = new Set([
|
|
28
|
-
"bin/env.ts",
|
|
29
|
-
"bin/server.ts",
|
|
30
|
-
"bin/kumiko.ts",
|
|
31
|
-
]);
|
|
32
|
-
|
|
33
|
-
const EXCLUDE_DIR = /(?:^|\/)(?:node_modules|dist|__tests__)\//;
|
|
34
|
-
const IS_TEST = /\.(?:test|integration)\.tsx?$/;
|
|
35
|
-
|
|
36
|
-
// process.env.FOO | process.env.foo | process.env["FOO"] | process.env[`FOO`]
|
|
37
|
-
const PROCESS_ENV_REF = /process\.env(?:\.[A-Za-z_][A-Za-z0-9_]*|\[(?:'[^']+'|"[^"]+"|`[^`]+`)\])/;
|
|
38
|
-
|
|
39
|
-
export type ProcessEnvFinding = {
|
|
40
|
-
readonly file: string;
|
|
41
|
-
readonly line: number;
|
|
42
|
-
readonly text: string;
|
|
43
|
-
};
|
|
44
|
-
|
|
45
|
-
/** Returns true when the line contains a live process.env reference. */
|
|
46
|
-
export function processEnvOnLine(line: string): boolean {
|
|
47
|
-
// `(?<!:)` keeps `https://…` inside string literals from being cut as a comment.
|
|
48
|
-
const code = line.replace(/(?<!:)\/\/.*$/, "");
|
|
49
|
-
return PROCESS_ENV_REF.test(code);
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export function isScannableBinFile(rel: string): boolean {
|
|
53
|
-
return rel.startsWith("bin/") && rel.endsWith(".ts") && !ALLOWED_BIN_FILES.has(rel);
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
// Fail-scope deliberately covers every repo with bin/env.ts (rather than only
|
|
57
|
-
// hard-failing kumiko-studio and warning on the rest). Kept as a
|
|
58
|
-
// known-candidate allowlist (documents which repos use the bin/env.ts
|
|
59
|
-
// convention at all — "solon" is deliberately not on it) and intersected
|
|
60
|
-
// with the resolved roots, so a restricted scope actually narrows what this
|
|
61
|
-
// guard scans instead of always walking every repo regardless of scope
|
|
62
|
-
// (follow-up — a money-horse-scoped push must not fail on a
|
|
63
|
-
// finding in publicstatus).
|
|
64
|
-
const CANDIDATE_ENV_TS_REPOS: ReadonlySet<string> = new Set([
|
|
65
|
-
"kumiko-studio",
|
|
66
|
-
"publicstatus",
|
|
67
|
-
"money-horse",
|
|
68
|
-
"phronexsis",
|
|
69
|
-
]);
|
|
70
|
-
|
|
71
|
-
export function reposWithEnvTs(roots: ReadonlyArray<RepoRoot> = resolveRepoRoots()): RepoRoot[] {
|
|
72
|
-
return roots.filter(
|
|
73
|
-
(root) => CANDIDATE_ENV_TS_REPOS.has(root.name) && existsSync(join(root.absPath, "bin/env.ts")),
|
|
74
|
-
);
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
export function findDirectProcessEnv(roots?: ReadonlyArray<RepoRoot>): ProcessEnvFinding[] {
|
|
78
|
-
return scanDirectProcessEnv(roots).findings;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
/**
|
|
82
|
-
* Like findDirectProcessEnv, additionally reports the number of files read
|
|
83
|
-
* and repos with bin/env.ts — without that an empty scan can't be told apart
|
|
84
|
-
* from a clean one.
|
|
85
|
-
*/
|
|
86
|
-
export function scanDirectProcessEnv(roots: ReadonlyArray<RepoRoot> = resolveRepoRoots()): {
|
|
87
|
-
readonly findings: ProcessEnvFinding[];
|
|
88
|
-
readonly scannedFiles: number;
|
|
89
|
-
readonly reposPresent: number;
|
|
90
|
-
} {
|
|
91
|
-
const findings: ProcessEnvFinding[] = [];
|
|
92
|
-
let scannedFiles = 0;
|
|
93
|
-
const repos = reposWithEnvTs(roots);
|
|
94
|
-
for (const repo of repos) {
|
|
95
|
-
const repoDir = repo.absPath;
|
|
96
|
-
for (const pattern of SCAN_PATTERNS) {
|
|
97
|
-
for (const rel of new Glob(pattern).scanSync({ cwd: repoDir })) {
|
|
98
|
-
if (EXCLUDE_DIR.test(`/${rel}`) || IS_TEST.test(rel)) continue;
|
|
99
|
-
if (rel.startsWith("bin/") && !isScannableBinFile(rel)) continue;
|
|
100
|
-
const abs = join(repoDir, rel);
|
|
101
|
-
scannedFiles++;
|
|
102
|
-
scanLinesForPredicate(abs, `${repo.name}/${rel}`, processEnvOnLine, findings);
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
return { findings, scannedFiles, reposPresent: repos.length };
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
export const check: RepoCheck = {
|
|
110
|
-
name: "guard-no-direct-process-env",
|
|
111
|
-
hint: "Read runtime config from bin/env.ts (validated env export), not process.env in bin/main.ts, bin helpers, or src/.",
|
|
112
|
-
run(roots) {
|
|
113
|
-
const scan = scanDirectProcessEnv(roots);
|
|
114
|
-
return {
|
|
115
|
-
violations: scan.findings.map((f) => ({ file: f.file, line: f.line, message: f.text })),
|
|
116
|
-
matchedFiles: scan.scannedFiles,
|
|
117
|
-
// reposPresent as the applicability signal: no repo with bin/env.ts means
|
|
118
|
-
// not applicable, repos present but nothing scanned means broken resolution.
|
|
119
|
-
notApplicable: scan.reposPresent === 0,
|
|
120
|
-
};
|
|
121
|
-
},
|
|
122
|
-
};
|
|
123
|
-
|
|
124
|
-
if (import.meta.main) {
|
|
125
|
-
const failed = reportResults(await runRepoChecks([check]));
|
|
126
|
-
process.exit(failed > 0 ? 1 : 0);
|
|
127
|
-
}
|