@nifrajs/cli 5.4.0 → 5.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/README.md +2 -1
  3. package/dist/check-scan.d.ts +6 -0
  4. package/dist/check-scan.d.ts.map +1 -1
  5. package/dist/check-scan.js +10 -10
  6. package/dist/check-scan.js.map +1 -1
  7. package/dist/check.d.ts.map +1 -1
  8. package/dist/check.js +1 -0
  9. package/dist/check.js.map +1 -1
  10. package/dist/cli.d.ts.map +1 -1
  11. package/dist/cli.js +6 -5
  12. package/dist/cli.js.map +1 -1
  13. package/dist/docs-search.d.ts +10 -1
  14. package/dist/docs-search.d.ts.map +1 -1
  15. package/dist/docs-search.js +86 -9
  16. package/dist/docs-search.js.map +1 -1
  17. package/dist/doctor.d.ts.map +1 -1
  18. package/dist/doctor.js +49 -4
  19. package/dist/doctor.js.map +1 -1
  20. package/dist/load.d.ts +4 -1
  21. package/dist/load.d.ts.map +1 -1
  22. package/dist/load.js +8 -0
  23. package/dist/load.js.map +1 -1
  24. package/dist/lock-links.d.ts.map +1 -1
  25. package/dist/lock-links.js +3 -1
  26. package/dist/lock-links.js.map +1 -1
  27. package/dist/mcp-http.js +1 -1
  28. package/dist/recipes/5.4.0.d.ts.map +1 -1
  29. package/dist/recipes/5.4.0.js +2 -0
  30. package/dist/recipes/5.4.0.js.map +1 -1
  31. package/dist/recipes/5.5.0.d.ts +9 -0
  32. package/dist/recipes/5.5.0.d.ts.map +1 -0
  33. package/dist/recipes/5.5.0.js +31 -0
  34. package/dist/recipes/5.5.0.js.map +1 -0
  35. package/dist/recipes/index.d.ts +7 -0
  36. package/dist/recipes/index.d.ts.map +1 -1
  37. package/dist/recipes/index.js +2 -0
  38. package/dist/recipes/index.js.map +1 -1
  39. package/dist/release-verification.d.ts +20 -0
  40. package/dist/release-verification.d.ts.map +1 -1
  41. package/dist/release-verification.js +62 -13
  42. package/dist/release-verification.js.map +1 -1
  43. package/dist/review.d.ts.map +1 -1
  44. package/dist/review.js +2 -0
  45. package/dist/review.js.map +1 -1
  46. package/dist/rules/codes.d.ts +2 -0
  47. package/dist/rules/codes.d.ts.map +1 -1
  48. package/dist/rules/codes.js +2 -0
  49. package/dist/rules/codes.js.map +1 -1
  50. package/dist/rules/explanations.d.ts.map +1 -1
  51. package/dist/rules/explanations.js +12 -2
  52. package/dist/rules/explanations.js.map +1 -1
  53. package/dist/rules/legacy.d.ts.map +1 -1
  54. package/dist/rules/legacy.js +63 -19
  55. package/dist/rules/legacy.js.map +1 -1
  56. package/dist/rules/security.d.ts +6 -0
  57. package/dist/rules/security.d.ts.map +1 -1
  58. package/dist/rules/security.js +152 -2
  59. package/dist/rules/security.js.map +1 -1
  60. package/dist/rules/zones.d.ts.map +1 -1
  61. package/dist/rules/zones.js +43 -1
  62. package/dist/rules/zones.js.map +1 -1
  63. package/dist/smoke.d.ts +17 -1
  64. package/dist/smoke.d.ts.map +1 -1
  65. package/dist/smoke.js +49 -0
  66. package/dist/smoke.js.map +1 -1
  67. package/dist/upgrade.d.ts +40 -12
  68. package/dist/upgrade.d.ts.map +1 -1
  69. package/dist/upgrade.js +182 -17
  70. package/dist/upgrade.js.map +1 -1
  71. package/dist/verification-plan.d.ts +4 -0
  72. package/dist/verification-plan.d.ts.map +1 -1
  73. package/dist/verification-plan.js +48 -0
  74. package/dist/verification-plan.js.map +1 -1
  75. package/dist/version-drift.d.ts +2 -1
  76. package/dist/version-drift.d.ts.map +1 -1
  77. package/dist/version-drift.js +11 -26
  78. package/dist/version-drift.js.map +1 -1
  79. package/dist/web-app-options.d.ts +1 -1
  80. package/dist/web-app-options.d.ts.map +1 -1
  81. package/dist/web-app-options.js.map +1 -1
  82. package/docs/examples.json +14 -2
  83. package/docs/llms-full.txt +358 -33
  84. package/docs/types.json +171 -47
  85. package/package.json +11 -11
  86. package/src/check-scan.ts +10 -12
  87. package/src/check.ts +1 -0
  88. package/src/cli.ts +6 -5
  89. package/src/docs-search.ts +90 -10
  90. package/src/doctor.ts +60 -4
  91. package/src/load.ts +13 -0
  92. package/src/lock-links.ts +3 -1
  93. package/src/mcp-http.ts +1 -1
  94. package/src/recipes/5.4.0.ts +2 -0
  95. package/src/recipes/5.5.0.ts +32 -0
  96. package/src/recipes/index.ts +9 -0
  97. package/src/release-verification.ts +88 -12
  98. package/src/review.ts +2 -0
  99. package/src/rules/codes.ts +2 -0
  100. package/src/rules/explanations.ts +12 -2
  101. package/src/rules/legacy.ts +75 -20
  102. package/src/rules/security.ts +171 -2
  103. package/src/rules/zones.ts +44 -1
  104. package/src/smoke.ts +70 -0
  105. package/src/upgrade.ts +199 -21
  106. package/src/verification-plan.ts +51 -0
  107. package/src/version-drift.ts +18 -26
  108. package/src/web-app-options.ts +1 -0
