@nifrajs/cli 3.1.0 → 3.3.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 +10 -0
- package/dist/assure-hydration.d.ts.map +1 -1
- package/dist/assure-hydration.js +6 -1
- package/dist/assure-hydration.js.map +1 -1
- package/dist/assure.d.ts.map +1 -1
- package/dist/assure.js +3 -2
- package/dist/assure.js.map +1 -1
- package/dist/check-diagnostics.d.ts +165 -0
- package/dist/check-diagnostics.d.ts.map +1 -0
- package/dist/check-diagnostics.js +1009 -0
- package/dist/check-diagnostics.js.map +1 -0
- package/dist/check-scan.d.ts +245 -0
- package/dist/check-scan.d.ts.map +1 -0
- package/dist/check-scan.js +1599 -0
- package/dist/check-scan.js.map +1 -0
- package/dist/check.d.ts +4 -324
- package/dist/check.d.ts.map +1 -1
- package/dist/check.js +8 -2366
- package/dist/check.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +247 -10
- package/dist/cli.js.map +1 -1
- package/dist/command-catalog.d.ts +21 -1
- package/dist/command-catalog.d.ts.map +1 -1
- package/dist/command-catalog.js +122 -0
- package/dist/command-catalog.js.map +1 -1
- package/dist/env-file.js +5 -5
- package/dist/env-file.js.map +1 -1
- package/dist/frontend-guidance.d.ts +57 -0
- package/dist/frontend-guidance.d.ts.map +1 -0
- package/dist/frontend-guidance.js +195 -0
- package/dist/frontend-guidance.js.map +1 -0
- package/dist/levels-tool.d.ts.map +1 -1
- package/dist/levels-tool.js +6 -0
- package/dist/levels-tool.js.map +1 -1
- package/dist/load.d.ts.map +1 -1
- package/dist/load.js +4 -1
- package/dist/load.js.map +1 -1
- package/dist/mcp-context.d.ts +48 -0
- package/dist/mcp-context.d.ts.map +1 -0
- package/dist/mcp-context.js +215 -0
- package/dist/mcp-context.js.map +1 -0
- package/dist/mcp-docs-tools.d.ts.map +1 -1
- package/dist/mcp-docs-tools.js +31 -0
- package/dist/mcp-docs-tools.js.map +1 -1
- package/dist/mcp-exec.d.ts +74 -0
- package/dist/mcp-exec.d.ts.map +1 -0
- package/dist/mcp-exec.js +844 -0
- package/dist/mcp-exec.js.map +1 -0
- package/dist/mcp-http.js +1 -1
- package/dist/mcp-io.d.ts +26 -0
- package/dist/mcp-io.d.ts.map +1 -0
- package/dist/mcp-io.js +100 -0
- package/dist/mcp-io.js.map +1 -0
- package/dist/mcp-reflect.d.ts +16 -0
- package/dist/mcp-reflect.d.ts.map +1 -0
- package/dist/mcp-reflect.js +101 -0
- package/dist/mcp-reflect.js.map +1 -0
- package/dist/mcp-root.d.ts +7 -0
- package/dist/mcp-root.d.ts.map +1 -1
- package/dist/mcp-root.js +51 -3
- package/dist/mcp-root.js.map +1 -1
- package/dist/mcp.d.ts +10 -92
- package/dist/mcp.d.ts.map +1 -1
- package/dist/mcp.js +13 -1232
- package/dist/mcp.js.map +1 -1
- package/dist/openapi-tool.d.ts +5 -10
- package/dist/openapi-tool.d.ts.map +1 -1
- package/dist/openapi-tool.js +21 -2
- package/dist/openapi-tool.js.map +1 -1
- package/dist/openapi-types.d.ts +21 -0
- package/dist/openapi-types.d.ts.map +1 -0
- package/dist/openapi-types.js +214 -0
- package/dist/openapi-types.js.map +1 -0
- package/dist/port.d.ts.map +1 -1
- package/dist/port.js +2 -1
- package/dist/port.js.map +1 -1
- package/dist/project-facts.d.ts +2 -1
- package/dist/project-facts.d.ts.map +1 -1
- package/dist/project-facts.js.map +1 -1
- package/dist/release-verification.d.ts +4 -1
- package/dist/release-verification.d.ts.map +1 -1
- package/dist/release-verification.js +6 -138
- package/dist/release-verification.js.map +1 -1
- package/dist/rules/codes.d.ts +4 -0
- package/dist/rules/codes.d.ts.map +1 -1
- package/dist/rules/codes.js +4 -0
- package/dist/rules/codes.js.map +1 -1
- package/dist/rules/islands.d.ts +4 -0
- package/dist/rules/islands.d.ts.map +1 -0
- package/dist/rules/islands.js +155 -0
- package/dist/rules/islands.js.map +1 -0
- package/dist/rules/nano.d.ts +6 -0
- package/dist/rules/nano.d.ts.map +1 -0
- package/dist/rules/nano.js +264 -0
- package/dist/rules/nano.js.map +1 -0
- package/dist/rules/security.d.ts.map +1 -1
- package/dist/rules/security.js +38 -4
- package/dist/rules/security.js.map +1 -1
- package/dist/scaffold.d.ts +12 -6
- package/dist/scaffold.d.ts.map +1 -1
- package/dist/scaffold.js +149 -10
- package/dist/scaffold.js.map +1 -1
- package/dist/search-terms.d.ts.map +1 -1
- package/dist/search-terms.js +5 -3
- package/dist/search-terms.js.map +1 -1
- package/dist/stylex-migrate.d.ts +38 -0
- package/dist/stylex-migrate.d.ts.map +1 -0
- package/dist/stylex-migrate.js +1052 -0
- package/dist/stylex-migrate.js.map +1 -0
- package/dist/sync-manifest.d.ts.map +1 -1
- package/dist/sync-manifest.js +2 -1
- package/dist/sync-manifest.js.map +1 -1
- package/dist/verification-plan.d.ts +24 -0
- package/dist/verification-plan.d.ts.map +1 -0
- package/dist/verification-plan.js +116 -0
- package/dist/verification-plan.js.map +1 -0
- package/dist/work-graph.d.ts.map +1 -1
- package/dist/work-graph.js +6 -3
- package/dist/work-graph.js.map +1 -1
- package/docs/examples.json +46 -4
- package/docs/llms-full.txt +1346 -28
- package/docs/types.json +4185 -87
- package/package.json +9 -9
- package/src/assure-hydration.ts +6 -1
- package/src/assure.ts +4 -2
- package/src/check-diagnostics.ts +1219 -0
- package/src/check-scan.ts +1825 -0
- package/src/check.ts +47 -2752
- package/src/cli.ts +252 -10
- package/src/command-catalog.ts +155 -0
- package/src/env-file.ts +5 -5
- package/src/frontend-guidance.ts +259 -0
- package/src/levels-tool.ts +6 -0
- package/src/load.ts +4 -1
- package/src/mcp-context.ts +266 -0
- package/src/mcp-docs-tools.ts +37 -0
- package/src/mcp-exec.ts +1040 -0
- package/src/mcp-http.ts +1 -1
- package/src/mcp-io.ts +118 -0
- package/src/mcp-reflect.ts +140 -0
- package/src/mcp-root.ts +62 -4
- package/src/mcp.ts +61 -1511
- package/src/openapi-tool.ts +32 -2
- package/src/openapi-types.ts +261 -0
- package/src/port.ts +2 -1
- package/src/project-facts.ts +2 -4
- package/src/release-verification.ts +22 -164
- package/src/rules/codes.ts +4 -0
- package/src/rules/islands.ts +171 -0
- package/src/rules/nano.ts +295 -0
- package/src/rules/security.ts +40 -4
- package/src/scaffold.ts +169 -9
- package/src/search-terms.ts +7 -3
- package/src/stylex-migrate.ts +1139 -0
- package/src/sync-manifest.ts +2 -1
- package/src/verification-plan.ts +242 -0
- package/src/work-graph.ts +6 -3
|
@@ -0,0 +1,1219 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Diagnostic model and projections for the nifra verification pipeline.
|
|
3
|
+
*
|
|
4
|
+
* Scanners publish frozen facts; this module turns those facts plus policy into the stable legacy and
|
|
5
|
+
* structured diagnostic views. The CLI, JSON output, and MCP all consume the resulting CheckResult.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { existsSync } from "node:fs"
|
|
9
|
+
import { join, resolve } from "node:path"
|
|
10
|
+
import type { AssuranceConfig, AssuranceReport } from "@nifrajs/core/assurance"
|
|
11
|
+
import { type ProjectEvidenceSnapshot, snapshotProjectEvidence } from "@nifrajs/core/evidence"
|
|
12
|
+
import { SINGLE_COPY_REGISTER_SPECIFIER } from "@nifrajs/core/single-copy"
|
|
13
|
+
import type { CapabilityProjectReport } from "./capabilities-tool.ts"
|
|
14
|
+
import type { SourceFinding, StaticRouteFinding } from "./check-scan.ts"
|
|
15
|
+
import {
|
|
16
|
+
IDENT,
|
|
17
|
+
parseSimpleFetchCall,
|
|
18
|
+
REMOVED_IMPORTS,
|
|
19
|
+
SIMPLE_REWRITE_METHODS,
|
|
20
|
+
} from "./check-scan.ts"
|
|
21
|
+
import { type Diagnostic, diagnostic } from "./diagnostics.ts"
|
|
22
|
+
import type { DuplicateInstallFinding } from "./doctor.ts"
|
|
23
|
+
import type { TypeScriptApi } from "./internal/typescript-import.ts"
|
|
24
|
+
import type { PipelineReport } from "./pipeline-report.ts"
|
|
25
|
+
import { freezeProjectFacts, type ProjectFactsSeed } from "./project-facts.ts"
|
|
26
|
+
import { parseRulePacks, type RuleContext, runRuleRegistry } from "./rules/index.ts"
|
|
27
|
+
import { islandRules } from "./rules/islands.ts"
|
|
28
|
+
import { LEGACY_RULE_CODES, legacyRules } from "./rules/legacy.ts"
|
|
29
|
+
import { nanoRules } from "./rules/nano.ts"
|
|
30
|
+
import { routeRules } from "./rules/routes.ts"
|
|
31
|
+
import { securityRules } from "./rules/security.ts"
|
|
32
|
+
|
|
33
|
+
const TSC_LINE = /^(.+?)\((\d+),\d+\):\s*(?:error|warning)\s+TS\d+:\s*(.+)$/
|
|
34
|
+
|
|
35
|
+
/** A single machine-readable check failure - the unit an agent (or CI) acts on. */
|
|
36
|
+
export interface CheckDiagnostic {
|
|
37
|
+
readonly rule: string
|
|
38
|
+
/** `error` fails the gate (a real contract break); `warning` is advisory - surfaced to the agent but
|
|
39
|
+
* does NOT fail `nifra check`, for patterns that are sometimes intentional (a route returning a raw
|
|
40
|
+
* `Response`, which silently drops the typed client to `data: never` but is valid for files/redirects). */
|
|
41
|
+
readonly severity: "error" | "warning" | "info"
|
|
42
|
+
/** Stable diagnostic protocol code. The legacy `rule` remains for compatibility. */
|
|
43
|
+
readonly code?: string
|
|
44
|
+
readonly file?: string
|
|
45
|
+
readonly line?: number
|
|
46
|
+
readonly message: string
|
|
47
|
+
/** The canonical, rule-level fix - clean of the per-occurrence snippet, so an agent can apply it
|
|
48
|
+
* directly. Set for the lint rules (they have one correct fix); omitted for `typecheck` (the fix is
|
|
49
|
+
* specific to each type error). */
|
|
50
|
+
readonly fix?: string
|
|
51
|
+
/** A richer, agent-oriented fix hint. Diffs are only emitted when the edit is mechanical and local;
|
|
52
|
+
* ambiguous cases give concrete steps instead of pretending the checker can safely rewrite code. */
|
|
53
|
+
readonly suggestion?: CheckSuggestion
|
|
54
|
+
/**
|
|
55
|
+
* The import chain that pulls server-only code into the browser bundle, as display labels
|
|
56
|
+
* `[routeFile, …as-written specifiers…, sink]`. Set only on `server-only-import`.
|
|
57
|
+
*
|
|
58
|
+
* #4.4: this is now the FULL **transitive** chain - a bounded import-resolution walk (`Bun.resolveSync`
|
|
59
|
+
* from each file's dir, BFS the local module graph) follows `route → ../data → ../db → node:crypto`,
|
|
60
|
+
* matching the build leak-guard's depth (`detectNodeBuiltinsInClient` in `@nifrajs/web/build`). A
|
|
61
|
+
* length-2 chain (`[routeFile, specifier]`) means the route imports the sink directly. When a hop can't
|
|
62
|
+
* be resolved precisely (a bare pkg, a tsconfig path alias), the walk degrades to the honest direct
|
|
63
|
+
* edge rather than fabricating a deeper path - never a lie.
|
|
64
|
+
*/
|
|
65
|
+
readonly chain?: readonly string[]
|
|
66
|
+
readonly evidence?: readonly string[]
|
|
67
|
+
readonly verify?: string
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface CheckSuggestion {
|
|
71
|
+
readonly kind: "edit" | "command" | "manual"
|
|
72
|
+
readonly title: string
|
|
73
|
+
readonly diff?: string
|
|
74
|
+
/** argv array, not a shell string, so MCP clients can run it without quoting hazards. */
|
|
75
|
+
readonly command?: readonly string[]
|
|
76
|
+
readonly steps?: readonly string[]
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The structured result of a full check - what `--json` prints and the `nifra_check` MCP tool returns. */
|
|
80
|
+
export interface CheckResult {
|
|
81
|
+
readonly ok: boolean
|
|
82
|
+
readonly typecheck: "pass" | "fail" | "skipped"
|
|
83
|
+
/** Why `typecheck` is `"skipped"` (no tsconfig.json, typescript not installed, lints-only mode).
|
|
84
|
+
* Absent when the typecheck ran. Echoed in the human report so a skip is never a dim mystery. */
|
|
85
|
+
readonly typecheckNote?: string
|
|
86
|
+
readonly diagnostics: readonly CheckDiagnostic[]
|
|
87
|
+
/** Normalized diagnostics with stable codes for agents and external renderers. */
|
|
88
|
+
readonly structuredDiagnostics?: readonly Diagnostic[]
|
|
89
|
+
/**
|
|
90
|
+
* Which bundler this app's phases run on, read statically from the config, and how nifra concluded
|
|
91
|
+
* it. Returned even when nothing is wrong: an agent reading this project has to know which plugin
|
|
92
|
+
* slot is live and which toolchain compiles a component before its next edit, and every `pipeline`
|
|
93
|
+
* diagnostic below is only interpretable against it. Absent when the directory is not a nifra app.
|
|
94
|
+
*/
|
|
95
|
+
readonly pipeline?: PipelineReport
|
|
96
|
+
/** Intentional non-typed mount prefixes declared in `nifra.check.json` (e.g. `/auth` for a mounted
|
|
97
|
+
* better-auth). Echoed here so `--json` / the MCP tool / the report can show what the typed-client scan
|
|
98
|
+
* deliberately skipped - a suppressed prefix stays auditable instead of silently hiding real drift. */
|
|
99
|
+
readonly externalMounts?: readonly string[]
|
|
100
|
+
/** Active per-rule overrides from `nifra.check.json` `rules`, echoed verbatim so a retagged or
|
|
101
|
+
* suppressed finding stays auditable in `--json`, the MCP tool, and the human report - config can
|
|
102
|
+
* lower (or raise) the gate, but never invisibly. */
|
|
103
|
+
readonly ruleOverrides?: Readonly<Record<string, RuleOverride>>
|
|
104
|
+
/** Set only when the caller passed `maxDiagnostics` and there were more - `diagnostics` then holds the
|
|
105
|
+
* first `shown` of `total`. It caps the serialized size so the `nifra_check` MCP tool can't emit a
|
|
106
|
+
* message large enough to break the stdio transport; fix the shown diagnostics and re-run for the rest. */
|
|
107
|
+
readonly truncated?: { readonly shown: number; readonly total: number }
|
|
108
|
+
/**
|
|
109
|
+
* The identity preflight's machine-readable result: every duplicate physical install of an
|
|
110
|
+
* identity-sensitive package, with each copy's resolved absolute path, version, and the importers
|
|
111
|
+
* that pulled it in. Present whenever the dependency scan ran - including when it found nothing, so
|
|
112
|
+
* tooling can distinguish "clean" from "did not look". The human rendering of the same data lives in
|
|
113
|
+
* the `duplicate-install` diagnostics; this field is what `--json` consumers parse instead.
|
|
114
|
+
*/
|
|
115
|
+
readonly identityPreflight?: IdentityPreflightResult
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** The `identityPreflight` slice of {@link CheckResult}. */
|
|
119
|
+
export interface IdentityPreflightResult {
|
|
120
|
+
/** Which tree the scan looked at, in the same words the build/dev preflight uses. */
|
|
121
|
+
readonly basis?: string
|
|
122
|
+
/** The scan stopped at the workspace-enumeration cap - "no duplicates" covers only the scanned part. */
|
|
123
|
+
readonly truncated?: boolean
|
|
124
|
+
/** Duplicates that fail the gate. Empty means the scanned tree is clean. */
|
|
125
|
+
readonly duplicates: readonly DuplicateInstallFinding[]
|
|
126
|
+
/** Duplicates covered by a `"nifra": { "singleCopy": [...] }` declaration - reported, never fatal. */
|
|
127
|
+
readonly deduplicated: readonly DuplicateInstallFinding[]
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Pre-resolved route-assurance inputs, so the same reflection that `nifra assure` / `nifra levels`
|
|
132
|
+
* already ran can feed `check`'s capability + trust-manifest diagnostics instead of a second pass.
|
|
133
|
+
* Supplied by {@link collectProjectVerification}. When omitted, `collectCheckResult` loads and computes
|
|
134
|
+
* these itself (the standalone `nifra_check` MCP path); the two routes produce byte-identical results.
|
|
135
|
+
*/
|
|
136
|
+
export interface CheckAssuranceContext {
|
|
137
|
+
/** Whether `nifra.assurance.ts` exists: the gate for running the assurance-fed diagnostics at all. */
|
|
138
|
+
readonly present: boolean
|
|
139
|
+
/** The loaded config, when it loaded. Absent when the file is missing or {@link error} is set. */
|
|
140
|
+
readonly config?: AssuranceConfig
|
|
141
|
+
/** The failure from loading/evaluating the config, surfaced as a `capability-config` diagnostic. */
|
|
142
|
+
readonly error?: unknown
|
|
143
|
+
/** `evaluateRouteAssurance` over the config's source + policy (drives the trust-manifest check). */
|
|
144
|
+
readonly routeAssurance?: AssuranceReport
|
|
145
|
+
/** Static capability provenance, when the config declares a capabilities policy. */
|
|
146
|
+
readonly capability?: CapabilityProjectReport
|
|
147
|
+
/** Canonical token-only evidence reused by manifest and other offline projections. */
|
|
148
|
+
readonly evidence?: ProjectEvidenceSnapshot
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Optional per-project `nifra.check.json` - pure data (no code execution), so it's safe to read before
|
|
152
|
+
* the app is built or even importable, preserving check's pre-`loadApp` invariant. */
|
|
153
|
+
export interface CheckConfig {
|
|
154
|
+
readonly externalMounts: readonly string[]
|
|
155
|
+
readonly rules: Readonly<Record<string, RuleOverride>>
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* One entry of `nifra.check.json` `rules`, keyed by legacy rule name (`response-route`) or stable
|
|
160
|
+
* NF- code (`NF-S002`) - one key retags the finding in both diagnostic views. `severity: "off"`
|
|
161
|
+
* drops the rule's findings; `ignore` drops findings whose file matches any of the globs. Overrides
|
|
162
|
+
* are applied centrally BEFORE `ok` is computed and echoed in the result and the human report -
|
|
163
|
+
* configuration can lower (or raise) the gate, but never invisibly.
|
|
164
|
+
*/
|
|
165
|
+
export interface RuleOverride {
|
|
166
|
+
readonly severity?: "error" | "warn" | "info" | "off"
|
|
167
|
+
readonly ignore?: readonly string[]
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const MAX_IGNORE_GLOB_LENGTH = 4096
|
|
171
|
+
const MAX_IGNORE_GLOB_ALTERNATIVES = 64
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Match the small file-glob language used by check overrides without compiling user input into a
|
|
175
|
+
* regular expression. `nifra.check.json` is commonly supplied by a project or CI wrapper, so an
|
|
176
|
+
* attacker who can influence it must not be able to turn a diagnostic filter into a ReDoS input.
|
|
177
|
+
* The matcher supports the portable glob forms users expect here: `*`, `?`, `**`, character
|
|
178
|
+
* classes, and brace alternatives.
|
|
179
|
+
*/
|
|
180
|
+
function safeIgnoreGlobMatch(pattern: string, file: string): boolean {
|
|
181
|
+
if (pattern.length === 0 || pattern.length > MAX_IGNORE_GLOB_LENGTH) return false
|
|
182
|
+
for (const alternative of expandIgnoreGlobBraces(pattern)) {
|
|
183
|
+
if (matchIgnoreGlobPath(alternative, file)) return true
|
|
184
|
+
}
|
|
185
|
+
return false
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function expandIgnoreGlobBraces(pattern: string): readonly string[] {
|
|
189
|
+
const open = firstUnescaped(pattern, "{")
|
|
190
|
+
if (open === -1) return [pattern]
|
|
191
|
+
const close = matchingBrace(pattern, open)
|
|
192
|
+
if (close === -1) return [pattern]
|
|
193
|
+
const choices = splitBraceChoices(pattern.slice(open + 1, close))
|
|
194
|
+
if (choices.length < 2) return [pattern]
|
|
195
|
+
|
|
196
|
+
const expanded: string[] = []
|
|
197
|
+
for (const choice of choices) {
|
|
198
|
+
const prefix = pattern.slice(0, open) + choice + pattern.slice(close + 1)
|
|
199
|
+
for (const nested of expandIgnoreGlobBraces(prefix)) {
|
|
200
|
+
expanded.push(nested)
|
|
201
|
+
if (expanded.length >= MAX_IGNORE_GLOB_ALTERNATIVES) return expanded
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return expanded
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function firstUnescaped(value: string, needle: string): number {
|
|
208
|
+
let escaped = false
|
|
209
|
+
for (let index = 0; index < value.length; index++) {
|
|
210
|
+
const char = value[index]!
|
|
211
|
+
if (escaped) {
|
|
212
|
+
escaped = false
|
|
213
|
+
continue
|
|
214
|
+
}
|
|
215
|
+
if (char === "\\") {
|
|
216
|
+
escaped = true
|
|
217
|
+
continue
|
|
218
|
+
}
|
|
219
|
+
if (char === needle) return index
|
|
220
|
+
}
|
|
221
|
+
return -1
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function matchingBrace(value: string, open: number): number {
|
|
225
|
+
let depth = 0
|
|
226
|
+
let escaped = false
|
|
227
|
+
for (let index = open; index < value.length; index++) {
|
|
228
|
+
const char = value[index]!
|
|
229
|
+
if (escaped) {
|
|
230
|
+
escaped = false
|
|
231
|
+
continue
|
|
232
|
+
}
|
|
233
|
+
if (char === "\\") {
|
|
234
|
+
escaped = true
|
|
235
|
+
continue
|
|
236
|
+
}
|
|
237
|
+
if (char === "{") depth++
|
|
238
|
+
else if (char === "}" && --depth === 0) return index
|
|
239
|
+
}
|
|
240
|
+
return -1
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function splitBraceChoices(value: string): readonly string[] {
|
|
244
|
+
const choices: string[] = []
|
|
245
|
+
let start = 0
|
|
246
|
+
let depth = 0
|
|
247
|
+
let escaped = false
|
|
248
|
+
for (let index = 0; index < value.length; index++) {
|
|
249
|
+
const char = value[index]!
|
|
250
|
+
if (escaped) {
|
|
251
|
+
escaped = false
|
|
252
|
+
continue
|
|
253
|
+
}
|
|
254
|
+
if (char === "\\") {
|
|
255
|
+
escaped = true
|
|
256
|
+
continue
|
|
257
|
+
}
|
|
258
|
+
if (char === "{") depth++
|
|
259
|
+
else if (char === "}") depth--
|
|
260
|
+
else if (char === "," && depth === 0) {
|
|
261
|
+
choices.push(value.slice(start, index))
|
|
262
|
+
start = index + 1
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
choices.push(value.slice(start))
|
|
266
|
+
return choices
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function matchIgnoreGlobPath(pattern: string, file: string): boolean {
|
|
270
|
+
const patternParts = pattern.split("/")
|
|
271
|
+
const fileParts = file.split("/")
|
|
272
|
+
let reachable = new Array<boolean>(fileParts.length + 1).fill(false)
|
|
273
|
+
reachable[0] = true
|
|
274
|
+
for (const part of patternParts) {
|
|
275
|
+
const next = new Array<boolean>(fileParts.length + 1).fill(false)
|
|
276
|
+
if (part === "**") {
|
|
277
|
+
let canReach = false
|
|
278
|
+
for (let index = 0; index <= fileParts.length; index++) {
|
|
279
|
+
canReach ||= reachable[index] === true
|
|
280
|
+
next[index] = canReach
|
|
281
|
+
}
|
|
282
|
+
} else {
|
|
283
|
+
for (let index = 0; index < fileParts.length; index++) {
|
|
284
|
+
if (reachable[index] && matchIgnoreGlobPart(part, fileParts[index]!)) next[index + 1] = true
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
reachable = next
|
|
288
|
+
}
|
|
289
|
+
return reachable[fileParts.length] === true
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function matchIgnoreGlobPart(pattern: string, value: string): boolean {
|
|
293
|
+
let previous = new Array<boolean>(value.length + 1).fill(false)
|
|
294
|
+
previous[0] = true
|
|
295
|
+
for (let patternIndex = 0; patternIndex < pattern.length; patternIndex++) {
|
|
296
|
+
const char = pattern[patternIndex]!
|
|
297
|
+
const next = new Array<boolean>(value.length + 1).fill(false)
|
|
298
|
+
if (char === "*") {
|
|
299
|
+
next[0] = previous[0] === true
|
|
300
|
+
for (let valueIndex = 1; valueIndex <= value.length; valueIndex++)
|
|
301
|
+
next[valueIndex] = previous[valueIndex] === true || next[valueIndex - 1] === true
|
|
302
|
+
} else if (char === "?") {
|
|
303
|
+
for (let valueIndex = 1; valueIndex <= value.length; valueIndex++)
|
|
304
|
+
next[valueIndex] = previous[valueIndex - 1] === true
|
|
305
|
+
} else if (char === "\\" && patternIndex + 1 < pattern.length) {
|
|
306
|
+
const literal = pattern[++patternIndex]!
|
|
307
|
+
for (let valueIndex = 1; valueIndex <= value.length; valueIndex++)
|
|
308
|
+
next[valueIndex] = previous[valueIndex - 1] === true && value[valueIndex - 1] === literal
|
|
309
|
+
} else if (char === "[") {
|
|
310
|
+
const classEnd = ignoreGlobClassEnd(pattern, patternIndex + 1)
|
|
311
|
+
if (classEnd === -1)
|
|
312
|
+
return matchIgnoreGlobPart(`\\[${pattern.slice(patternIndex + 1)}`, value)
|
|
313
|
+
for (let valueIndex = 1; valueIndex <= value.length; valueIndex++)
|
|
314
|
+
next[valueIndex] =
|
|
315
|
+
previous[valueIndex - 1] === true &&
|
|
316
|
+
matchIgnoreGlobClass(pattern.slice(patternIndex + 1, classEnd), value[valueIndex - 1]!)
|
|
317
|
+
patternIndex = classEnd
|
|
318
|
+
} else {
|
|
319
|
+
for (let valueIndex = 1; valueIndex <= value.length; valueIndex++)
|
|
320
|
+
next[valueIndex] = previous[valueIndex - 1] === true && value[valueIndex - 1] === char
|
|
321
|
+
}
|
|
322
|
+
previous = next
|
|
323
|
+
}
|
|
324
|
+
return previous[value.length] === true
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function ignoreGlobClassEnd(pattern: string, start: number): number {
|
|
328
|
+
for (let index = start; index < pattern.length; index++) {
|
|
329
|
+
if (pattern[index] === "]" && index > start) return index
|
|
330
|
+
}
|
|
331
|
+
return -1
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function matchIgnoreGlobClass(spec: string, value: string): boolean {
|
|
335
|
+
let index = 0
|
|
336
|
+
let negated = false
|
|
337
|
+
if (spec[0] === "!" || spec[0] === "^") {
|
|
338
|
+
negated = true
|
|
339
|
+
index++
|
|
340
|
+
}
|
|
341
|
+
let matched = false
|
|
342
|
+
while (index < spec.length) {
|
|
343
|
+
const first = spec[index] === "\\" ? spec[++index] : spec[index]
|
|
344
|
+
if (first === undefined) break
|
|
345
|
+
index++
|
|
346
|
+
if (spec[index] === "-" && index + 1 < spec.length) {
|
|
347
|
+
index++
|
|
348
|
+
const last = spec[index] === "\\" ? spec[++index] : spec[index]
|
|
349
|
+
if (last !== undefined && first <= value && value <= last) matched = true
|
|
350
|
+
index++
|
|
351
|
+
} else if (value === first) {
|
|
352
|
+
matched = true
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
return negated ? !matched : matched
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
const UNTYPED_CLIENT_HINT =
|
|
359
|
+
'client("…") without a type argument - write client<typeof app>("…") (or client(contract, url)) so the compiler can catch drift'
|
|
360
|
+
const FETCH_HINT =
|
|
361
|
+
"hand-rolled fetch() to your own API - call it through client<typeof app> (from @nifrajs/client) so the compiler catches drift"
|
|
362
|
+
const SERVER_IMPORT_HINT =
|
|
363
|
+
"server-only import in a route module (bundled for the browser) - reach it via c.db / ctx.api inside a loader, never a top-level import"
|
|
364
|
+
const RESPONSE_ROUTE_HINT =
|
|
365
|
+
"route handler returns a raw Response - the typed client infers `data: never`, so drift detection is lost for this route. Return a plain object (it's serialized for you); for a stream use a typed SSE route (`app.sse(...)`), which keeps typed events; or, if a raw Response is intended (file/redirect), add `{ response: t.… }` or a `// nifra-expect raw-response` comment to mark it and silence this"
|
|
366
|
+
const PIPELINE_DOC_HINT =
|
|
367
|
+
"nifra runs one bundler per phase - `vitePlugins` feed Vite, `clientPlugins`/`serverPlugins` feed Bun, and the file `nifra build` imports the adapter from is bundled into the server. See the Gotchas section of the Dev & HMR guide."
|
|
368
|
+
const UNDECLARED_DEP_HINT =
|
|
369
|
+
"imported package is not declared in package.json dependencies - run bun add to declare it"
|
|
370
|
+
const SQL_COMPILER_MISSING_HINT =
|
|
371
|
+
"the interpolated-SQL rule did NOT run - it parses source with the TypeScript compiler, which is an optional peer and is not installed here. This report says nothing about SQL injection either way. Install it with `bun add -d typescript`"
|
|
372
|
+
const SQL_INTERPOLATION_EXAMPLE = "$" + "{value}"
|
|
373
|
+
const INTERPOLATED_SQL_HINT = `SQL built by interpolating a value into the statement text - the value becomes statement, not a parameter, so anything the caller controls can end the literal and continue as SQL. Pass it as a bound parameter (\`?\` / \`$1\` and an argument), or use your driver's tagged template (sql\`… ${SQL_INTERPOLATION_EXAMPLE} …\`), which binds the substitutions for you`
|
|
374
|
+
const MANIFEST_DRIFT_HINT =
|
|
375
|
+
"server-manifest.ts is out of sync with routes/ - re-run the build to regenerate it (a disk-less worker bakes this route table, so the drift is a silent edge break), then commit it"
|
|
376
|
+
const TRUST_MANIFEST_DRIFT_HINT =
|
|
377
|
+
"nifra.manifest.json is missing, invalid, or out of sync - run `nifra manifest emit`, review it, and commit the regenerated trust artifact"
|
|
378
|
+
const CAPABILITY_HINT =
|
|
379
|
+
"effect/capability assurance failed - align the route declaration with approved adapter provenance; never bypass an owned effect seam"
|
|
380
|
+
|
|
381
|
+
export interface CheckTypecheckResult {
|
|
382
|
+
readonly ran: boolean
|
|
383
|
+
readonly ok: boolean
|
|
384
|
+
readonly note?: string
|
|
385
|
+
readonly output?: string
|
|
386
|
+
readonly missingTypeScript?: boolean
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
export interface CheckAnalysisInput {
|
|
390
|
+
readonly facts: ProjectFactsSeed
|
|
391
|
+
readonly typecheck: CheckTypecheckResult
|
|
392
|
+
readonly sqlCompiler: TypeScriptApi | undefined
|
|
393
|
+
readonly checkConfigError?: string
|
|
394
|
+
readonly checkConfigWarnings: readonly string[]
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
export interface CheckDiagnosticsOptions {
|
|
398
|
+
readonly maxDiagnostics?: number
|
|
399
|
+
readonly assurance?: CheckAssuranceContext
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
const bySite = (a: SourceFinding, b: SourceFinding): number =>
|
|
403
|
+
a.file.localeCompare(b.file) || a.line - b.line
|
|
404
|
+
|
|
405
|
+
function oneLineDiff(file: string, line: number, before: string, after: string): string {
|
|
406
|
+
return `--- ${file}:${line}\n+++ ${file}:${line}\n@@\n-${before}\n+${after}`
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
function untypedClientSuggestion(f: SourceFinding): CheckSuggestion {
|
|
410
|
+
const replacement = f.snippet.replace(/(?<![.\w])client\s*\(/, "client<typeof app>(")
|
|
411
|
+
return replacement === f.snippet
|
|
412
|
+
? {
|
|
413
|
+
kind: "manual",
|
|
414
|
+
title: "Add the app type argument to the client factory",
|
|
415
|
+
steps: [
|
|
416
|
+
'Change `client("...")` to `client<typeof app>("...")`.',
|
|
417
|
+
"Make sure the backend app type is imported or otherwise in scope.",
|
|
418
|
+
],
|
|
419
|
+
}
|
|
420
|
+
: {
|
|
421
|
+
kind: "edit",
|
|
422
|
+
title: "Insert `<typeof app>` into the client factory call",
|
|
423
|
+
diff: oneLineDiff(f.file, f.line, f.snippet, replacement),
|
|
424
|
+
steps: ["Make sure the backend app type is imported or otherwise in scope."],
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
function routeKey(method: string, path: string): string {
|
|
429
|
+
return `${method.toUpperCase()} ${path}`
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
function typedClientCall(method: string, path: string): string {
|
|
433
|
+
const segs = path.split("/").filter((seg) => seg !== "")
|
|
434
|
+
let chain = "api"
|
|
435
|
+
if (segs.length === 0) chain += ".index"
|
|
436
|
+
else {
|
|
437
|
+
for (const seg of segs) {
|
|
438
|
+
chain += IDENT.test(seg) ? `.${seg}` : `[${JSON.stringify(seg)}]`
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
return `${chain}.${method.toLowerCase()}()`
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
function staticRouteMap(routes: readonly StaticRouteFinding[]): Map<string, StaticRouteFinding[]> {
|
|
445
|
+
const out = new Map<string, StaticRouteFinding[]>()
|
|
446
|
+
for (const route of routes) {
|
|
447
|
+
if (route.path.includes(":") || route.path.includes("*")) continue
|
|
448
|
+
const key = routeKey(route.method, route.path)
|
|
449
|
+
const bucket = out.get(key)
|
|
450
|
+
if (bucket === undefined) out.set(key, [route])
|
|
451
|
+
else bucket.push(route)
|
|
452
|
+
}
|
|
453
|
+
return out
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function ownFetchEditSuggestion(
|
|
457
|
+
f: SourceFinding,
|
|
458
|
+
routes: Map<string, StaticRouteFinding[]>,
|
|
459
|
+
): CheckSuggestion | undefined {
|
|
460
|
+
const call = parseSimpleFetchCall(f.snippet)
|
|
461
|
+
if (call === undefined || !SIMPLE_REWRITE_METHODS.has(call.method)) return undefined
|
|
462
|
+
const matches = routes.get(routeKey(call.method, call.path))
|
|
463
|
+
if (matches === undefined || matches.length !== 1) return undefined
|
|
464
|
+
const replacementCall = typedClientCall(call.method, call.path)
|
|
465
|
+
const replacement = `${f.snippet.slice(0, call.start)}${replacementCall}${f.snippet.slice(call.end)}`
|
|
466
|
+
if (replacement === f.snippet) return undefined
|
|
467
|
+
const route = matches[0]
|
|
468
|
+
if (route === undefined) return undefined
|
|
469
|
+
return {
|
|
470
|
+
kind: "edit",
|
|
471
|
+
title: "Rewrite simple own-API fetch to the typed nifra client",
|
|
472
|
+
diff: oneLineDiff(f.file, f.line, f.snippet, replacement),
|
|
473
|
+
steps: [
|
|
474
|
+
`Matched ${route.method} ${route.path} at ${route.file}:${route.line}.`,
|
|
475
|
+
"Use an in-scope typed client named `api` (`client<typeof app>(baseUrl)` or the route loader/action `api`).",
|
|
476
|
+
"Update downstream `Response` handling to branch on `{ ok, data, error }` if this variable is used later.",
|
|
477
|
+
],
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
function ownFetchSuggestion(
|
|
482
|
+
f: SourceFinding,
|
|
483
|
+
routes: Map<string, StaticRouteFinding[]>,
|
|
484
|
+
): CheckSuggestion {
|
|
485
|
+
const exact = ownFetchEditSuggestion(f, routes)
|
|
486
|
+
if (exact !== undefined) return exact
|
|
487
|
+
return {
|
|
488
|
+
kind: "manual",
|
|
489
|
+
title: "Replace own-API fetch with the typed nifra client",
|
|
490
|
+
steps: [
|
|
491
|
+
"Call `nifra_routes` or read `nifra://routes` for the exact typed-client call form.",
|
|
492
|
+
"Create `const api = client<typeof app>(baseUrl)` from `@nifrajs/client`.",
|
|
493
|
+
"Replace the relative `fetch()` call with the generated `api...get/post/...` call and branch on `{ ok, data, error }`.",
|
|
494
|
+
],
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
function serverImportSuggestion(
|
|
499
|
+
specifier: string,
|
|
500
|
+
chain: readonly string[],
|
|
501
|
+
fallback: boolean,
|
|
502
|
+
): CheckSuggestion {
|
|
503
|
+
const sink = chain[chain.length - 1] ?? specifier
|
|
504
|
+
// Surface the resolved chain in the fix steps so the agent sees the full path (`route → ../data →
|
|
505
|
+
// ../db → node:crypto`) and which module to cut - not just the route's own top-level import.
|
|
506
|
+
const chainStep =
|
|
507
|
+
chain.length > 2
|
|
508
|
+
? fallback
|
|
509
|
+
? `Server-only code reaches this route through \`${chain.join(" → ")}\` (the deeper chain couldn't be resolved precisely - trace it from \`${specifier}\`).`
|
|
510
|
+
: `Server-only code reaches this route transitively: \`${chain.join(" → ")}\`. The sink is \`${sink}\`; break the chain at the first hop (\`${specifier}\`) or move the sink behind the server boundary.`
|
|
511
|
+
: undefined
|
|
512
|
+
return {
|
|
513
|
+
kind: "manual",
|
|
514
|
+
title: "Move server-only code behind the route server boundary",
|
|
515
|
+
steps: [
|
|
516
|
+
...(chainStep !== undefined ? [chainStep] : []),
|
|
517
|
+
`Remove the top-level \`import … from "${specifier}"\` from this route module (it's bundled for the browser).`,
|
|
518
|
+
"Access backend/data work through the route `loader`/`action` context (`api`, `env`, or project server context).",
|
|
519
|
+
`If a direct module import is unavoidable, lazy-load it (\`await import("${specifier}")\`) inside the server-only loader/action path.`,
|
|
520
|
+
],
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
function responseRouteSuggestion(): CheckSuggestion {
|
|
525
|
+
return {
|
|
526
|
+
kind: "manual",
|
|
527
|
+
title: "Preserve typed-client response inference",
|
|
528
|
+
steps: [
|
|
529
|
+
"Prefer returning a plain object from JSON routes; nifra serializes it for you.",
|
|
530
|
+
"For a stream, use a typed SSE route - `app.sse(...)` (or `sse(c, run)` from `@nifrajs/core/server`) - which keeps typed events instead of collapsing the client to `data: never`.",
|
|
531
|
+
"If this route must return a raw Response (redirect, file), declare an explicit response schema, or add a `// nifra-expect raw-response` comment above the return to mark it intentional and silence this advisory.",
|
|
532
|
+
],
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
export async function collectCheckDiagnostics(
|
|
537
|
+
cwd: string,
|
|
538
|
+
scan: CheckAnalysisInput,
|
|
539
|
+
opts: CheckDiagnosticsOptions = {},
|
|
540
|
+
): Promise<CheckResult> {
|
|
541
|
+
const factsSeed = scan.facts
|
|
542
|
+
const { fetches, untypedClients, removedImports, responseRoutes, interpolatedSql } =
|
|
543
|
+
factsSeed.sourceFindings
|
|
544
|
+
const staticRoutes = factsSeed.routes
|
|
545
|
+
const serverImports = factsSeed.importGraph
|
|
546
|
+
const { doctor: dr, manifestDrift } = factsSeed.packages
|
|
547
|
+
const { checkConfig } = factsSeed.policies
|
|
548
|
+
const tc = scan.typecheck
|
|
549
|
+
const sqlCompiler = scan.sqlCompiler
|
|
550
|
+
const checkConfigError = scan.checkConfigError
|
|
551
|
+
const checkConfigWarnings = scan.checkConfigWarnings
|
|
552
|
+
const diagnostics: CheckDiagnostic[] = []
|
|
553
|
+
const structuredExtras: Diagnostic[] = []
|
|
554
|
+
if (checkConfigError !== undefined) {
|
|
555
|
+
diagnostics.push({
|
|
556
|
+
rule: "check-config",
|
|
557
|
+
severity: "warning",
|
|
558
|
+
file: "nifra.check.json",
|
|
559
|
+
message: `nifra.check.json could not be parsed (${checkConfigError}) - its external-mount allowlist was ignored`,
|
|
560
|
+
fix: "Fix the JSON syntax in nifra.check.json",
|
|
561
|
+
})
|
|
562
|
+
}
|
|
563
|
+
for (const warning of checkConfigWarnings) {
|
|
564
|
+
diagnostics.push({
|
|
565
|
+
rule: "check-config",
|
|
566
|
+
severity: "warning",
|
|
567
|
+
file: "nifra.check.json",
|
|
568
|
+
message: `nifra.check.json: ${warning}`,
|
|
569
|
+
fix: "Fix the entry in nifra.check.json",
|
|
570
|
+
})
|
|
571
|
+
}
|
|
572
|
+
if (tc.missingTypeScript === true) {
|
|
573
|
+
// A tsconfig with no reachable `typescript` install is a broken gate, not a benign skip: the
|
|
574
|
+
// contract check the project asked for (by having a tsconfig) silently didn't run. Fail closed.
|
|
575
|
+
diagnostics.push({
|
|
576
|
+
rule: "typecheck",
|
|
577
|
+
severity: "error",
|
|
578
|
+
file: "tsconfig.json",
|
|
579
|
+
message:
|
|
580
|
+
"tsconfig.json is present but no `typescript` install was found from this directory upward - the typecheck gate did NOT run",
|
|
581
|
+
fix: "bun add -d typescript",
|
|
582
|
+
suggestion: {
|
|
583
|
+
kind: "command",
|
|
584
|
+
title: "Install TypeScript so the contract gate can run",
|
|
585
|
+
command: ["bun", "add", "-d", "typescript"],
|
|
586
|
+
},
|
|
587
|
+
})
|
|
588
|
+
}
|
|
589
|
+
if (tc.ran && !tc.ok) {
|
|
590
|
+
const lines = (tc.output ?? "").split("\n")
|
|
591
|
+
let matched = false
|
|
592
|
+
for (const l of lines) {
|
|
593
|
+
const m = TSC_LINE.exec(l.trim())
|
|
594
|
+
if (m) {
|
|
595
|
+
matched = true
|
|
596
|
+
diagnostics.push({
|
|
597
|
+
rule: "typecheck",
|
|
598
|
+
severity: "error",
|
|
599
|
+
file: m[1] as string,
|
|
600
|
+
line: Number(m[2]),
|
|
601
|
+
message: m[3] as string,
|
|
602
|
+
suggestion: {
|
|
603
|
+
kind: "manual",
|
|
604
|
+
title: "Fix the TypeScript contract error",
|
|
605
|
+
steps: [
|
|
606
|
+
"Open the reported file and line.",
|
|
607
|
+
"Align the handler, route schema, or typed-client call with the compiler error.",
|
|
608
|
+
"Run `nifra_check` again after the edit.",
|
|
609
|
+
],
|
|
610
|
+
},
|
|
611
|
+
})
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
if (!matched)
|
|
615
|
+
diagnostics.push({
|
|
616
|
+
rule: "typecheck",
|
|
617
|
+
severity: "error",
|
|
618
|
+
message: tc.output || "typecheck failed",
|
|
619
|
+
suggestion: {
|
|
620
|
+
kind: "manual",
|
|
621
|
+
title: "Fix the TypeScript contract error",
|
|
622
|
+
steps: ["Run `tsc --noEmit` locally for the full compiler output."],
|
|
623
|
+
},
|
|
624
|
+
})
|
|
625
|
+
}
|
|
626
|
+
const routes = staticRouteMap(staticRoutes)
|
|
627
|
+
for (const f of [...fetches].sort(bySite)) {
|
|
628
|
+
diagnostics.push({
|
|
629
|
+
rule: "typed-client",
|
|
630
|
+
severity: "error",
|
|
631
|
+
file: f.file,
|
|
632
|
+
line: f.line,
|
|
633
|
+
message: `${f.snippet} - ${FETCH_HINT}`,
|
|
634
|
+
fix: FETCH_HINT,
|
|
635
|
+
suggestion: ownFetchSuggestion(f, routes),
|
|
636
|
+
})
|
|
637
|
+
}
|
|
638
|
+
for (const f of [...removedImports].sort(bySite)) {
|
|
639
|
+
const entry = REMOVED_IMPORTS.find(
|
|
640
|
+
(candidate) =>
|
|
641
|
+
f.snippet.includes(`"${candidate.specifier}`) ||
|
|
642
|
+
f.snippet.includes(`'${candidate.specifier}`),
|
|
643
|
+
)
|
|
644
|
+
diagnostics.push({
|
|
645
|
+
rule: "removed-import",
|
|
646
|
+
severity: "error",
|
|
647
|
+
file: f.file,
|
|
648
|
+
line: f.line,
|
|
649
|
+
message: `${f.snippet} - removed in nifra ${entry?.since ?? "2.0"}: ${entry?.replacement ?? "see the changelog"}`,
|
|
650
|
+
fix: entry?.replacement ?? "see the changelog",
|
|
651
|
+
})
|
|
652
|
+
}
|
|
653
|
+
for (const f of [...untypedClients].sort(bySite)) {
|
|
654
|
+
diagnostics.push({
|
|
655
|
+
rule: "untyped-client",
|
|
656
|
+
severity: "error",
|
|
657
|
+
file: f.file,
|
|
658
|
+
line: f.line,
|
|
659
|
+
message: `${f.snippet} - ${UNTYPED_CLIENT_HINT}`,
|
|
660
|
+
fix: UNTYPED_CLIENT_HINT,
|
|
661
|
+
suggestion: untypedClientSuggestion(f),
|
|
662
|
+
})
|
|
663
|
+
}
|
|
664
|
+
for (const f of [...serverImports].sort(bySite)) {
|
|
665
|
+
// #4.4: the FULL transitive chain the import-resolution walk found - `route → ../data → ../db →
|
|
666
|
+
// node:crypto`, matching the build leak-guard's depth - instead of just the direct edge. The chain's
|
|
667
|
+
// tail is the actual server-only sink; the head is the route. When a precise resolve wasn't possible
|
|
668
|
+
// (a bare pkg / path alias), `fallback` is set and the chain degrades to the honest direct edge.
|
|
669
|
+
const chain = f.chain
|
|
670
|
+
const sink = chain[chain.length - 1] ?? f.specifier
|
|
671
|
+
diagnostics.push({
|
|
672
|
+
rule: "server-only-import",
|
|
673
|
+
severity: "error",
|
|
674
|
+
file: f.file,
|
|
675
|
+
line: f.line,
|
|
676
|
+
message: `${f.snippet} - server-only "${sink}" reaches the browser bundle via ${chain.join(" → ")}${f.fallback ? " (direct edge - couldn't resolve the transitive chain precisely)" : ""}; ${SERVER_IMPORT_HINT}`,
|
|
677
|
+
fix: SERVER_IMPORT_HINT,
|
|
678
|
+
chain,
|
|
679
|
+
suggestion: serverImportSuggestion(f.specifier, chain, f.fallback),
|
|
680
|
+
})
|
|
681
|
+
}
|
|
682
|
+
if (sqlCompiler === undefined) {
|
|
683
|
+
// A security rule that could not run must say so. Silence here is indistinguishable from a clean
|
|
684
|
+
// result, and this is the one rule whose clean result means "no SQL injection was found".
|
|
685
|
+
diagnostics.push({
|
|
686
|
+
rule: "interpolated-sql",
|
|
687
|
+
severity: "warning",
|
|
688
|
+
message: SQL_COMPILER_MISSING_HINT,
|
|
689
|
+
fix: SQL_COMPILER_MISSING_HINT,
|
|
690
|
+
suggestion: {
|
|
691
|
+
kind: "command",
|
|
692
|
+
title: "Install TypeScript so the SQL rule can run",
|
|
693
|
+
command: ["bun add -d typescript"],
|
|
694
|
+
},
|
|
695
|
+
})
|
|
696
|
+
}
|
|
697
|
+
for (const f of [...interpolatedSql].sort(bySite)) {
|
|
698
|
+
diagnostics.push({
|
|
699
|
+
rule: "interpolated-sql",
|
|
700
|
+
severity: "error",
|
|
701
|
+
file: f.file,
|
|
702
|
+
line: f.line,
|
|
703
|
+
message: `${f.snippet} - ${INTERPOLATED_SQL_HINT}`,
|
|
704
|
+
fix: "bind the value as a parameter instead of interpolating it into the statement",
|
|
705
|
+
suggestion: {
|
|
706
|
+
kind: "manual",
|
|
707
|
+
title: "Bind the value instead of interpolating it",
|
|
708
|
+
steps: [
|
|
709
|
+
"Replace the interpolation with a placeholder your driver understands (`?` for SQLite/MySQL, `$1` for Postgres).",
|
|
710
|
+
"Pass the value as an argument alongside the statement, so the driver binds it.",
|
|
711
|
+
`Or switch to the driver's tagged template (sql\`… ${SQL_INTERPOLATION_EXAMPLE} …\`): the tag receives substitutions separately and binds them.`,
|
|
712
|
+
"An identifier that genuinely cannot be bound (a table or column name) must be checked against an allowlist you control, never taken from the request.",
|
|
713
|
+
"If the statement is dynamic but every value is already bound (generating `($1),($2),…` for a batch insert), mark it with a `// nifra-expect sql-dynamic: <reason>` comment on the line above - the reason is required.",
|
|
714
|
+
],
|
|
715
|
+
},
|
|
716
|
+
})
|
|
717
|
+
}
|
|
718
|
+
// Advisory - surfaced but NOT folded into `ok`, so it never fails the gate (a raw Response is valid).
|
|
719
|
+
for (const f of [...responseRoutes].sort(bySite)) {
|
|
720
|
+
diagnostics.push({
|
|
721
|
+
rule: "response-route",
|
|
722
|
+
severity: "warning",
|
|
723
|
+
file: f.file,
|
|
724
|
+
line: f.line,
|
|
725
|
+
message: `${f.snippet} - ${RESPONSE_ROUTE_HINT}`,
|
|
726
|
+
fix: RESPONSE_ROUTE_HINT,
|
|
727
|
+
suggestion: responseRouteSuggestion(),
|
|
728
|
+
})
|
|
729
|
+
}
|
|
730
|
+
if (dr.ran) {
|
|
731
|
+
for (const f of dr.findings) {
|
|
732
|
+
diagnostics.push({
|
|
733
|
+
rule: "undeclared-dependency",
|
|
734
|
+
severity: "error",
|
|
735
|
+
file: f.file,
|
|
736
|
+
line: f.line,
|
|
737
|
+
message: `imports ${f.package} which is not declared in package.json - ${UNDECLARED_DEP_HINT}`,
|
|
738
|
+
fix: `add ${f.package} to package.json dependencies`,
|
|
739
|
+
suggestion: {
|
|
740
|
+
kind: "command",
|
|
741
|
+
title: `Declare ${f.package} in package.json`,
|
|
742
|
+
command: ["bun", "add", f.package],
|
|
743
|
+
},
|
|
744
|
+
})
|
|
745
|
+
}
|
|
746
|
+
for (const finding of dr.duplicateInstalls) {
|
|
747
|
+
// One line per physical copy: version, resolved absolute path, and who pulled it in. The
|
|
748
|
+
// absolute path is what a reader pastes into an editor or `rm -rf`; the importer list is what
|
|
749
|
+
// tells them WHICH package.json to fix - a relative path alone answers neither.
|
|
750
|
+
const copyLines = finding.copies.map(
|
|
751
|
+
(copy) =>
|
|
752
|
+
`${finding.package}@${copy.version} at ${copy.absolutePath ?? copy.path} - pulled in by ${copy.importers.join(", ")}`,
|
|
753
|
+
)
|
|
754
|
+
diagnostics.push({
|
|
755
|
+
rule: "duplicate-install",
|
|
756
|
+
severity: "error",
|
|
757
|
+
message: `${finding.package} identity preflight found ${finding.cause} - ${finding.explanation}${finding.topology === undefined ? "" : `. Topology: ${finding.topology}`}${finding.scope === undefined ? "" : `. Scope: ${finding.scope}`}`,
|
|
758
|
+
fix: finding.remediation,
|
|
759
|
+
evidence: copyLines,
|
|
760
|
+
suggestion: {
|
|
761
|
+
kind: "manual",
|
|
762
|
+
title: `Resolve ${finding.package} to one loaded copy`,
|
|
763
|
+
// The renderer prints this block verbatim before the steps: the exact config for fix 2, so
|
|
764
|
+
// the reader pastes instead of transcribing prose into JSON and TOML.
|
|
765
|
+
diff: [
|
|
766
|
+
"package.json:",
|
|
767
|
+
` "nifra": { "singleCopy": ["${finding.package}"] }`,
|
|
768
|
+
"bunfig.toml:",
|
|
769
|
+
` preload = ["${SINGLE_COPY_REGISTER_SPECIFIER}"]`,
|
|
770
|
+
" [test]",
|
|
771
|
+
` preload = ["${SINGLE_COPY_REGISTER_SPECIFIER}"]`,
|
|
772
|
+
].join("\n"),
|
|
773
|
+
steps: [
|
|
774
|
+
...copyLines.map((line) => `Copy: ${line}`),
|
|
775
|
+
"Fix 1 - deduplicate: align workspace dependency and peer ranges on one compatible version, remove stale nested installs, and reinstall from the workspace root so every importer resolves one physical copy.",
|
|
776
|
+
`Fix 2 - declare single-copy: apply the package.json and bunfig.toml config printed above; nifra then rewrites every duplicate to this app's copy.${finding.cause === "version-skew" ? " A declaration only covers same-version duplicates, so fix 1's range alignment must land first." : ""}`,
|
|
777
|
+
"Re-run `nifra check`; the gate stays failing until one fix lands.",
|
|
778
|
+
],
|
|
779
|
+
},
|
|
780
|
+
})
|
|
781
|
+
}
|
|
782
|
+
// Declared single-copy: the resolver collapses these before anything loads, so the build is sound
|
|
783
|
+
// and the gate stays green. It is still worth a line - the guarantee lives in a declaration now,
|
|
784
|
+
// and a reader who deletes it gets a null hook dispatcher with no obvious cause.
|
|
785
|
+
for (const finding of dr.deduplicatedInstalls ?? []) {
|
|
786
|
+
const copies = finding.copies.map((copy) => copy.path).join("; ")
|
|
787
|
+
diagnostics.push({
|
|
788
|
+
rule: "duplicate-install",
|
|
789
|
+
severity: "warning",
|
|
790
|
+
message: `${finding.package} is installed at ${finding.copies.length} paths (${copies}) and is declared single-copy - nifra resolves every duplicate to this app's copy`,
|
|
791
|
+
fix: finding.remediation,
|
|
792
|
+
})
|
|
793
|
+
}
|
|
794
|
+
// Advisory (never fails the gate): while actively editing a linked package its dist is always
|
|
795
|
+
// momentarily behind. The finding earns its keep when a dev server is about to start against it -
|
|
796
|
+
// Bun reads live `src` while Vite's SSR runner reads the artifact, so a stale one 500s inside
|
|
797
|
+
// framework/shared-package code and reads exactly like an upstream regression.
|
|
798
|
+
for (const f of dr.staleDists) {
|
|
799
|
+
// The rebuild is only actionable with the LOCATION: a workspace link routinely points into a
|
|
800
|
+
// sibling repo, so "rebuild @nifrajs/core" left the developer to go find the checkout and guess
|
|
801
|
+
// the script. Name the directory and the package's own script, or say plainly that it declares
|
|
802
|
+
// none - never suggest a command that would fail.
|
|
803
|
+
const rebuild =
|
|
804
|
+
f.buildScript === undefined
|
|
805
|
+
? `${f.packageDir} declares no build script - build it the way that package expects`
|
|
806
|
+
: `cd ${f.packageDir} && bun run ${f.buildScript} (or \`nifra fix --code NF-C010\`)`
|
|
807
|
+
diagnostics.push({
|
|
808
|
+
rule: "stale-workspace-dist",
|
|
809
|
+
severity: "warning",
|
|
810
|
+
message: f.missing
|
|
811
|
+
? `${f.package} was never built - ${f.distFile} is missing, but its export map serves it to Vite SSR/node consumers while Bun reads src - ${rebuild}`
|
|
812
|
+
: `${f.package} has a stale build artifact - ${f.distFile} is ${f.behindSeconds}s older than ${f.sourceFile}, and Vite SSR/node consumers read the artifact while Bun reads src - ${rebuild}`,
|
|
813
|
+
fix: rebuild,
|
|
814
|
+
evidence: [f.package, f.distFile, f.sourceFile, f.packageDir],
|
|
815
|
+
suggestion: {
|
|
816
|
+
kind: "manual",
|
|
817
|
+
title: `Rebuild ${f.package}`,
|
|
818
|
+
steps: [
|
|
819
|
+
rebuild,
|
|
820
|
+
"Only workspace-linked installs drift; npm tarballs are immutable and never flagged.",
|
|
821
|
+
],
|
|
822
|
+
},
|
|
823
|
+
})
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
// The two-pipeline rule, read from the config as TEXT (doctor collects it - see ./pipeline-report.ts).
|
|
827
|
+
// `loadApp` already refuses a misplaced plugin, but only when something loads the app; a check that
|
|
828
|
+
// never executes project code, and CI that never starts a dev server, would otherwise meet these for
|
|
829
|
+
// the first time as a production server that built cleanly and died at startup.
|
|
830
|
+
for (const f of dr.pipeline?.findings ?? []) {
|
|
831
|
+
diagnostics.push({
|
|
832
|
+
rule: "pipeline",
|
|
833
|
+
severity: f.severity,
|
|
834
|
+
file: f.file,
|
|
835
|
+
...(f.line !== undefined ? { line: f.line } : {}),
|
|
836
|
+
message: f.message,
|
|
837
|
+
fix: f.fix,
|
|
838
|
+
suggestion: { kind: "manual", title: f.fix, steps: [PIPELINE_DOC_HINT] },
|
|
839
|
+
})
|
|
840
|
+
}
|
|
841
|
+
// #7: a committed server-manifest.ts that drifted from routes/ - name the exact missing/extra routes.
|
|
842
|
+
for (const f of manifestDrift) {
|
|
843
|
+
const parts: string[] = []
|
|
844
|
+
if (f.missing.length > 0) parts.push(`missing from manifest: ${f.missing.join(", ")}`)
|
|
845
|
+
if (f.extra.length > 0) parts.push(`stale in manifest: ${f.extra.join(", ")}`)
|
|
846
|
+
diagnostics.push({
|
|
847
|
+
rule: "server-manifest-drift",
|
|
848
|
+
severity: "error",
|
|
849
|
+
file: f.file,
|
|
850
|
+
message: `${f.file} drifted from routes/ (${parts.join("; ")}) - ${MANIFEST_DRIFT_HINT}`,
|
|
851
|
+
fix: MANIFEST_DRIFT_HINT,
|
|
852
|
+
evidence: [...f.missing, ...f.extra],
|
|
853
|
+
suggestion: {
|
|
854
|
+
kind: "manual",
|
|
855
|
+
title: "Regenerate the committed server manifest",
|
|
856
|
+
steps: [
|
|
857
|
+
"Re-run your build (`nifra build --target <t>` or your build script) - it regenerates server-manifest.ts from the current routes/.",
|
|
858
|
+
"Commit the updated server-manifest.ts.",
|
|
859
|
+
],
|
|
860
|
+
},
|
|
861
|
+
})
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
// G+B+D+F: when the project opts into capability assurance, `nifra check` becomes the static
|
|
865
|
+
// provenance firewall as well as the typed-contract gate. Loading is explicit/config-owned; projects
|
|
866
|
+
// without nifra.assurance.ts retain the historical scan and hot path unchanged.
|
|
867
|
+
const provided = opts.assurance
|
|
868
|
+
let applicationRulePacks: readonly import("./rules/index.ts").RulePack[] = []
|
|
869
|
+
let loadedPolicy = provided
|
|
870
|
+
let loadedCapability: CapabilityProjectReport | undefined = provided?.capability
|
|
871
|
+
const assuranceConfigPath = join(cwd, "nifra.assurance.ts")
|
|
872
|
+
if (provided !== undefined ? provided.present : existsSync(assuranceConfigPath)) {
|
|
873
|
+
try {
|
|
874
|
+
// Either the shared reflection from `collectProjectVerification` (no second pass) or, on the
|
|
875
|
+
// standalone path, loaded + reflected here. Both branches yield the same config + evidence.
|
|
876
|
+
let config: AssuranceConfig
|
|
877
|
+
let project: CapabilityProjectReport | undefined
|
|
878
|
+
let routeAssurance: AssuranceReport | undefined
|
|
879
|
+
let evidence: ProjectEvidenceSnapshot | undefined
|
|
880
|
+
if (provided !== undefined) {
|
|
881
|
+
// A load/evaluate failure travels as `provided.error`; re-throwing lands it in the same
|
|
882
|
+
// capability-config diagnostic the standalone catch produces.
|
|
883
|
+
if (provided.error !== undefined) throw provided.error
|
|
884
|
+
config = provided.config as AssuranceConfig
|
|
885
|
+
project = provided.capability
|
|
886
|
+
routeAssurance = provided.routeAssurance
|
|
887
|
+
evidence = provided.evidence
|
|
888
|
+
} else {
|
|
889
|
+
const { loadAssuranceConfig } = await import("./assure.ts")
|
|
890
|
+
config = await loadAssuranceConfig(cwd)
|
|
891
|
+
if (config.capabilities !== undefined) {
|
|
892
|
+
const { collectCapabilityProjectReport } = await import("./capabilities-tool.ts")
|
|
893
|
+
project = await collectCapabilityProjectReport(cwd, config.source, config.capabilities)
|
|
894
|
+
}
|
|
895
|
+
loadedPolicy = {
|
|
896
|
+
present: true,
|
|
897
|
+
config,
|
|
898
|
+
...(routeAssurance === undefined ? {} : { routeAssurance }),
|
|
899
|
+
...(project === undefined ? {} : { capability: project }),
|
|
900
|
+
...(evidence === undefined ? {} : { evidence }),
|
|
901
|
+
}
|
|
902
|
+
loadedCapability = project
|
|
903
|
+
}
|
|
904
|
+
applicationRulePacks = parseRulePacks(config.rulePacks)
|
|
905
|
+
const capabilityReport = project?.report
|
|
906
|
+
if (config.capabilities !== undefined && project !== undefined) {
|
|
907
|
+
for (const finding of project.report.findings) {
|
|
908
|
+
const violation =
|
|
909
|
+
finding.code === "forbidden-effect-import"
|
|
910
|
+
? project.violations.find(
|
|
911
|
+
(candidate) =>
|
|
912
|
+
candidate.method === finding.method && candidate.path === finding.path,
|
|
913
|
+
)
|
|
914
|
+
: undefined
|
|
915
|
+
const truncation =
|
|
916
|
+
finding.code === "provenance-truncated"
|
|
917
|
+
? project.truncations.find(
|
|
918
|
+
(candidate) =>
|
|
919
|
+
candidate.method === finding.method && candidate.path === finding.path,
|
|
920
|
+
)
|
|
921
|
+
: undefined
|
|
922
|
+
// An unmatched seam is a policy defect, not a route defect: the fix is in the policy file,
|
|
923
|
+
// so it gets its own steps instead of the route-side provenance guidance.
|
|
924
|
+
const seamFix =
|
|
925
|
+
finding.code === "unmatched-provenance-seam"
|
|
926
|
+
? "Write the seam exactly as the code imports it, or delete the rule."
|
|
927
|
+
: undefined
|
|
928
|
+
diagnostics.push({
|
|
929
|
+
rule: "capability-assurance",
|
|
930
|
+
severity: "error",
|
|
931
|
+
...(violation !== undefined
|
|
932
|
+
? { file: violation.module, chain: violation.chain }
|
|
933
|
+
: truncation !== undefined
|
|
934
|
+
? { chain: truncation.chain }
|
|
935
|
+
: {}),
|
|
936
|
+
message: `${finding.message}${seamFix === undefined ? ` - ${CAPABILITY_HINT}` : ""}`,
|
|
937
|
+
fix: seamFix ?? CAPABILITY_HINT,
|
|
938
|
+
suggestion:
|
|
939
|
+
seamFix === undefined
|
|
940
|
+
? {
|
|
941
|
+
kind: "manual",
|
|
942
|
+
title: "Restore declared effect provenance",
|
|
943
|
+
steps: [
|
|
944
|
+
"Route effectful work through an import listed in capabilities.provenance.imports.",
|
|
945
|
+
"Declare the exact capability token on the route; do not widen unrelated routes in the same file.",
|
|
946
|
+
"For domain writes, add the adapter the capability definition requires: `schema.idempotency` for the `request` tier, `.use(durableCommand({ journal }))` from @nifrajs/middleware for the `durable` tier.",
|
|
947
|
+
"Run `nifra capabilities snapshot` only after assurance passes, then review the lockfile diff.",
|
|
948
|
+
],
|
|
949
|
+
}
|
|
950
|
+
: {
|
|
951
|
+
kind: "manual",
|
|
952
|
+
title: "Point the provenance rule at a module that exists",
|
|
953
|
+
steps: [
|
|
954
|
+
"Copy the specifier from the import statement itself - it is matched as written, with no extension or index resolution.",
|
|
955
|
+
"Use a trailing `/*` when the seam is a directory of modules (`@myorg/db/*`).",
|
|
956
|
+
"For a routeModules entry, give the project-relative path of the file that implements the route.",
|
|
957
|
+
"Delete the rule if the seam it governed is gone; leaving it in place proves nothing.",
|
|
958
|
+
],
|
|
959
|
+
},
|
|
960
|
+
})
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
if (config.manifest !== undefined) {
|
|
964
|
+
const { buildNifraManifest, parseNifraManifest, serializeNifraManifest } = await import(
|
|
965
|
+
"@nifrajs/core/manifest"
|
|
966
|
+
)
|
|
967
|
+
const assurance =
|
|
968
|
+
routeAssurance ??
|
|
969
|
+
(await import("@nifrajs/core/assurance")).evaluateRouteAssurance(
|
|
970
|
+
config.source,
|
|
971
|
+
config.policy,
|
|
972
|
+
{
|
|
973
|
+
...(config.capabilities !== undefined
|
|
974
|
+
? { definitions: config.capabilities.definitions }
|
|
975
|
+
: {}),
|
|
976
|
+
},
|
|
977
|
+
)
|
|
978
|
+
evidence ??= snapshotProjectEvidence(config.source, {
|
|
979
|
+
assurance,
|
|
980
|
+
...(capabilityReport !== undefined ? { capabilities: capabilityReport } : {}),
|
|
981
|
+
})
|
|
982
|
+
const path = resolve(cwd, config.manifest.path ?? "nifra.manifest.json")
|
|
983
|
+
let message: string | undefined
|
|
984
|
+
if (!assurance.ok || (capabilityReport !== undefined && !capabilityReport.ok)) {
|
|
985
|
+
message =
|
|
986
|
+
"the configured assurance policy is failing, so a trusted manifest cannot be built"
|
|
987
|
+
} else if (!existsSync(path)) {
|
|
988
|
+
message = "the configured trust manifest is missing"
|
|
989
|
+
} else {
|
|
990
|
+
try {
|
|
991
|
+
const current = await buildNifraManifest({
|
|
992
|
+
evidence,
|
|
993
|
+
assurance,
|
|
994
|
+
...(capabilityReport !== undefined ? { capabilities: capabilityReport } : {}),
|
|
995
|
+
})
|
|
996
|
+
const storedText = await Bun.file(path).text()
|
|
997
|
+
const stored = await parseNifraManifest(storedText, path)
|
|
998
|
+
const expectedText = `${serializeNifraManifest(current)}\n`
|
|
999
|
+
if (storedText !== expectedText || stored.contentHash !== current.contentHash) {
|
|
1000
|
+
message = "the configured trust manifest does not match live route reflection"
|
|
1001
|
+
}
|
|
1002
|
+
} catch (error) {
|
|
1003
|
+
message = `the configured trust manifest is invalid: ${error instanceof Error ? error.message : String(error)}`
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
if (message !== undefined) {
|
|
1007
|
+
diagnostics.push({
|
|
1008
|
+
rule: "manifest-drift",
|
|
1009
|
+
severity: "error",
|
|
1010
|
+
file: path,
|
|
1011
|
+
message: `${message} - ${TRUST_MANIFEST_DRIFT_HINT}`,
|
|
1012
|
+
fix: TRUST_MANIFEST_DRIFT_HINT,
|
|
1013
|
+
suggestion: {
|
|
1014
|
+
kind: "command",
|
|
1015
|
+
title: "Regenerate the signed-manifest input artifact",
|
|
1016
|
+
command: ["nifra", "manifest", "emit"],
|
|
1017
|
+
steps: [
|
|
1018
|
+
"Review the route, assurance, capability, and classification delta before committing it.",
|
|
1019
|
+
],
|
|
1020
|
+
},
|
|
1021
|
+
})
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
} catch (err) {
|
|
1025
|
+
loadedPolicy = { present: true, error: err }
|
|
1026
|
+
diagnostics.push({
|
|
1027
|
+
rule: "capability-config",
|
|
1028
|
+
severity: "error",
|
|
1029
|
+
file: "nifra.assurance.ts",
|
|
1030
|
+
message: `capability assurance config could not be evaluated: ${err instanceof Error ? err.message : String(err)}`,
|
|
1031
|
+
suggestion: {
|
|
1032
|
+
kind: "manual",
|
|
1033
|
+
title: "Repair the assurance config",
|
|
1034
|
+
steps: [
|
|
1035
|
+
"Ensure nifra.assurance.ts default-exports defineAssuranceConfig({ source, policy, capabilities }).",
|
|
1036
|
+
"Fix configuration/import errors; the provenance firewall fails closed when its policy cannot load.",
|
|
1037
|
+
],
|
|
1038
|
+
},
|
|
1039
|
+
})
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
try {
|
|
1044
|
+
const { checkContractsLock } = await import("./contracts.ts")
|
|
1045
|
+
if (!existsSync(join(cwd, "backend.ts")) && !existsSync(join(cwd, "contracts.lock.json"))) {
|
|
1046
|
+
throw new Error("contract source not configured")
|
|
1047
|
+
}
|
|
1048
|
+
const contract = await checkContractsLock(cwd)
|
|
1049
|
+
if (!contract.present) {
|
|
1050
|
+
structuredExtras.push(
|
|
1051
|
+
diagnostic({
|
|
1052
|
+
code: "NF-K001",
|
|
1053
|
+
severity: "info",
|
|
1054
|
+
message: "no contract lock; run `nifra contracts snapshot` to enable drift detection",
|
|
1055
|
+
verify: "nifra contracts snapshot",
|
|
1056
|
+
}),
|
|
1057
|
+
)
|
|
1058
|
+
} else {
|
|
1059
|
+
if (contract.vacuous) {
|
|
1060
|
+
// Every route hashes to the empty-schema digest, so the lock exists but the drift rule guards
|
|
1061
|
+
// nothing: it can only ever compare "no schema" to "no schema". Say so, or a green contract check
|
|
1062
|
+
// reads as proof of a stable contract when there is no contract to be stable.
|
|
1063
|
+
structuredExtras.push(
|
|
1064
|
+
diagnostic({
|
|
1065
|
+
code: "NF-K001",
|
|
1066
|
+
severity: "info",
|
|
1067
|
+
message:
|
|
1068
|
+
"no route schemas declared - the trust manifest is vacuous: every contract hash is the empty-schema digest, so drift detection guards nothing. Declare route schemas (body/query/params/response) so the lock has a contract to protect.",
|
|
1069
|
+
verify: "nifra check --lints-only",
|
|
1070
|
+
}),
|
|
1071
|
+
)
|
|
1072
|
+
}
|
|
1073
|
+
for (const finding of contract.diagnostics) {
|
|
1074
|
+
diagnostics.push({
|
|
1075
|
+
rule: "contract-drift",
|
|
1076
|
+
severity: "error",
|
|
1077
|
+
code: "NF-K001",
|
|
1078
|
+
...(finding.route !== undefined ? { evidence: [finding.route] } : {}),
|
|
1079
|
+
message: finding.message,
|
|
1080
|
+
fix: "run `nifra contracts snapshot` after reviewing the contract change",
|
|
1081
|
+
verify: "nifra check --lints-only",
|
|
1082
|
+
})
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
} catch (error) {
|
|
1086
|
+
if (error instanceof Error && error.message === "contract source not configured") {
|
|
1087
|
+
// API-only source scans have no contract surface to snapshot.
|
|
1088
|
+
} else {
|
|
1089
|
+
diagnostics.push({
|
|
1090
|
+
rule: "contract-drift",
|
|
1091
|
+
severity: "error",
|
|
1092
|
+
code: "NF-K001",
|
|
1093
|
+
message: `contract lock could not be checked: ${error instanceof Error ? error.message : String(error)}`,
|
|
1094
|
+
verify: "nifra contracts snapshot",
|
|
1095
|
+
})
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
const projectFacts = freezeProjectFacts(
|
|
1100
|
+
{
|
|
1101
|
+
...factsSeed,
|
|
1102
|
+
policies: {
|
|
1103
|
+
...factsSeed.policies,
|
|
1104
|
+
...(loadedPolicy === undefined ? {} : { assurance: loadedPolicy }),
|
|
1105
|
+
...(loadedCapability === undefined ? {} : { capability: loadedCapability }),
|
|
1106
|
+
rulePacks: applicationRulePacks,
|
|
1107
|
+
},
|
|
1108
|
+
},
|
|
1109
|
+
diagnostics,
|
|
1110
|
+
)
|
|
1111
|
+
const ruleContext: RuleContext = {
|
|
1112
|
+
root: cwd,
|
|
1113
|
+
sources: projectFacts.source,
|
|
1114
|
+
project: projectFacts,
|
|
1115
|
+
}
|
|
1116
|
+
const structuredDiagnostics = [...structuredExtras]
|
|
1117
|
+
let registryDiagnostics: Diagnostic[] = []
|
|
1118
|
+
try {
|
|
1119
|
+
registryDiagnostics = await runRuleRegistry(
|
|
1120
|
+
ruleContext,
|
|
1121
|
+
[...legacyRules, ...securityRules, ...routeRules, ...islandRules, ...nanoRules],
|
|
1122
|
+
projectFacts.policies.rulePacks,
|
|
1123
|
+
)
|
|
1124
|
+
structuredDiagnostics.push(...registryDiagnostics)
|
|
1125
|
+
} catch (error) {
|
|
1126
|
+
registryDiagnostics = [
|
|
1127
|
+
diagnostic({
|
|
1128
|
+
code: "NF-C017",
|
|
1129
|
+
severity: "error",
|
|
1130
|
+
message: `rule registry failed closed: ${error instanceof Error ? error.message : String(error)}`,
|
|
1131
|
+
fix: { recipe: "rule-pack.repair", command: "nifra check --lints-only" },
|
|
1132
|
+
verify: "nifra check --lints-only",
|
|
1133
|
+
}),
|
|
1134
|
+
]
|
|
1135
|
+
structuredDiagnostics.push(...registryDiagnostics)
|
|
1136
|
+
}
|
|
1137
|
+
for (const item of registryDiagnostics) {
|
|
1138
|
+
// The legacy adapters publish stable structured findings; the human compatibility view already
|
|
1139
|
+
// contains their original rule names. Security rules and application packs still need a legacy-view
|
|
1140
|
+
// row because they have no pre-registry diagnostic.
|
|
1141
|
+
if (legacyRules.some((rule) => rule.code === item.code)) continue
|
|
1142
|
+
diagnostics.push({
|
|
1143
|
+
rule: item.code,
|
|
1144
|
+
severity: item.severity === "error" ? "error" : "warning",
|
|
1145
|
+
code: item.code,
|
|
1146
|
+
...(item.file !== undefined ? { file: item.file } : {}),
|
|
1147
|
+
...(item.line !== undefined ? { line: item.line } : {}),
|
|
1148
|
+
message: item.message,
|
|
1149
|
+
...(item.evidence !== undefined ? { evidence: item.evidence } : {}),
|
|
1150
|
+
...(item.verify !== undefined ? { verify: item.verify } : {}),
|
|
1151
|
+
})
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
// Per-rule overrides from `nifra.check.json` `rules`, applied centrally to BOTH diagnostic views
|
|
1155
|
+
// before `ok` is computed - never inside individual rules, so no rule can dodge (or double-apply)
|
|
1156
|
+
// them. A key matches the legacy rule name or the stable NF- code.
|
|
1157
|
+
const overrideFor = (...keys: (string | undefined)[]): RuleOverride | undefined => {
|
|
1158
|
+
for (const key of keys) {
|
|
1159
|
+
if (key !== undefined && checkConfig.rules[key] !== undefined) return checkConfig.rules[key]
|
|
1160
|
+
}
|
|
1161
|
+
return undefined
|
|
1162
|
+
}
|
|
1163
|
+
const dropped = (override: RuleOverride, file: string | undefined): boolean => {
|
|
1164
|
+
if (override.severity === "off") return true
|
|
1165
|
+
if (override.ignore === undefined || file === undefined) return false
|
|
1166
|
+
return override.ignore.some((pattern) => safeIgnoreGlobMatch(pattern, file))
|
|
1167
|
+
}
|
|
1168
|
+
const codeToLegacy = new Map(
|
|
1169
|
+
Object.entries(LEGACY_RULE_CODES).map(([name, code]) => [code, name]),
|
|
1170
|
+
)
|
|
1171
|
+
const finalDiagnostics = diagnostics.flatMap<CheckDiagnostic>((d) => {
|
|
1172
|
+
const override = overrideFor(d.rule, d.code, LEGACY_RULE_CODES[d.rule])
|
|
1173
|
+
if (override === undefined) return [d]
|
|
1174
|
+
if (dropped(override, d.file)) return []
|
|
1175
|
+
// "off" is fully handled by `dropped` above - only real severities reach the retag.
|
|
1176
|
+
if (override.severity === undefined || override.severity === "off") return [d]
|
|
1177
|
+
return [{ ...d, severity: override.severity === "warn" ? "warning" : override.severity }]
|
|
1178
|
+
})
|
|
1179
|
+
const finalStructured = structuredDiagnostics.flatMap<Diagnostic>((d) => {
|
|
1180
|
+
const override = overrideFor(d.code, codeToLegacy.get(d.code))
|
|
1181
|
+
if (override === undefined) return [d]
|
|
1182
|
+
if (dropped(override, d.file)) return []
|
|
1183
|
+
if (override.severity === undefined || override.severity === "off") return [d]
|
|
1184
|
+
return [Object.freeze({ ...d, severity: override.severity })]
|
|
1185
|
+
})
|
|
1186
|
+
|
|
1187
|
+
// Cap the diagnostics when asked (the MCP path), so a project with thousands of findings can't return a
|
|
1188
|
+
// message that breaks the stdio transport. `ok` reflects the FULL set - truncation never flips it.
|
|
1189
|
+
const total = finalDiagnostics.length
|
|
1190
|
+
const max = opts.maxDiagnostics
|
|
1191
|
+
const shown = max !== undefined && total > max ? finalDiagnostics.slice(0, max) : finalDiagnostics
|
|
1192
|
+
const result: CheckResult = {
|
|
1193
|
+
ok: !finalDiagnostics.some((diagnostic) => diagnostic.severity === "error"),
|
|
1194
|
+
typecheck: tc.ran ? (tc.ok ? "pass" : "fail") : "skipped",
|
|
1195
|
+
...(!tc.ran && tc.note !== undefined ? { typecheckNote: tc.note } : {}),
|
|
1196
|
+
diagnostics: shown,
|
|
1197
|
+
...(dr.pipeline !== undefined ? { pipeline: dr.pipeline } : {}),
|
|
1198
|
+
...(dr.ran
|
|
1199
|
+
? {
|
|
1200
|
+
identityPreflight: {
|
|
1201
|
+
...(dr.identityBasis !== undefined ? { basis: dr.identityBasis } : {}),
|
|
1202
|
+
...(dr.identityScanTruncated === true ? { truncated: true } : {}),
|
|
1203
|
+
duplicates: dr.duplicateInstalls,
|
|
1204
|
+
deduplicated: dr.deduplicatedInstalls ?? [],
|
|
1205
|
+
},
|
|
1206
|
+
}
|
|
1207
|
+
: {}),
|
|
1208
|
+
...(checkConfig.externalMounts.length > 0
|
|
1209
|
+
? { externalMounts: checkConfig.externalMounts }
|
|
1210
|
+
: {}),
|
|
1211
|
+
...(Object.keys(checkConfig.rules).length > 0 ? { ruleOverrides: checkConfig.rules } : {}),
|
|
1212
|
+
...(shown.length < total ? { truncated: { shown: shown.length, total } } : {}),
|
|
1213
|
+
}
|
|
1214
|
+
Object.defineProperty(result, "structuredDiagnostics", {
|
|
1215
|
+
value: finalStructured.slice(0, shown.length + structuredExtras.length),
|
|
1216
|
+
enumerable: false,
|
|
1217
|
+
})
|
|
1218
|
+
return result
|
|
1219
|
+
}
|