@@ -10,6 +10,8 @@ import { tmpdir } from "node:os"
10
10
  import { dirname, join, relative, resolve, sep } from "node:path"
11
11
  import {
12
12
  omittedVerificationGateIds,
13
+ releaseGroupGateIds,
14
+ releaseGroupNames,
13
15
  type VerificationGateSpec,
14
16
  type VerificationPlanMode,
15
17
  verificationPlan,
@@ -28,8 +30,15 @@ export interface ReleaseGateResult {
28
30
  /** The last lines a failed gate's command printed, so a CI log shows why it failed. */
29
31
  readonly output?: string
30
32
  readonly remediation: string
33
+ /** How long the gate's commands ran; absent for a gate that did not run. */
34
+ readonly durationMs?: number
31
35
  }
32
36
 
37
+ /** A gate starting, or finishing with its result, reported while verification runs. */
38
+ export type ReleaseProgressEvent =
39
+ | { readonly type: "start"; readonly id: string }
40
+ | { readonly type: "end"; readonly gate: ReleaseGateResult }
41
+
33
42
  export interface ReleaseVerificationResult {
34
43
  readonly ok: boolean
35
44
  readonly mode: ReleaseVerificationMode
@@ -38,6 +47,9 @@ export interface ReleaseVerificationResult {
38
47
  readonly omittedReleaseGateIds: readonly string[]
39
48
  /** Gates a shared runner left out; a local verification runs them. */
40
49
  readonly localGateIds: readonly string[]
50
+ /** The gates this run was limited to, when it ran only part of the plan. */
51
+ readonly selectedGateIds?: readonly string[]
52
+ readonly durationMs: number
41
53
  }
42
54
 
43
55
  export interface ReleaseCommandResult {
@@ -64,6 +76,9 @@ export interface ReleaseVerificationOptions {
64
76
  * The repository's own gate runs every gate in its plan, so a renamed script cannot drop one.
65
77
  */
66
78
  readonly requireScripts?: boolean
79
+ /** Run only these gates of the plan, in plan order; CI splits the release plan this way. */
80
+ readonly gateIds?: readonly string[]
81
+ readonly onProgress?: (event: ReleaseProgressEvent) => void
67
82
  readonly runCommand?: (spec: ReleaseCommandSpec) => Promise<ReleaseCommandResult>
68
83
  }
69
84
 
@@ -166,6 +181,7 @@ const runGate = async (
166
181
  runCommand: (spec: ReleaseCommandSpec) => Promise<ReleaseCommandResult>,
167
182
  fixtureRoot: string,
168
183
  ): Promise<ReleaseGateResult> => {
184
+ const started = performance.now()
169
185
  let lastExitCode: number | undefined
170
186
  for (const [index, args] of gate.commands.entries()) {
171
187
  const fixture = mkdtempSync(join(fixtureRoot, `${gate.id}-${index}-`))
@@ -187,6 +203,7 @@ const runGate = async (
187
203
  exitCode: result.exitCode,
188
204
  message: `${commandLabel(args)} exited with code ${result.exitCode}`,
189
205
  remediation: gate.remediation,
206
+ durationMs: performance.now() - started,
190
207
  }
191
208
  const output = outputTail(result)
192
209
  if (output !== undefined) failed.output = output
@@ -199,6 +216,7 @@ const runGate = async (
199
216
  commands: gate.commands.map(commandLabel),
200
217
  ...(lastExitCode === undefined ? {} : { exitCode: lastExitCode }),
201
218
  remediation: gate.remediation,
219
+ durationMs: performance.now() - started,
202
220
  }
203
221
  }
204
222
 
@@ -248,37 +266,51 @@ export async function collectReleaseVerification(
248
266
  const scripts = new Set(
249
267
  declared !== null && typeof declared === "object" ? Object.keys(declared) : [],
250
268
  )
251
- const plan = gatePlan(mode)
269
+ const started = performance.now()
270
+ const fullPlan = gatePlan(mode)
271
+ const selected = options.gateIds
272
+ if (selected !== undefined) {
273
+ const unknown = selected.filter((id) => !fullPlan.some((gate) => gate.id === id))
274
+ if (unknown.length > 0)
275
+ throw new Error(`the ${mode} plan has no gate named ${unknown.join(", ")}`)
276
+ }
277
+ const plan =
278
+ selected === undefined ? fullPlan : fullPlan.filter((gate) => selected.includes(gate.id))
252
279
  const local = options.sharedRunner === true ? plan.filter((gate) => !gate.workflowRequired) : []
253
280
  const gates: ReleaseGateResult[] = []
281
+ const record = (result: ReleaseGateResult): void => {
282
+ gates.push(result)
283
+ options.onProgress?.({ type: "end", gate: result })
284
+ }
254
285
  try {
255
286
  let failedId: string | undefined
256
287
  for (const gate of plan) {
257
288
  if (local.includes(gate)) continue
258
289
  if (failedId !== undefined) {
259
- gates.push(skippedGate(gate, failedId))
290
+ record(skippedGate(gate, failedId))
260
291
  continue
261
292
  }
262
293
  // The plan names the nifra repository's own scripts; a project without one has nothing to run.
263
294
  const missing = undeclaredScript(gate, scripts)
264
295
  if (missing !== undefined && options.requireScripts === true) {
265
296
  const result = missingScriptGate(gate, missing)
266
- gates.push(result)
297
+ record(result)
267
298
  failedId = result.id
268
299
  continue
269
300
  }
270
301
  if (missing !== undefined) {
271
- gates.push(undeclaredGate(gate, missing))
302
+ record(undeclaredGate(gate, missing))
272
303
  continue
273
304
  }
305
+ options.onProgress?.({ type: "start", id: gate.id })
274
306
  const result = await runGate(root, gate, runCommand, fixtureRoot)
275
- gates.push(result)
307
+ record(result)
276
308
  if (result.status === "fail") failedId = result.id
277
309
  }
278
310
  } finally {
279
311
  rmSync(fixtureRoot, { recursive: true, force: true })
280
312
  }
281
- return {
313
+ const result: ReleaseVerificationResult = {
282
314
  ok:
283
315
  gates.some((gate) => gate.status === "pass") &&
284
316
  gates.every((gate) => gate.status === "pass" || gate.status === "undeclared"),
@@ -286,14 +318,30 @@ export async function collectReleaseVerification(
286
318
  gates,
287
319
  omittedReleaseGateIds: omittedVerificationGateIds(mode),
288
320
  localGateIds: local.map((gate) => gate.id),
321
+ durationMs: performance.now() - started,
289
322
  }
323
+ return selected === undefined
324
+ ? result
325
+ : { ...result, selectedGateIds: plan.map((gate) => gate.id) }
290
326
  }
291
327
 
328
+ /** `41.2s` under a minute, `2m 31s` above. */
329
+ export function formatDuration(ms: number): string {
330
+ if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`
331
+ const seconds = Math.round(ms / 1000)
332
+ return `${Math.floor(seconds / 60)}m ${String(seconds % 60).padStart(2, "0")}s`
333
+ }
334
+
335
+ const gateMarker = (status: ReleaseGateStatus): string =>
336
+ status === "pass" ? "✓" : status === "fail" ? "✗" : "-"
337
+
338
+ const gateLine = (gate: ReleaseGateResult): string =>
339
+ `${gateMarker(gate.status)} ${gate.id}: ${gate.status}${gate.durationMs === undefined ? "" : ` (${formatDuration(gate.durationMs)})`}`
340
+
292
341
  export function renderReleaseVerification(result: ReleaseVerificationResult): string {
293
342
  const lines = [`nifra verify --${result.mode}`, ""]
294
343
  for (const gate of result.gates) {
295
- const marker = gate.status === "pass" ? "✓" : gate.status === "fail" ? "✗" : "-"
296
- lines.push(`${marker} ${gate.id}: ${gate.status}`)
344
+ lines.push(gateLine(gate))
297
345
  if (gate.message !== undefined) lines.push(` ${gate.message}`)
298
346
  if (gate.output !== undefined)
299
347
  lines.push(...gate.output.split("\n").map((line) => ` | ${line}`))
@@ -314,16 +362,31 @@ export function renderReleaseVerification(result: ReleaseVerificationResult): st
314
362
  " run `bun run check:release` locally for them.",
315
363
  )
316
364
  }
317
- lines.push("", result.ok ? "✓ verification passed" : "✗ verification failed")
365
+ if (result.selectedGateIds !== undefined) {
366
+ lines.push("", `note: this run checked only these gates: ${result.selectedGateIds.join(", ")}`)
367
+ }
368
+ lines.push(
369
+ "",
370
+ `${result.ok ? "✓ verification passed" : "✗ verification failed"} in ${formatDuration(result.durationMs)}`,
371
+ )
318
372
  return lines.join("\n")
319
373
  }
320
374
 
375
+ /** One stderr line as each gate starts and finishes, so a long run shows where it is. */
376
+ export const printReleaseProgress = (event: ReleaseProgressEvent): void => {
377
+ if (event.type === "start") console.error(`> ${event.id}: running`)
378
+ else console.error(gateLine(event.gate))
379
+ }
380
+
321
381
  /** Run verification and render either the human or machine interface. */
322
382
  export async function runReleaseVerification(
323
383
  cwd: string,
324
384
  options: ReleaseVerificationOptions & { readonly json?: boolean } = {},
325
385
  ): Promise<boolean> {
326
- const result = await collectReleaseVerification(cwd, options)
386
+ const result = await collectReleaseVerification(cwd, {
387
+ ...options,
388
+ onProgress: options.onProgress ?? printReleaseProgress,
389
+ })
327
390
  if (options.json) console.log(JSON.stringify(result, null, 2))
328
391
  else console.log(renderReleaseVerification(result))
329
392
  return result.ok
@@ -331,11 +394,24 @@ export async function runReleaseVerification(
331
394
 
332
395
  if (import.meta.main) {
333
396
  const mode: ReleaseVerificationMode = process.argv.includes("--release") ? "release" : "default"
334
- const ok = await runReleaseVerification(process.cwd(), {
397
+ const groupAt = process.argv.indexOf("--group")
398
+ const group = groupAt === -1 ? undefined : process.argv[groupAt + 1]
399
+ const gateIds = group === undefined ? undefined : releaseGroupGateIds(group)
400
+ if (groupAt !== -1 && (mode !== "release" || gateIds === undefined)) {
401
+ console.error(
402
+ `--group needs --release and one of: ${releaseGroupNames().join(", ")} (got ${group ?? "nothing"})`,
403
+ )
404
+ process.exit(2)
405
+ }
406
+ const options = {
335
407
  mode,
336
408
  sharedRunner: process.argv.includes("--shared-runner"),
337
409
  requireScripts: true,
338
410
  json: process.argv.includes("--json"),
339
- })
411
+ }
412
+ const ok = await runReleaseVerification(
413
+ process.cwd(),
414
+ gateIds === undefined ? options : { ...options, gateIds },
415
+ )
340
416
  if (!ok) process.exitCode = 1
341
417
  }
package/src/review.ts CHANGED
@@ -157,6 +157,7 @@ export const CHECK_CODES: Readonly<Record<string, ReviewCheckId>> = {
157
157
  "NF-C043": "security",
158
158
  "NF-C044": "route-boundary",
159
159
  "NF-C045": "typed-client",
160
+ "NF-C046": "dependency",
160
161
  "NF-D001": "dependency",
161
162
  "NF-D002": "dependency",
162
163
  "NF-D003": "dependency",
@@ -174,6 +175,7 @@ export const CHECK_CODES: Readonly<Record<string, ReviewCheckId>> = {
174
175
  "NF-S006": "security",
175
176
  "NF-S007": "security",
176
177
  "NF-S008": "security",
178
+ "NF-S009": "security",
177
179
  }
178
180
 
179
181
  const REVIEW_INPUT_SCHEMA = {
@@ -42,6 +42,7 @@ export const RULE_CODES = Object.freeze({
42
42
  "NF-C043": "Merged routes skip the parent's authentication",
43
43
  "NF-C044": "createWebApp passes no copy chunks",
44
44
  "NF-C045": "Route registered outside the typed chain",
45
+ "NF-C046": "Identity-sensitive version skew",
45
46
  "NF-C020": "Island enhancer cleanup check",
46
47
  "NF-C021": "nano binding cleanup check",
47
48
  "NF-C022": "nano bindList key check",
@@ -63,6 +64,7 @@ export const RULE_CODES = Object.freeze({
63
64
  "NF-S006": "Security escape hatch enabled",
64
65
  "NF-S007": "Secure cookie without a __Host-/__Secure- prefix",
65
66
  "NF-S008": "Authenticated route validates input before authentication",
67
+ "NF-S009": "WebSocket frames parsed without a messageSchema",
66
68
  } as const)
67
69
 
68
70
  /** Codes that no longer fire but remain reserved forever. */
@@ -55,7 +55,7 @@ export const RULE_EXPLANATIONS: Readonly<Record<BuiltInCode, RuleExplanation>> =
55
55
  docs: "/docs/troubleshooting",
56
56
  },
57
57
  "NF-C009": {
58
- why: "A package resolves to more than one physical copy, so module-level state (contexts, registries, instanceof checks) splits between them.",
58
+ why: "A package resolves to more than one physical copy of one version, so module-level state (contexts, registries, instanceof checks) splits between them. Copies at different versions are NF-C046.",
59
59
  fix: "Deduplicate the installs so each resolves to one path, or declare the package single-copy in package.json's nifra.singleCopy and preload the register module.",
60
60
  docs: "/docs/troubleshooting",
61
61
  },
@@ -155,7 +155,7 @@ export const RULE_EXPLANATIONS: Readonly<Record<BuiltInCode, RuleExplanation>> =
155
155
  },
156
156
  "NF-C028": {
157
157
  why: "A file imports across a zone boundary the project declares, such as browser code reaching backend code, or the zone configuration itself is invalid.",
158
- fix: "Import through the boundary's public entry, or move the code to the zone that may use it.",
158
+ fix: 'Import through the boundary\'s public entry, or move the code to the zone that may use it. A frontend module backend code needs can be declared shared where it lives (a .shared suffix, or a "nifra.zones" shared entry) when its own imports are shared-safe; the finding says whether they are.',
159
159
  docs: "/docs/structure",
160
160
  },
161
161
  "NF-C029": {
@@ -248,6 +248,11 @@ export const RULE_EXPLANATIONS: Readonly<Record<BuiltInCode, RuleExplanation>> =
248
248
  fix: "Chain the registration onto the server's declaration, or declare the routes on their own server() and merge() it. A route kept off the type on purpose takes `// nifra-expect NF-C045: <reason>` above the statement.",
249
249
  docs: "/docs/api#typed-client",
250
250
  },
251
+ "NF-C046": {
252
+ why: "A package resolves to copies at more than one version, often one in a linked sibling repository that installs its own. Module state splits as with NF-C009, and the two halves can also disagree on behavior. A singleCopy declaration only collapses copies of one version, so it cannot cover this.",
253
+ fix: "Install one version everywhere: align the ranges in every install root that carries a copy, or for nifra packages run `nifra upgrade <version>` in this app and in the linked repository, then install in each.",
254
+ docs: "/docs/troubleshooting",
255
+ },
251
256
  "NF-D001": {
252
257
  why: "The doctor gate of `nifra assure` found an undeclared import or a package installed more than once.",
253
258
  fix: "Run `nifra doctor` for the details and the fix of each finding.",
@@ -336,4 +341,9 @@ export const RULE_EXPLANATIONS: Readonly<Record<BuiltInCode, RuleExplanation>> =
336
341
  fix: 'Authenticate with app.authenticate(), which runs before validation, or set `validationOrder: "auth-before-validation"` on the route.',
337
342
  docs: "/docs/auth",
338
343
  },
344
+ "NF-S009": {
345
+ why: "An app.ws() route parses frames itself in message() with no messageSchema, so a client's frame reaches the handler unvalidated and the typed client's send() is untyped.",
346
+ fix: "Declare messageSchema (a discriminated union for several frame kinds): message() receives the parsed, validated value and invalid frames go to onInvalidMessage.",
347
+ docs: "/docs/websockets",
348
+ },
339
349
  })
@@ -26,6 +26,7 @@ import { createWebAppProbe, withApiKindHint } from "../internal/nifra-project.ts
26
26
  import { unsupportedTypeScriptDiagnostic } from "../internal/typescript-import.ts"
27
27
  import { linkLockUpdate, staleLinkLockMessage } from "../lock-links.ts"
28
28
  import { zoneFolderOf } from "../typecheck-coverage.ts"
29
+ import { compareSemverSpec, isFixedGroup } from "../upgrade.ts"
29
30
  import { versionDriftMessage } from "../version-drift.ts"
30
31
  import { MISSING_EXPECTATION_REASON } from "./comment-markers.ts"
31
32
  import type { CheckRule, RuleContext } from "./index.ts"
@@ -42,6 +43,7 @@ export const LEGACY_RULE_CODES: Readonly<Record<string, string>> = Object.freeze
42
43
  "response-route": "NF-C007",
43
44
  "undeclared-dependency": "NF-C008",
44
45
  "duplicate-install": "NF-C009",
46
+ "version-skew": "NF-C046",
45
47
  "stale-workspace-dist": "NF-C010",
46
48
  pipeline: "NF-C011",
47
49
  "server-manifest-drift": "NF-C012",
@@ -62,6 +64,7 @@ const TITLES: Readonly<Record<string, string>> = Object.freeze({
62
64
  "response-route": "Raw response route advisory",
63
65
  "undeclared-dependency": "Undeclared dependency check",
64
66
  "duplicate-install": "Duplicate install check",
67
+ "version-skew": "Identity-sensitive version skew",
65
68
  "stale-workspace-dist": "Stale workspace build check",
66
69
  pipeline: "Build pipeline check",
67
70
  "server-manifest-drift": "Server manifest drift check",
@@ -84,6 +87,7 @@ export const LEGACY_RULE_ORDER: readonly string[] = Object.freeze([
84
87
  "response-route",
85
88
  "undeclared-dependency",
86
89
  "duplicate-install",
90
+ "version-skew",
87
91
  "stale-workspace-dist",
88
92
  "pipeline",
89
93
  "server-manifest-drift",
@@ -664,6 +668,15 @@ function copyLines(finding: DuplicateInstallFinding): string[] {
664
668
  )
665
669
  }
666
670
 
671
+ const provenanceSteps = (group: readonly DuplicateInstallFinding[]): string[] =>
672
+ group.flatMap((finding) =>
673
+ finding.provenance === undefined
674
+ ? []
675
+ : [
676
+ `Planted links${group.length === 1 ? "" : ` (${finding.package})`}: ${finding.provenance} Try this before the fixes below.`,
677
+ ],
678
+ )
679
+
667
680
  /** One fix for duplicates that share a cause and topology, so a linked sibling repository that
668
681
  * duplicates every package reads as one finding instead of one paragraph per package. */
669
682
  function duplicateSuggestion(group: readonly DuplicateInstallFinding[]): DiagnosticSuggestion {
@@ -684,27 +697,49 @@ function duplicateSuggestion(group: readonly DuplicateInstallFinding[]): Diagnos
684
697
  ].join("\n"),
685
698
  steps: [
686
699
  ...group.flatMap(copyLines).map((line) => `Copy: ${line}`),
687
- ...group.flatMap((finding) =>
688
- finding.provenance === undefined
689
- ? []
690
- : [
691
- `Planted links${group.length === 1 ? "" : ` (${finding.package})`}: ${finding.provenance} Try this before the fixes below.`,
692
- ],
693
- ),
700
+ ...provenanceSteps(group),
694
701
  "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.",
695
- `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.${group.some((finding) => finding.cause === "version-skew") ? " A declaration only covers same-version duplicates, so fix 1's range alignment must land first." : ""}`,
702
+ "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.",
696
703
  "Re-run `nifra check`; the gate stays failing until one fix lands.",
697
704
  ],
698
705
  }
699
706
  }
700
707
 
708
+ /** A version skew has one fix, one version: a singleCopy declaration never redirects across versions. */
709
+ function skewSuggestion(group: readonly DuplicateInstallFinding[]): DiagnosticSuggestion {
710
+ const newest = group
711
+ .flatMap((finding) => finding.versions)
712
+ .reduce<string | undefined>(
713
+ (best, version) =>
714
+ best === undefined || compareSemverSpec(version, best) > 0 ? version : best,
715
+ undefined,
716
+ )
717
+ const align = group.every((finding) => isFixedGroup(finding.package))
718
+ ? `Upgrade each install that is behind to one nifra version (the newest here is ${newest}): \`nifra upgrade ${newest}\` in this app, and in a linked repository on its own, then install in each.`
719
+ : "Align dependency and peer ranges on one version in every install root that carries a copy, then install in each."
720
+ return {
721
+ kind: "manual",
722
+ title:
723
+ group.length === 1
724
+ ? `Install ${group[0]?.package} at one version`
725
+ : `Install each of ${group.length} packages at one version`,
726
+ steps: [
727
+ ...group.flatMap(copyLines).map((line) => `Copy: ${line}`),
728
+ ...provenanceSteps(group),
729
+ align,
730
+ "A singleCopy declaration does not cover this: it only collapses copies of one version.",
731
+ "Re-run `nifra check`; the gate stays failing until every copy is at one version.",
732
+ ],
733
+ }
734
+ }
735
+
701
736
  function duplicateDiagnostic(group: readonly DuplicateInstallFinding[]): Diagnostic | undefined {
702
737
  const first = group[0]
703
738
  if (first === undefined) return undefined
704
739
  const context = `${first.topology === undefined ? "" : `. Topology: ${first.topology}`}${first.scope === undefined ? "" : `. Scope: ${first.scope}`}`
705
740
  const skew = first.cause === "version-skew"
706
741
  const names = group.map((finding) => finding.package)
707
- return legacyDiagnostic("duplicate-install", {
742
+ return legacyDiagnostic(skew ? "version-skew" : "duplicate-install", {
708
743
  severity: "error",
709
744
  message:
710
745
  group.length === 1
@@ -715,10 +750,30 @@ function duplicateDiagnostic(group: readonly DuplicateInstallFinding[]): Diagnos
715
750
  ? first.remediation
716
751
  : `Deduplicate so each resolves to a single physical path, or declare them single-copy: add "nifra": { "singleCopy": [${names.map((name) => `"${name}"`).join(", ")}] } to package.json and preload "${SINGLE_COPY_REGISTER_SPECIFIER}" from bunfig.toml.`,
717
752
  evidence: group.flatMap(copyLines),
718
- suggestion: duplicateSuggestion(group),
753
+ suggestion: skew ? skewSuggestion(group) : duplicateSuggestion(group),
719
754
  })
720
755
  }
721
756
 
757
+ /**
758
+ * The identity preflight's findings of one cause as diagnostics. Duplicates with one cause and one
759
+ * layout (every package a linked sibling repo installs again) have one fix, so they are one finding;
760
+ * `identityPreflight` in --json keeps each package.
761
+ */
762
+ function identityDiagnostics(
763
+ ctx: RuleContext,
764
+ cause: DuplicateInstallFinding["cause"],
765
+ ): readonly Diagnostic[] {
766
+ const doctor = ctx.project.packages.doctor
767
+ if (!doctor.ran) return []
768
+ const groups = new Map<string, DuplicateInstallFinding[]>()
769
+ for (const finding of doctor.duplicateInstalls) {
770
+ if (finding.cause !== cause) continue
771
+ const key = [finding.topology ?? "", finding.scope ?? ""].join("\0")
772
+ groups.set(key, [...(groups.get(key) ?? []), finding])
773
+ }
774
+ return [...groups.values()].flatMap((group) => duplicateDiagnostic(group) ?? [])
775
+ }
776
+
722
777
  const doctorRules: readonly CheckRule[] = Object.freeze([
723
778
  {
724
779
  code: LEGACY_RULE_CODES["undeclared-dependency"]!,
@@ -746,16 +801,16 @@ const doctorRules: readonly CheckRule[] = Object.freeze([
746
801
  code: LEGACY_RULE_CODES["duplicate-install"]!,
747
802
  title: TITLES["duplicate-install"]!,
748
803
  async scan(ctx: RuleContext) {
749
- const doctor = ctx.project.packages.doctor
750
- if (!doctor.ran) return []
751
- // Duplicates with one cause and one layout (every package a linked sibling repo installs again)
752
- // have one fix, so they are one finding; `identityPreflight` in --json keeps each package.
753
- const groups = new Map<string, DuplicateInstallFinding[]>()
754
- for (const finding of doctor.duplicateInstalls) {
755
- const key = [finding.cause, finding.topology ?? "", finding.scope ?? ""].join("\0")
756
- groups.set(key, [...(groups.get(key) ?? []), finding])
757
- }
758
- return [...groups.values()].flatMap((group) => duplicateDiagnostic(group) ?? [])
804
+ return identityDiagnostics(ctx, "duplicate-path")
805
+ },
806
+ },
807
+ // Its own code so a severity override that quiets same-version duplicates never quiets a skew,
808
+ // which no declaration can cover.
809
+ {
810
+ code: LEGACY_RULE_CODES["version-skew"]!,
811
+ title: TITLES["version-skew"]!,
812
+ async scan(ctx: RuleContext) {
813
+ return identityDiagnostics(ctx, "version-skew")
759
814
  },
760
815
  },
761
816
  {
@@ -29,7 +29,8 @@ function didNotRun(code: string, title: string): readonly Diagnostic[] {
29
29
  ]
30
30
  }
31
31
 
32
- const SECRET = /(?:token|secret|apiKey|api_key|signature|hmac|password)/i
32
+ const SECRET =
33
+ /(?:token|secret|apiKey|api_key|signature|hmac|password|(?:service|private|signing|master|encryption)_?key)/i
33
34
  const PII = /(?:email|phone|ssn|password|token|authorization)/i
34
35
  // Retired in 5.0.0: it silenced any security finding without a reason. It now silences nothing and
35
36
  // only makes the finding name the form that replaced it.
@@ -321,6 +322,76 @@ function isConfigRead(ts: typeof TSApi, node: TSApi.Expression): boolean {
321
322
  return CONTEXT_NAMES.has(owner.text) && CONFIG_KEY.test(key) && isParameterRef(ts, owner)
322
323
  }
323
324
 
325
+ /**
326
+ * The initializer of the `const` that `id` names, when that const is the nearest binding of the name.
327
+ * A parameter, a loop or catch variable, a `let` or a function in between disproves it.
328
+ */
329
+ function constInitializer(ts: typeof TSApi, id: TSApi.Identifier): TSApi.Expression | undefined {
330
+ for (let node: TSApi.Node | undefined = id.parent; node !== undefined; node = node.parent) {
331
+ if (ts.isFunctionLike(node) && node.parameters.some((p) => bindsName(ts, p.name, id.text)))
332
+ return undefined
333
+ if (
334
+ (ts.isForStatement(node) || ts.isForOfStatement(node) || ts.isForInStatement(node)) &&
335
+ node.initializer !== undefined &&
336
+ ts.isVariableDeclarationList(node.initializer) &&
337
+ node.initializer.declarations.some((d) => bindsName(ts, d.name, id.text))
338
+ )
339
+ return undefined
340
+ if (
341
+ ts.isCatchClause(node) &&
342
+ node.variableDeclaration !== undefined &&
343
+ bindsName(ts, node.variableDeclaration.name, id.text)
344
+ )
345
+ return undefined
346
+ if (!ts.isBlock(node) && !ts.isSourceFile(node)) continue
347
+ for (const statement of node.statements) {
348
+ if (!ts.isVariableStatement(statement)) continue
349
+ const constant = (statement.declarationList.flags & ts.NodeFlags.Const) !== 0
350
+ for (const declaration of statement.declarationList.declarations) {
351
+ if (!bindsName(ts, declaration.name, id.text)) continue
352
+ return constant && ts.isIdentifier(declaration.name) ? declaration.initializer : undefined
353
+ }
354
+ }
355
+ if (declaresIn(ts, node.statements, id.text)) return undefined
356
+ }
357
+ return undefined
358
+ }
359
+
360
+ /**
361
+ * Whether `node` holds deployment configuration: a read {@link isConfigRead} accepts, or a `const`
362
+ * initialized from one (`const key = process.env.KEY`), through parentheses, `as`, `!`, a `.trim()` and
363
+ * a `??`/`||` string default.
364
+ */
365
+ function isConfigValue(ts: typeof TSApi, node: TSApi.Expression, depth = 0): boolean {
366
+ if (depth > 8) return false
367
+ if (
368
+ ts.isParenthesizedExpression(node) ||
369
+ ts.isAsExpression(node) ||
370
+ ts.isNonNullExpression(node) ||
371
+ ts.isSatisfiesExpression(node)
372
+ )
373
+ return isConfigValue(ts, node.expression, depth + 1)
374
+ if (
375
+ ts.isBinaryExpression(node) &&
376
+ (node.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken ||
377
+ node.operatorToken.kind === ts.SyntaxKind.BarBarToken) &&
378
+ ts.isStringLiteralLike(node.right)
379
+ )
380
+ return isConfigValue(ts, node.left, depth + 1)
381
+ if (
382
+ ts.isCallExpression(node) &&
383
+ node.arguments.length === 0 &&
384
+ ts.isPropertyAccessExpression(node.expression) &&
385
+ node.expression.name.text === "trim"
386
+ )
387
+ return isConfigValue(ts, node.expression.expression, depth + 1)
388
+ if (ts.isIdentifier(node)) {
389
+ const initializer = constInitializer(ts, node)
390
+ return initializer !== undefined && isConfigValue(ts, initializer, depth + 1)
391
+ }
392
+ return isConfigRead(ts, node)
393
+ }
394
+
324
395
  function secretComparisons(
325
396
  ts: typeof TSApi,
326
397
  tree: TSApi.SourceFile,
@@ -344,7 +415,7 @@ function secretComparisons(
344
415
  if (
345
416
  (isSecretName(left) || isSecretName(right)) &&
346
417
  !isClientConfirmationPair(browser, left, right) &&
347
- !(isConfigRead(ts, node.left) && isConfigRead(ts, node.right))
418
+ !(isConfigValue(ts, node.left) && isConfigValue(ts, node.right))
348
419
  ) {
349
420
  const line = tree.getLineAndCharacterOfPosition(node.getStart(tree)).line + 1
350
421
  found.push({ node, left, right, line })
@@ -976,6 +1047,103 @@ export const inputBeforeAuthenticationRule: CheckRule = {
976
1047
  },
977
1048
  }
978
1049
 
1050
+ function propertyName(ts: typeof TSApi, prop: TSApi.ObjectLiteralElementLike): string | undefined {
1051
+ if (ts.isSpreadAssignment(prop)) return undefined
1052
+ return ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : undefined
1053
+ }
1054
+
1055
+ /** The `message` handler of an `app.ws()` handler object, when it is written inline. */
1056
+ function wsMessageHandler(
1057
+ ts: typeof TSApi,
1058
+ handler: TSApi.ObjectLiteralExpression,
1059
+ ): TSApi.Node | undefined {
1060
+ for (const prop of handler.properties) {
1061
+ if (propertyName(ts, prop) !== "message") continue
1062
+ if (ts.isMethodDeclaration(prop)) return prop.body
1063
+ if (ts.isPropertyAssignment(prop)) {
1064
+ const fn = prop.initializer
1065
+ if (ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)) return fn.body
1066
+ }
1067
+ }
1068
+ return undefined
1069
+ }
1070
+
1071
+ function callsJsonParse(ts: typeof TSApi, node: TSApi.Node): boolean {
1072
+ if (
1073
+ ts.isCallExpression(node) &&
1074
+ ts.isPropertyAccessExpression(node.expression) &&
1075
+ node.expression.name.text === "parse" &&
1076
+ ts.isIdentifier(node.expression.expression) &&
1077
+ node.expression.expression.text === "JSON"
1078
+ ) {
1079
+ return true
1080
+ }
1081
+ return ts.forEachChild(node, (child) => (callsJsonParse(ts, child) ? true : undefined)) === true
1082
+ }
1083
+
1084
+ /**
1085
+ * An `app.ws()` route whose `message()` parses frames itself has no `messageSchema`, so a client's
1086
+ * frame reaches the handler unvalidated and the typed client's `send()` is untyped. Only an inline
1087
+ * handler object with no spread is judged: a spread may carry the schema.
1088
+ */
1089
+ export const unvalidatedWsFrameRule: CheckRule = {
1090
+ code: "NF-S009",
1091
+ title: "WebSocket frames parsed without a messageSchema",
1092
+ async scan(ctx) {
1093
+ const loaded = await loadRuleTypeScript(ctx)
1094
+ if (loaded.diagnostics !== undefined) return loaded.diagnostics
1095
+ const ts = loaded.compiler
1096
+ if (ts === undefined) return didNotRun("NF-S009", "WebSocket messageSchema scan")
1097
+ const findings: Diagnostic[] = []
1098
+ for (const file of ctx.project.source.files) {
1099
+ const parsed = parsedFile(ts, ctx.project.source, file)
1100
+ if (parsed === undefined) continue
1101
+ const { tree, lines } = parsed
1102
+ const visit = (node: TSApi.Node): void => {
1103
+ if (
1104
+ ts.isCallExpression(node) &&
1105
+ ts.isPropertyAccessExpression(node.expression) &&
1106
+ node.expression.name.text === "ws"
1107
+ ) {
1108
+ const [path, handler] = node.arguments
1109
+ if (
1110
+ path !== undefined &&
1111
+ ts.isStringLiteralLike(path) &&
1112
+ handler !== undefined &&
1113
+ ts.isObjectLiteralExpression(handler) &&
1114
+ !handler.properties.some(
1115
+ (prop) => ts.isSpreadAssignment(prop) || propertyName(ts, prop) === "messageSchema",
1116
+ )
1117
+ ) {
1118
+ const body = wsMessageHandler(ts, handler)
1119
+ if (body !== undefined && callsJsonParse(ts, body)) {
1120
+ const line =
1121
+ tree.getLineAndCharacterOfPosition(node.expression.name.getStart(tree)).line + 1
1122
+ const reviewed = expectedReason(lines, line, "NF-S009") !== undefined
1123
+ findings.push(
1124
+ diagnostic({
1125
+ code: "NF-S009",
1126
+ severity: "info",
1127
+ file,
1128
+ line,
1129
+ message: reviewed
1130
+ ? `ws("${path.text}") parsing its own frames is expected here`
1131
+ : `ws("${path.text}") parses frames with JSON.parse in message() and declares no messageSchema, so a client's frame reaches the handler unvalidated and the typed client's send() takes unknown. Declare messageSchema: message() then receives the parsed, validated value, invalid frames go to onInvalidMessage, and send() is typed from it`,
1132
+ evidence: [path.text, ...expectationEvidence(lines, line, "NF-S009")],
1133
+ verify: "nifra check --lints-only",
1134
+ }),
1135
+ )
1136
+ }
1137
+ }
1138
+ }
1139
+ ts.forEachChild(node, visit)
1140
+ }
1141
+ visit(tree)
1142
+ }
1143
+ return findings
1144
+ },
1145
+ }
1146
+
979
1147
  export const securityRules = Object.freeze([
980
1148
  failOpenGateRule,
981
1149
  secretComparisonRule,
@@ -985,4 +1153,5 @@ export const securityRules = Object.freeze([
985
1153
  assuranceEscapeHatchRule,
986
1154
  unprefixedSecureCookieRule,
987
1155
  inputBeforeAuthenticationRule,
1156
+ unvalidatedWsFrameRule,
988
1157
  ])