prunelle 0.6.0 → 0.7.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/LICENSE +21 -0
- package/llms.txt +48 -43
- package/package.json +4 -1
- package/src/a11y/declaration.ts +106 -72
- package/src/a11y/index.ts +59 -39
- package/src/a11y/rgaa-map.ts +95 -49
- package/src/build/bundle.ts +8 -4
- package/src/build/byte-size.ts +11 -0
- package/src/build/client-plugin.ts +3 -1
- package/src/build/compile.ts +2 -1
- package/src/build/ecoindex.ts +15 -14
- package/src/build/files.ts +6 -0
- package/src/build/first-load.ts +83 -11
- package/src/build/graph.ts +29 -39
- package/src/build/index.ts +57 -18
- package/src/build/island-promote.ts +229 -0
- package/src/build/islands.ts +9 -201
- package/src/build/manifest.ts +4 -125
- package/src/build/plugin-host.ts +21 -8
- package/src/build/precompress.ts +1 -1
- package/src/build/prerender.ts +97 -44
- package/src/build/reach.ts +136 -0
- package/src/build/render-rules.ts +2 -2
- package/src/build/report.ts +19 -3
- package/src/build/static-headers.ts +93 -0
- package/src/build/static.ts +2 -0
- package/src/cli/check-forms.ts +97 -48
- package/src/cli/check-imports.ts +25 -0
- package/src/cli/check-links.ts +2 -2
- package/src/cli/check-security.ts +64 -0
- package/src/cli/check.ts +33 -7
- package/src/cli/commands.ts +35 -7
- package/src/cli/docs.ts +4 -3
- package/src/cli/inspect.ts +2 -1
- package/src/cli/mcp-tools.ts +7 -5
- package/src/cli/mcp.ts +1 -1
- package/src/cli/new.ts +14 -3
- package/src/cli/render.ts +14 -19
- package/src/cli/upgrade.ts +22 -5
- package/src/compiler/analyze.ts +26 -5
- package/src/compiler/cacheability.ts +2 -2
- package/src/compiler/compliance-eco.ts +71 -0
- package/src/compiler/compliance-rgaa.ts +110 -4
- package/src/compiler/compliance-urls.ts +145 -0
- package/src/compiler/compliance.ts +168 -116
- package/src/compiler/foreign-imports.ts +88 -0
- package/src/compiler/mistakes.ts +19 -1
- package/src/compiler/props-body.ts +52 -0
- package/src/compiler/shared.ts +2 -2
- package/src/compiler/ssr.ts +2 -2
- package/src/context.ts +34 -0
- package/src/dev/error-log.ts +90 -64
- package/src/dev/host-check.ts +26 -0
- package/src/dev/index.ts +12 -5
- package/src/dev/open-editor.ts +15 -11
- package/src/dev/protocol.ts +2 -0
- package/src/dev/supervisor.ts +8 -0
- package/src/dev/watchers.ts +27 -2
- package/src/dom/action.ts +4 -1
- package/src/dom/extras.ts +1 -2
- package/src/dom/index.ts +13 -2
- package/src/dom/island.ts +22 -10
- package/src/dom/loop.ts +25 -16
- package/src/eco/declaration.ts +257 -0
- package/src/eco/index.ts +65 -0
- package/src/index.ts +2 -2
- package/src/jsx-runtime.ts +2 -2
- package/src/plugins/config.ts +1 -1
- package/src/plugins/context.ts +16 -1
- package/src/plugins/load.ts +4 -3
- package/src/plugins/public.ts +2 -2
- package/src/plugins/services.ts +3 -0
- package/src/plugins/types.ts +17 -2
- package/src/server/action-flash.ts +158 -0
- package/src/server/action-protect.ts +38 -37
- package/src/server/action.ts +11 -127
- package/src/server/app-secret.ts +63 -0
- package/src/server/compress.ts +5 -1
- package/src/server/consent.ts +59 -22
- package/src/server/cookies.ts +16 -2
- package/src/server/env.ts +14 -0
- package/src/server/errors.ts +3 -1
- package/src/server/form-schema.ts +1 -1
- package/src/server/health.ts +46 -15
- package/src/server/http.ts +47 -7
- package/src/server/index.ts +52 -30
- package/src/server/loader.ts +6 -2
- package/src/server/plugin-host.ts +3 -1
- package/src/server/public.ts +4 -3
- package/src/server/rate-limit.ts +52 -9
- package/src/server/route-cache.ts +26 -4
- package/src/server/route-table.ts +7 -3
- package/src/server/routing.ts +3 -87
- package/src/server/sanitize-html.ts +309 -0
- package/src/server/security.ts +71 -20
- package/src/server/serve-handlers.ts +14 -4
- package/src/server/start.ts +1 -1
- package/src/server/static-dir.ts +27 -4
- package/src/server/stream.ts +28 -6
- package/src/ssr/consent-banner.ts +58 -0
- package/src/ssr/context.ts +20 -4
- package/src/ssr/index.ts +18 -0
- package/src/ssr/navigation.ts +2 -2
- package/src/style.ts +32 -1
- package/templates/_shared/gitignore +5 -0
- package/templates/_shared/src/routes/legal.tsx +10 -1
- package/templates/app/.env.example +4 -0
- package/templates/app/package.json +2 -1
- package/templates/app/prunelle.config.ts +2 -0
- package/templates/app/src/auth.ts +4 -6
- package/templates/app/src/mail.ts +4 -0
- package/templates/app/src/routes/_layout.tsx +9 -1
- package/templates/app/src/routes/dashboard/index.tsx +42 -8
- package/templates/app/src/routes/login.tsx +49 -30
- package/templates/app/src/routes/privacy.tsx +25 -0
- package/templates/app/src/styles/app.css +8 -1
- package/templates/app/tests/app.test.ts +44 -3
- package/templates/blog/package.json +1 -1
- package/templates/blog/src/routes/_layout.tsx +6 -1
- package/templates/blog/src/routes/index.tsx +1 -1
- package/templates/blog/src/styles/app.css +6 -1
- package/templates/fullstack/package.json +1 -1
- package/templates/fullstack/src/components/GreetForm.tsx +2 -1
- package/templates/fullstack/src/routes/_layout.tsx +4 -0
- package/templates/fullstack/src/styles/app.css +11 -1
- package/templates/minimal/package.json +1 -1
- package/templates/minimal/src/routes/_layout.tsx +4 -0
- package/templates/minimal/src/styles/app.css +11 -1
package/src/cli/check-forms.ts
CHANGED
|
@@ -6,19 +6,22 @@
|
|
|
6
6
|
import type { JSXAttribute, JSXElement, Node, Program } from 'oxc-parser'
|
|
7
7
|
import type { ModuleGraph } from '../build/graph'
|
|
8
8
|
import type { ModuleAnalysis } from '../compiler/analyze'
|
|
9
|
+
import type { ComplianceConfig, FormWarningRule } from '../compiler/compliance'
|
|
9
10
|
import type { ServerAction } from '../server/action'
|
|
10
11
|
import { readFileSync } from 'node:fs'
|
|
11
12
|
import { basename, dirname } from 'node:path'
|
|
12
13
|
import { isInNodeModules, isTsFile, relPosix } from '../build/files'
|
|
14
|
+
import { resolveExportTarget } from '../build/island-promote'
|
|
13
15
|
import { isInside } from '../build/is-inside'
|
|
14
16
|
import { resolvePrunelleSpecifier } from '../build/resolve'
|
|
15
17
|
import { walk } from '../compiler/ast'
|
|
18
|
+
import { isIgnoredAt, isRuleIgnored, parsePrunelleIgnores } from '../compiler/compliance'
|
|
16
19
|
import { calleeName, formatDiagnostic, formatLoc, isComponentTag, jsxTagName, resolvePrunelleTag, unwrapTsExpr } from '../compiler/shared'
|
|
17
20
|
import { staticLiteralOrTemplate, staticOptionText } from '../compiler/ssr-helpers'
|
|
18
21
|
import { closestName } from '../plugins/config'
|
|
19
22
|
import { isServerAction } from '../server/action'
|
|
20
23
|
import { FORM_TIMESTAMP_FIELD, honeypotFieldName } from '../server/action-protect'
|
|
21
|
-
import { extractFormSchema, lookupFieldConstraint } from '../server/form-schema'
|
|
24
|
+
import { extractFormSchema, isRecord, lookupFieldConstraint } from '../server/form-schema'
|
|
22
25
|
|
|
23
26
|
export interface FormCheckInput {
|
|
24
27
|
root: string
|
|
@@ -27,8 +30,13 @@ export interface FormCheckInput {
|
|
|
27
30
|
graph: ModuleGraph
|
|
28
31
|
/** Optional pre-read source map (falls back to `graph.source(file)`). */
|
|
29
32
|
sources?: ReadonlyMap<string, string> | undefined
|
|
33
|
+
/** `compliance.ignore` silences a form warning across the app. */
|
|
34
|
+
compliance?: ComplianceConfig | undefined
|
|
30
35
|
}
|
|
31
36
|
|
|
37
|
+
/** Emits a form warning unless `compliance.ignore` or a `prunelle-ignore` comment at that place silences it; says whether it did. */
|
|
38
|
+
type WarnAt = (rule: FormWarningRule, file: string, offset: number, message: string) => boolean
|
|
39
|
+
|
|
32
40
|
export interface FormCheckResult {
|
|
33
41
|
errors: string[]
|
|
34
42
|
warnings: string[]
|
|
@@ -58,15 +66,28 @@ async function tryDirectImport(file: string, hash: string): Promise<Record<strin
|
|
|
58
66
|
catch { return undefined }
|
|
59
67
|
}
|
|
60
68
|
|
|
61
|
-
|
|
62
|
-
|
|
69
|
+
// An action module's exports, or why it would not import.
|
|
70
|
+
type LoadedModule = { mod: Record<string, unknown> } | { failure: string }
|
|
71
|
+
|
|
72
|
+
const messageOf = (error: unknown): string => error instanceof AggregateError && error.errors.length > 0
|
|
73
|
+
? error.errors.map(messageOf).join('; ')
|
|
74
|
+
: error instanceof Error ? error.message : String(error)
|
|
75
|
+
|
|
76
|
+
async function loadActionModule(file: string, cache: Map<string, LoadedModule>): Promise<LoadedModule> {
|
|
77
|
+
const cached = cache.get(file)
|
|
78
|
+
if (cached !== undefined) return cached
|
|
79
|
+
const loaded = await importActionModule(file)
|
|
80
|
+
cache.set(file, loaded)
|
|
81
|
+
return loaded
|
|
82
|
+
}
|
|
63
83
|
|
|
84
|
+
async function importActionModule(file: string): Promise<LoadedModule> {
|
|
64
85
|
let hash = '0'
|
|
65
86
|
try { hash = Bun.hash(readFileSync(file)).toString(36) }
|
|
66
|
-
catch
|
|
87
|
+
catch (error) { return { failure: messageOf(error) } }
|
|
67
88
|
|
|
68
89
|
const direct = await tryDirectImport(file, hash)
|
|
69
|
-
if (direct !== undefined) {
|
|
90
|
+
if (direct !== undefined) return { mod: direct }
|
|
70
91
|
|
|
71
92
|
try {
|
|
72
93
|
const built = await Bun.build({
|
|
@@ -83,13 +104,11 @@ async function loadActionModule(file: string, cache: Map<string, Record<string,
|
|
|
83
104
|
}],
|
|
84
105
|
})
|
|
85
106
|
const output = built.outputs[0]
|
|
86
|
-
if (!built.success || output === undefined) {
|
|
107
|
+
if (!built.success || output === undefined) return { failure: built.logs.map(log => log.message).join('; ') || 'it does not bundle' }
|
|
87
108
|
const js = await output.text()
|
|
88
|
-
|
|
89
|
-
cache.set(file, mod)
|
|
90
|
-
return mod
|
|
109
|
+
return { mod: await import(`data:text/javascript;base64,${Buffer.from(js, 'utf8').toString('base64')}`) as Record<string, unknown> }
|
|
91
110
|
}
|
|
92
|
-
catch
|
|
111
|
+
catch (error) { return { failure: messageOf(error) } }
|
|
93
112
|
}
|
|
94
113
|
|
|
95
114
|
function isExportedAction(graph: ModuleGraph, target: ActionRef): boolean {
|
|
@@ -97,24 +116,9 @@ function isExportedAction(graph: ModuleGraph, target: ActionRef): boolean {
|
|
|
97
116
|
return analysis !== undefined && analysis.exportedActions.includes(target.exportName)
|
|
98
117
|
}
|
|
99
118
|
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
const direct = analysis.reexports.find(r => r.exported === exportName)
|
|
104
|
-
if (direct !== undefined) {
|
|
105
|
-
const next = graph.resolve(file, direct.source)
|
|
106
|
-
if (next !== undefined && isTsFile(next)) return safeExportTarget(graph, next, direct.local, depth + 1)
|
|
107
|
-
}
|
|
108
|
-
if (analysis.exportedNames.includes(exportName) || exportName === 'default') return { file, exportName }
|
|
109
|
-
for (const re of analysis.reexports) {
|
|
110
|
-
if (re.exported !== '*') continue
|
|
111
|
-
const next = graph.resolve(file, re.source)
|
|
112
|
-
if (next !== undefined && isTsFile(next) && graph.analyses.has(next)) {
|
|
113
|
-
const resolved = safeExportTarget(graph, next, exportName, depth + 1)
|
|
114
|
-
if (graph.analyses.get(resolved.file)?.exportedNames.includes(resolved.exportName)) return resolved
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
return { file, exportName }
|
|
119
|
+
/** The declaring module of an export among the files the graph already analyzed. */
|
|
120
|
+
function safeExportTarget(graph: ModuleGraph, file: string, exportName: string): ActionRef {
|
|
121
|
+
return resolveExportTarget(graph, f => graph.analyses.get(f), file, exportName) ?? { file, exportName }
|
|
118
122
|
}
|
|
119
123
|
|
|
120
124
|
function createActionResolver(file: string, analysis: ModuleAnalysis, graph: ModuleGraph): ModuleActionResolver {
|
|
@@ -453,19 +457,32 @@ function buildMiddlewareLookup(routesDir: string, routeFiles: readonly string[],
|
|
|
453
457
|
})
|
|
454
458
|
}
|
|
455
459
|
|
|
456
|
-
|
|
460
|
+
// Every page that renders `file`, through imports and through the layouts above it.
|
|
461
|
+
const pagesRendering = (file: string): string[] => {
|
|
457
462
|
const seen = new Set<string>([file])
|
|
458
463
|
const queue = [file]
|
|
459
464
|
for (let i = 0; i < queue.length; i++) {
|
|
460
|
-
const
|
|
461
|
-
if (pageRouteSet.has(cur) && !hasAncestorMiddleware(cur)) return true
|
|
462
|
-
for (const parent of importers.get(cur) ?? [])
|
|
465
|
+
for (const parent of importers.get(queue[i]!) ?? [])
|
|
463
466
|
if (!seen.has(parent)) { seen.add(parent); queue.push(parent) }
|
|
464
467
|
}
|
|
465
|
-
return
|
|
468
|
+
return queue.filter(cur => pageRouteSet.has(cur))
|
|
466
469
|
}
|
|
467
470
|
|
|
468
|
-
return { hasAncestorMiddleware,
|
|
471
|
+
return { hasAncestorMiddleware, pagesRendering }
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/** The `patternProperties` keys of a schema as regexes: a field name one matches is a key the schema accepts. */
|
|
475
|
+
function fieldPatterns(patternProperties: unknown): RegExp[] {
|
|
476
|
+
if (!isRecord(patternProperties))
|
|
477
|
+
return []
|
|
478
|
+
return Object.keys(patternProperties).flatMap((source) => {
|
|
479
|
+
try {
|
|
480
|
+
return [new RegExp(source, 'u')]
|
|
481
|
+
}
|
|
482
|
+
catch {
|
|
483
|
+
return []
|
|
484
|
+
}
|
|
485
|
+
})
|
|
469
486
|
}
|
|
470
487
|
|
|
471
488
|
function checkFormAgainstAction(
|
|
@@ -474,23 +491,23 @@ function checkFormAgainstAction(
|
|
|
474
491
|
locAt: (file: string, offset: number) => string,
|
|
475
492
|
warnedVendors: Set<string>,
|
|
476
493
|
errors: string[],
|
|
477
|
-
|
|
494
|
+
warn: WarnAt,
|
|
478
495
|
): void {
|
|
479
496
|
const { exportName } = form.action
|
|
480
497
|
if (act.schema === undefined) return
|
|
481
498
|
|
|
482
499
|
const extracted = extractFormSchema(act.schema)
|
|
483
500
|
if (!extracted.ok) {
|
|
484
|
-
if (!warnedVendors.has(extracted.vendor)
|
|
501
|
+
if (!warnedVendors.has(extracted.vendor) && warn('form/schema-unsupported', form.file, form.offset, `Action "${exportName}" uses a "${extracted.vendor}" schema that has no JSON Schema output; form field checks skipped, and an error puts no field back in the form unless the action lists them in flashFields.`))
|
|
485
502
|
warnedVendors.add(extracted.vendor)
|
|
486
|
-
warnings.push(formatDiagnostic(locAt(form.file, form.offset), `[form/schema-unsupported] Action "${exportName}" uses a "${extracted.vendor}" schema that has no JSON Schema output; form field checks skipped.`, 'warning'))
|
|
487
|
-
}
|
|
488
503
|
return
|
|
489
504
|
}
|
|
490
505
|
|
|
491
506
|
const hpField = honeypotFieldName(act.protect)
|
|
492
507
|
const knownFields = [...extracted.fields.keys()]
|
|
493
|
-
const
|
|
508
|
+
const extra = extracted.jsonSchema.additionalProperties
|
|
509
|
+
const checkUnknown = extra !== true && !isRecord(extra) && (extracted.fields.size > 0 || extra === false)
|
|
510
|
+
const patterns = fieldPatterns(extracted.jsonSchema.patternProperties)
|
|
494
511
|
const sentFields = new Set<string>()
|
|
495
512
|
|
|
496
513
|
for (const field of form.fields) {
|
|
@@ -500,7 +517,7 @@ function checkFormAgainstAction(
|
|
|
500
517
|
sentFields.add(normalized)
|
|
501
518
|
|
|
502
519
|
const constraint = lookupFieldConstraint(extracted.fields, field.name)
|
|
503
|
-
if (constraint === undefined && checkUnknown) {
|
|
520
|
+
if (constraint === undefined && checkUnknown && !patterns.some(re => re.test(normalized))) {
|
|
504
521
|
const near = closestName(normalized, knownFields)
|
|
505
522
|
const hint = near !== undefined ? `did you mean "${near}"?` : knownFields.length > 0 ? `known fields: ${knownFields.join(', ')}.` : 'the schema accepts no fields.'
|
|
506
523
|
errors.push(formatDiagnostic(locAt(field.file, field.offset), `[form/unknown-field] Form field "${field.name}" does not exist on action "${exportName}"'s schema: ${hint}`, 'error'))
|
|
@@ -511,7 +528,7 @@ function checkFormAgainstAction(
|
|
|
511
528
|
const allowed = new Set(constraint.enumValues)
|
|
512
529
|
for (const opt of field.options) {
|
|
513
530
|
if (opt.value === '' || allowed.has(opt.value)) continue
|
|
514
|
-
|
|
531
|
+
warn('form/invalid-option', opt.file, opt.offset, `<option value="${opt.value}"> on <select name="${field.name}"> is not allowed by action "${exportName}"'s schema (allowed: ${constraint.enumValues.join(', ')}).`)
|
|
515
532
|
}
|
|
516
533
|
}
|
|
517
534
|
}
|
|
@@ -527,33 +544,65 @@ function checkFormAgainstAction(
|
|
|
527
544
|
}
|
|
528
545
|
}
|
|
529
546
|
|
|
547
|
+
/** A `protect.minTime` form on a prerendered or cached page: its signed `_pru_ts` is rendered once and handed to every visitor. */
|
|
548
|
+
function frozenTimestampErrors(form: CollectedForm, pages: readonly string[], graph: ModuleGraph, loc: string, relOf: (file: string) => string): string[] {
|
|
549
|
+
const errors: string[] = []
|
|
550
|
+
for (const page of pages) {
|
|
551
|
+
const analysis = graph.analyses.get(page)
|
|
552
|
+
const frozenBy = analysis?.hasPrerender === true ? 'prerender = true' : analysis?.cache !== undefined ? 'cache' : undefined
|
|
553
|
+
if (frozenBy === undefined) continue
|
|
554
|
+
errors.push(formatDiagnostic(loc, `[action/min-time-frozen] Form bound to action "${form.action.exportName}" uses protect.minTime on ${relOf(page)}, which exports ${frozenBy}: its signed timestamp is rendered once for every visitor, so bots pass minTime at once and every submit is refused 24 h after the render. Remove ${frozenBy === 'cache' ? 'the cache export' : 'prerender = true'} from ${relOf(page)}, or drop minTime and keep honeypot and rateLimit.`, 'error'))
|
|
555
|
+
}
|
|
556
|
+
return errors
|
|
557
|
+
}
|
|
558
|
+
|
|
530
559
|
/** Checks every `<form action={fn}>` across the app against its action's schema and public protection config. */
|
|
531
560
|
export async function checkAppForms(input: FormCheckInput): Promise<FormCheckResult> {
|
|
532
561
|
const { root, routesDir, routeFiles, graph, sources } = input
|
|
533
562
|
const errors: string[] = []
|
|
534
563
|
const warnings: string[] = []
|
|
535
|
-
const moduleCache = new Map<string,
|
|
564
|
+
const moduleCache = new Map<string, LoadedModule>()
|
|
565
|
+
const unimportable = new Set<string>()
|
|
536
566
|
const warnedVendors = new Set<string>()
|
|
537
|
-
const { hasAncestorMiddleware,
|
|
567
|
+
const { hasAncestorMiddleware, pagesRendering } = buildMiddlewareLookup(routesDir, routeFiles, graph)
|
|
538
568
|
|
|
539
569
|
const sourceOf = (file: string): string => sources?.get(file) ?? graph.source(file)
|
|
540
570
|
const locAt = (targetFile: string, offset: number): string => formatLoc(relPosix(root, targetFile), sourceOf(targetFile), offset)
|
|
571
|
+
const ignoresByFile = new Map<string, ReturnType<typeof parsePrunelleIgnores>>()
|
|
572
|
+
const warn: WarnAt = (rule, file, offset, message) => {
|
|
573
|
+
if (isRuleIgnored(rule, input.compliance)) return false
|
|
574
|
+
let ignores = ignoresByFile.get(file)
|
|
575
|
+
if (ignores === undefined) { ignores = parsePrunelleIgnores(sourceOf(file)); ignoresByFile.set(file, ignores) }
|
|
576
|
+
if (isIgnoredAt(ignores, rule, offset)) return false
|
|
577
|
+
warnings.push(formatDiagnostic(locAt(file, offset), `[${rule}] ${message}`, 'warning'))
|
|
578
|
+
return true
|
|
579
|
+
}
|
|
541
580
|
|
|
542
581
|
for (const [file, analysis] of graph.analyses) {
|
|
543
582
|
if (isInNodeModules(file) || !file.endsWith('.tsx') || !analysis.hasJsx) continue
|
|
544
583
|
const forms = collectModuleForms(file, analysis, graph)
|
|
545
584
|
if (forms.length === 0) continue
|
|
546
585
|
|
|
547
|
-
const
|
|
586
|
+
const pages = pagesRendering(file)
|
|
587
|
+
const publicPage = pages.some(page => !hasAncestorMiddleware(page))
|
|
548
588
|
for (const form of forms) {
|
|
549
|
-
const
|
|
550
|
-
|
|
589
|
+
const loaded = await loadActionModule(form.action.file, moduleCache)
|
|
590
|
+
if ('failure' in loaded) {
|
|
591
|
+
if (!unimportable.has(form.action.file)) {
|
|
592
|
+
unimportable.add(form.action.file)
|
|
593
|
+
warn('form/unchecked', form.file, form.offset, `${relPosix(root, form.action.file)} fails to import (${loaded.failure}), so prunelle check cannot read its actions: the forms posting to them go unchecked for their fields and protection. Move what fails into the action's handler, or make it import without the running app.`)
|
|
594
|
+
}
|
|
595
|
+
continue
|
|
596
|
+
}
|
|
597
|
+
const act = loaded.mod[form.action.exportName]
|
|
551
598
|
if (!isServerAction(act)) continue
|
|
552
599
|
|
|
553
|
-
checkFormAgainstAction(form, act, locAt, warnedVendors, errors,
|
|
600
|
+
checkFormAgainstAction(form, act, locAt, warnedVendors, errors, warn)
|
|
601
|
+
if (act.protect?.minTime !== undefined)
|
|
602
|
+
errors.push(...frozenTimestampErrors(form, pages, graph, locAt(form.file, form.offset), page => relPosix(root, page)))
|
|
554
603
|
|
|
555
604
|
if (publicPage && !hasAncestorMiddleware(form.action.file) && act.protect === undefined && act.rateLimit === undefined)
|
|
556
|
-
|
|
605
|
+
warn('action/unguarded-public-form', form.file, form.offset, `Public form action "${form.action.exportName}" has no protection: add { protect: { rateLimit, honeypot, minTime } } to action(), guard it with _middleware.ts, or write // prunelle-ignore action/unguarded-public-form above the form when it needs none.`)
|
|
557
606
|
}
|
|
558
607
|
}
|
|
559
608
|
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Finds an import no file or package answers, so check names it before build stops on it.
|
|
2
|
+
|
|
3
|
+
import { dirname } from 'node:path'
|
|
4
|
+
|
|
5
|
+
const SKIPPED = /^(?:prunelle(?:\/|$)|~icons\/|virtual:)/
|
|
6
|
+
|
|
7
|
+
/** The problem with an import specifier Bun's resolver finds nothing for, or undefined when it resolves or prunelle resolves it itself. */
|
|
8
|
+
export function unresolvedImport(file: string, rel: string, source: string): string | undefined {
|
|
9
|
+
if (SKIPPED.test(source))
|
|
10
|
+
return undefined
|
|
11
|
+
try {
|
|
12
|
+
Bun.resolveSync(source, dirname(file))
|
|
13
|
+
return undefined
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return source.startsWith('.')
|
|
17
|
+
? `prunelle check: import '${source}' in ${rel} does not resolve to a file: create it, or fix the path.`
|
|
18
|
+
: `prunelle check: import '${source}' in ${rel} does not resolve to a package: run bun add ${packageName(source)}, or fix the name.`
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function packageName(source: string): string {
|
|
23
|
+
const parts = source.split('/')
|
|
24
|
+
return source.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0]!
|
|
25
|
+
}
|
package/src/cli/check-links.ts
CHANGED
|
@@ -166,12 +166,12 @@ async function probeSinglePlugin(
|
|
|
166
166
|
const inject = <T>(key: { readonly name: string }) => state.services.get(key.name) as T | undefined
|
|
167
167
|
if (plugin.server !== undefined) {
|
|
168
168
|
const api: ServerPluginAPI = {
|
|
169
|
-
root, outDir, assetPrefix, site, dev: false,
|
|
169
|
+
root, outDir, assetPrefix, site, dev: false, devExposed: false,
|
|
170
170
|
trustProxy: config.trustProxy ?? false, trustedOrigins: config.trustedOrigins ?? [],
|
|
171
171
|
config: pickRuntimeConfig(config) as Readonly<Record<string, unknown>>,
|
|
172
172
|
use: (_mw, opts) => { if (plugin.name === '@prunellejs/seo' && typeof opts?.scope === 'string' && opts.scope.startsWith('/')) state.routes.push(opts.scope) },
|
|
173
173
|
route: (_method, path) => { state.routes.push(path) },
|
|
174
|
-
rateLimiter: () => ({ hit: () => 0 }), rewrite: () => {}, provide: state.provide,
|
|
174
|
+
rateLimiter: () => ({ hit: () => 0, peek: () => 0 }), rewrite: () => {}, provide: state.provide,
|
|
175
175
|
inject: key => inject(key) as never, getBuildData: () => undefined, healthCheck: () => {},
|
|
176
176
|
onShutdown: fn => { state.shutdowns.push(fn) },
|
|
177
177
|
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// `prunelle check` warnings about what weakens an app's defences: dotfiles under public/, and the security opt-outs in its config.
|
|
2
|
+
|
|
3
|
+
import type { SecurityHeadersOptions } from '../server/security'
|
|
4
|
+
import { relative } from 'node:path'
|
|
5
|
+
import { isHiddenPublicPath, walkAllFiles } from '../build/files'
|
|
6
|
+
import { formatDiagnostic } from '../compiler/shared'
|
|
7
|
+
import { resolveCspPolicy } from '../server/security'
|
|
8
|
+
|
|
9
|
+
/** One warning per dotfile in `public/` (other than `.well-known`): the build leaves it out, so it is either dead weight or a secret about to be committed. */
|
|
10
|
+
export function publicDotfileWarnings(publicDir: string, root: string): string[] {
|
|
11
|
+
return walkAllFiles(publicDir)
|
|
12
|
+
.map(abs => ({ abs, rel: relative(publicDir, abs) }))
|
|
13
|
+
.filter(file => isHiddenPublicPath(file.rel))
|
|
14
|
+
.sort((a, b) => a.rel.localeCompare(b.rel))
|
|
15
|
+
.map(file => formatDiagnostic(`${relative(root, file.abs)}:1:1`, `[security/public-dotfile] "${file.rel}" is in public/ but the build does not copy dotfiles, so it is never served: delete it, or move it out of public/ (only .well-known/ is kept).`, 'warning'))
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// `.redirect("https://…"` or `.redirect("//…"`: a literal address on another site, up to the closing parenthesis of the call.
|
|
19
|
+
const EXTERNAL_REDIRECT_RE = /\.redirect\(\s*(['"`])(?:https?:)?\/\/[^)]*\)/g
|
|
20
|
+
|
|
21
|
+
/** One warning per `ctx.redirect("https://other.site/…")` that lacks `{ external: true }`: since 0.x it throws at runtime. */
|
|
22
|
+
export function externalRedirectWarnings(files: readonly string[], read: (file: string) => string, locate: (file: string, offset: number) => string): string[] {
|
|
23
|
+
const warnings: string[] = []
|
|
24
|
+
for (const file of files) {
|
|
25
|
+
const code = read(file)
|
|
26
|
+
for (const match of code.matchAll(EXTERNAL_REDIRECT_RE)) {
|
|
27
|
+
if (!match[0].includes('external'))
|
|
28
|
+
warnings.push(formatDiagnostic(locate(file, match.index), '[security/external-redirect] ctx.redirect() to another site throws unless the app passes { external: true } as its third argument: add `{ external: true }` if the address is the app\'s own, and never pass one read from the request.', 'warning'))
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return warnings
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Fetch directives whose `'unsafe-inline'` lets an injected script or stylesheet run; `style-src-attr` is left out, as the default policy allows `style=""` attributes.
|
|
35
|
+
const INLINE_CODE_DIRECTIVES = new Set(['default-src', 'script-src', 'script-src-elem', 'style-src', 'style-src-elem'])
|
|
36
|
+
|
|
37
|
+
/** One warning for each way `security` in `prunelle.config.ts` turns a default defence off: all headers, the CSP, or `'unsafe-inline'` in it. */
|
|
38
|
+
export function securityConfigWarnings(security: SecurityHeadersOptions | false | undefined): string[] {
|
|
39
|
+
const at = 'prunelle.config.ts:1:1'
|
|
40
|
+
if (security === false)
|
|
41
|
+
return [formatDiagnostic(at, '[security/headers-off] security: false sends no CSP, HSTS, nosniff, frame, referrer, permissions, opener or resource policy header: drop it, and relax only the one header an integration needs (`security: { frameOptions: false }`).', 'warning')]
|
|
42
|
+
if (security?.csp === false)
|
|
43
|
+
return [formatDiagnostic(at, '[security/csp-off] security.csp is false, so no page carries a Content-Security-Policy: drop it, or extend the default with `security: { csp: { \'img-src\': [\'https://cdn.example\'] } }`.', 'warning')]
|
|
44
|
+
const csp = resolveCspPolicy(security)
|
|
45
|
+
const loose = (csp ?? '').split(';')
|
|
46
|
+
.map(part => part.trim().split(/\s+/))
|
|
47
|
+
.filter(([name, ...tokens]) => INLINE_CODE_DIRECTIVES.has(name!.toLowerCase()) && tokens.includes('\'unsafe-inline\''))
|
|
48
|
+
.map(([name]) => name!.toLowerCase())
|
|
49
|
+
return loose.length === 0
|
|
50
|
+
? []
|
|
51
|
+
: [formatDiagnostic(at, `[security/unsafe-inline] the CSP allows 'unsafe-inline' in ${loose.join(', ')}, which lets an injected script or style run: remove it, since prunelle hashes its own inline scripts and styles, or add a hash of the inline one you need.`, 'warning')]
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const CSRF_OFF_RE = /export\s+const\s+csrf\s*=\s*false\b/g
|
|
55
|
+
|
|
56
|
+
/** One warning per route file that exports `csrf = false`: it accepts a cross-site POST, so it must check a signature or a token itself. */
|
|
57
|
+
export function csrfOffWarnings(files: readonly string[], read: (file: string) => string, locate: (file: string, offset: number) => string): string[] {
|
|
58
|
+
const warnings: string[] = []
|
|
59
|
+
for (const file of files) {
|
|
60
|
+
for (const match of read(file).matchAll(CSRF_OFF_RE))
|
|
61
|
+
warnings.push(formatDiagnostic(locate(file, match.index), '[security/csrf-off] this route skips the cross-site request check, so any site can post to it: keep it only for a webhook or bearer-token API that verifies a signature or token itself, and drop `export const csrf = false` for anything a browser form posts to.', 'warning'))
|
|
62
|
+
}
|
|
63
|
+
return warnings
|
|
64
|
+
}
|
package/src/cli/check.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// `prunelle check [dir]`: validates routes, Prunelle compiler & island rules (unified with `prunelle build`), config, and TypeScript types.
|
|
2
2
|
|
|
3
|
+
import type { IslandValueUse } from '../build/island-promote'
|
|
3
4
|
import type { IslandIssue } from '../build/islands'
|
|
4
5
|
import type { ModuleAnalysis } from '../compiler/analyze'
|
|
5
6
|
import type { ComplianceConfig } from '../compiler/compliance'
|
|
@@ -14,13 +15,16 @@ import { ancestorFiles, discoverRouteMatchers, fileToRoutePath, hasRouteHandlerE
|
|
|
14
15
|
import { findUnknownStatusPages } from '../build/status-pages'
|
|
15
16
|
import { analyzeModule } from '../compiler/analyze'
|
|
16
17
|
import { findCachedRoutePrivateReads } from '../compiler/cacheability'
|
|
17
|
-
import { collectProjectComplianceWarnings, shouldEmitWarning } from '../compiler/compliance'
|
|
18
|
+
import { collectProjectComplianceWarnings, isIgnoredAt, isRuleIgnored, parsePrunelleIgnores, pluginSetsLang, shouldEmitWarning } from '../compiler/compliance'
|
|
18
19
|
import { collectMistakes, PrunelleMistake, serverOnlyTagError } from '../compiler/mistakes'
|
|
19
20
|
import { DIAGNOSTIC_PREFIX_RE, formatDiagnostic, formatLoc } from '../compiler/shared'
|
|
20
21
|
import { createAppContext, loadConfig, resolvePlugins, runWithAppContext } from '../plugins/index'
|
|
21
22
|
import { collectRequirements } from '../plugins/requires'
|
|
23
|
+
import { normalizeConsentConfig } from '../server/consent'
|
|
22
24
|
import { checkAppForms } from './check-forms'
|
|
25
|
+
import { unresolvedImport } from './check-imports'
|
|
23
26
|
import { checkAppLinks } from './check-links'
|
|
27
|
+
import { csrfOffWarnings, externalRedirectWarnings, publicDotfileWarnings, securityConfigWarnings } from './check-security'
|
|
24
28
|
|
|
25
29
|
/** Whether `prunelle check` typechecked the app, with which tool, or why it did not. */
|
|
26
30
|
export type TypecheckRun = { ran: true, tool: string } | { ran: false, reason: string }
|
|
@@ -141,6 +145,16 @@ function loadCheckedModule(
|
|
|
141
145
|
return undefined
|
|
142
146
|
}
|
|
143
147
|
|
|
148
|
+
// An imported island read as a value hydrates what holds it whole: a warning, as a table of islands may mean it.
|
|
149
|
+
function islandValueWarnings(uses: readonly IslandValueUse[], root: string, sources: Map<string, string>, compliance: ComplianceConfig | undefined): string[] {
|
|
150
|
+
const rule = 'rgesn/island-by-value'
|
|
151
|
+
if (isRuleIgnored(rule, compliance))
|
|
152
|
+
return []
|
|
153
|
+
return uses
|
|
154
|
+
.filter(use => !isIgnoredAt(parsePrunelleIgnores(sourceOf(use.file, sources)), rule, use.offset))
|
|
155
|
+
.map(use => formatDiagnostic(locOf(root, use.file, sources, use.offset), `[${rule}] ${use.name} is an island read as a value, not rendered as <${use.name} />, so what holds it hydrates as an island and ships its code too: render <${use.name} /> itself where it shows, or // prunelle-ignore ${rule} when the whole component should hydrate.`, 'warning'))
|
|
156
|
+
}
|
|
157
|
+
|
|
144
158
|
function formatIslandIssue(issue: IslandIssue, root: string, sources: Map<string, string>): string {
|
|
145
159
|
const rel = relPosix(root, issue.file)
|
|
146
160
|
switch (issue.kind) {
|
|
@@ -181,14 +195,15 @@ function formatIslandIssue(issue: IslandIssue, root: string, sources: Map<string
|
|
|
181
195
|
}
|
|
182
196
|
|
|
183
197
|
// Each plugin's check(ctx) runs inside a real AppRuntimeContext; what it reports without a place lands on prunelle.config.ts.
|
|
184
|
-
async function runPluginChecks(plugins: readonly PrunellePlugin[], paths: { root: string, routesDir: string, outDir: string, assetPrefix: string, site: string | undefined }, errors: string[], warnings: string[]): Promise<void> {
|
|
185
|
-
const { root, routesDir, outDir, assetPrefix, site } = paths
|
|
198
|
+
async function runPluginChecks(plugins: readonly PrunellePlugin[], paths: { root: string, routesDir: string, publicDir: string, outDir: string, assetPrefix: string, site: string | undefined, consentCategories: readonly string[] }, errors: string[], warnings: string[]): Promise<void> {
|
|
199
|
+
const { root, routesDir, publicDir, outDir, assetPrefix, site, consentCategories } = paths
|
|
186
200
|
const appCtx = createAppContext({ root, outDir, publicDir: join(outDir, 'public'), assetPrefix, site, dev: false })
|
|
187
201
|
const placed = (message: string, severity: 'error' | 'warning'): string =>
|
|
188
202
|
DIAGNOSTIC_PREFIX_RE.test(message) ? message : formatDiagnostic('prunelle.config.ts:1:1', message, severity)
|
|
189
203
|
const pluginCtx: CheckPluginContext = {
|
|
190
204
|
root,
|
|
191
205
|
routesDir,
|
|
206
|
+
publicDir,
|
|
192
207
|
error: message => errors.push(placed(message, 'error')),
|
|
193
208
|
warn: message => warnings.push(placed(message, 'warning')),
|
|
194
209
|
provide: appCtx.provide,
|
|
@@ -204,7 +219,7 @@ async function runPluginChecks(plugins: readonly PrunellePlugin[], paths: { root
|
|
|
204
219
|
errors.push(placed(`${plugin.name}: ${err instanceof Error ? err.message : String(err)}`, 'error'))
|
|
205
220
|
}
|
|
206
221
|
}
|
|
207
|
-
const { unmet, failed } = await runWithAppContext(appCtx, () => collectRequirements(plugins, { root, site }))
|
|
222
|
+
const { unmet, failed } = await runWithAppContext(appCtx, () => collectRequirements(plugins, { root, site, consentCategories }))
|
|
208
223
|
for (const line of unmet)
|
|
209
224
|
warnings.push(placed(`${line} (a production start refuses until it is set)`, 'warning'))
|
|
210
225
|
for (const line of failed)
|
|
@@ -236,10 +251,12 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
236
251
|
let compliance: ComplianceConfig | undefined
|
|
237
252
|
let loadedConfig: PrunelleConfig = {}
|
|
238
253
|
let plugins: Awaited<ReturnType<typeof loadConfig>>['plugins'] = []
|
|
254
|
+
let consentCategories: readonly string[] = []
|
|
239
255
|
try {
|
|
240
256
|
const cfg = await loadConfig(root)
|
|
241
257
|
loadedConfig = cfg
|
|
242
258
|
plugins = resolvePlugins(cfg.plugins)
|
|
259
|
+
consentCategories = normalizeConsentConfig(cfg.consent)?.categories ?? []
|
|
243
260
|
site = cfg.site
|
|
244
261
|
compliance = cfg.compliance
|
|
245
262
|
if (cfg.routesDir !== undefined)
|
|
@@ -308,6 +325,7 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
308
325
|
})
|
|
309
326
|
for (const issue of islands.issues)
|
|
310
327
|
errors.push(formatIslandIssue(issue, root, sources))
|
|
328
|
+
warnings.push(...islandValueWarnings(islands.valueUses, root, sources, compliance))
|
|
311
329
|
|
|
312
330
|
// 3b. Static guardrails: non-serializable island props, route exports, route conflicts, missing paths()
|
|
313
331
|
const seenRoutes = new Map<string, string>()
|
|
@@ -316,6 +334,9 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
316
334
|
continue
|
|
317
335
|
const rel = relPosix(root, file)
|
|
318
336
|
for (const imp of analysis.imports) {
|
|
337
|
+
const unresolved = unresolvedImport(file, rel, imp.source)
|
|
338
|
+
if (unresolved !== undefined)
|
|
339
|
+
errors.push(formatDiagnostic(locOf(root, file, sources, imp.start), unresolved))
|
|
319
340
|
if (imp.source === '@prunellejs/auth') {
|
|
320
341
|
const removed = imp.specifiers.find(s => s.imported === 'createRateLimiter' || s.imported === 'RateLimiter')
|
|
321
342
|
if (removed !== undefined)
|
|
@@ -370,18 +391,23 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
370
391
|
}
|
|
371
392
|
|
|
372
393
|
// 3d. French web law compliance checks (CSS third-party URLs, LCEN legal notice, RGAA accessibility statement)
|
|
373
|
-
warnings.push(...collectProjectComplianceWarnings({ root, srcDir, routesDir, routeFiles, analyses, compliance, site }))
|
|
394
|
+
warnings.push(...collectProjectComplianceWarnings({ root, srcDir, routesDir, routeFiles, analyses, compliance, consentMaxAge: loadedConfig.consent?.maxAge, site, lang: loadedConfig.lang, langFromPlugin: pluginSetsLang(plugins) }))
|
|
374
395
|
|
|
375
396
|
// 3d. Form field / schema checks & public action protection warnings (#4, #5)
|
|
376
|
-
const formCheck = await checkAppForms({ root, routesDir, routeFiles, graph, sources })
|
|
397
|
+
const formCheck = await checkAppForms({ root, routesDir, routeFiles, graph, sources, compliance })
|
|
377
398
|
errors.push(...formCheck.errors)
|
|
378
399
|
warnings.push(...formCheck.warnings)
|
|
379
400
|
|
|
401
|
+
warnings.push(...publicDotfileWarnings(publicDir, root))
|
|
402
|
+
warnings.push(...securityConfigWarnings(loadedConfig.security))
|
|
403
|
+
warnings.push(...csrfOffWarnings(routeFiles, file => sourceOf(file, sources), (file, offset) => locOf(root, file, sources, offset)))
|
|
404
|
+
warnings.push(...externalRedirectWarnings(files, file => sourceOf(file, sources), (file, offset) => locOf(root, file, sources, offset)))
|
|
405
|
+
|
|
380
406
|
// 3e. Broken internal link checks (#3)
|
|
381
407
|
warnings.push(...await checkAppLinks({ root, routesDir, publicDir, assetPrefix, site, config: loadedConfig, plugins, routeFiles, analyses, sources }))
|
|
382
408
|
|
|
383
409
|
// 3f. Plugin check(ctx) hooks
|
|
384
|
-
await runPluginChecks(plugins, { root, routesDir, outDir, assetPrefix, site }, errors, warnings)
|
|
410
|
+
await runPluginChecks(plugins, { root, routesDir, publicDir, outDir, assetPrefix, site, consentCategories }, errors, warnings)
|
|
385
411
|
|
|
386
412
|
const typecheck = options.skipTypecheck === true ? { ran: false as const, reason: "skipped by --no-typecheck" } : runTypecheck(root, errors)
|
|
387
413
|
|
package/src/cli/commands.ts
CHANGED
|
@@ -4,9 +4,10 @@ import type { Commands, ExitRow } from '@kaynooo/cli-kit'
|
|
|
4
4
|
import type { ScaffoldTemplate } from './new'
|
|
5
5
|
import { resolve } from 'node:path'
|
|
6
6
|
import { badUsage, Exit, fail, parse } from '@kaynooo/cli-kit'
|
|
7
|
+
import { parseByteSize } from '../build/byte-size'
|
|
7
8
|
|
|
8
9
|
const TEMPLATES = ['minimal', 'fullstack', 'blog', 'app'] as const
|
|
9
|
-
|
|
10
|
+
|
|
10
11
|
|
|
11
12
|
const ROOT = { type: 'string', description: 'the app folder, when it is not the current one or the [dir] argument' } as const
|
|
12
13
|
const PORT = { type: 'string', description: 'the port to listen on (PORT, then prunelle.config.ts port, then 3000; 0 picks a free one)' } as const
|
|
@@ -17,10 +18,7 @@ const USAGE_EXIT: ExitRow = [2, 'a usage error']
|
|
|
17
18
|
|
|
18
19
|
// `--max-js 40kb`, `--max-js 40KB` or `--max-js 40960` (bytes).
|
|
19
20
|
function parseSize(raw: string): number {
|
|
20
|
-
|
|
21
|
-
if (match === null)
|
|
22
|
-
return badUsage(`invalid --max-js "${raw}": give the gzipped size of a route's eager JS in bytes or KB, e.g. --max-js 40kb`)
|
|
23
|
-
return Math.round(Number(match[1]) * (match[2] === undefined ? 1 : 1024))
|
|
21
|
+
return parseByteSize(raw) ?? badUsage(`invalid --max-js "${raw}": give the gzipped size of a route's eager JS in bytes or KB, e.g. --max-js 40kb`)
|
|
24
22
|
}
|
|
25
23
|
|
|
26
24
|
function parsePort(raw: string | number | undefined, fallback: number): number {
|
|
@@ -64,6 +62,9 @@ function newCommand(cwd: string): Commands[string] {
|
|
|
64
62
|
const { scaffoldProject } = await import('./new')
|
|
65
63
|
const template = (values.template ?? 'minimal') as ScaffoldTemplate
|
|
66
64
|
const res = await failing('new', async () => scaffoldProject(rootOf(cwd, values.root, dir), { template, force: values.force === true }))
|
|
65
|
+
|
|
66
|
+
for (const file of res.overwritten)
|
|
67
|
+
console.log(`prunelle new: overwrote ${file}`)
|
|
67
68
|
console.log(`Created Prunelle (${template}) project in ${res.root} (${res.files.length} files)`)
|
|
68
69
|
console.log(`\nNext steps:\n cd ${dir}\n bun install\n bun run dev`)
|
|
69
70
|
return 0
|
|
@@ -119,7 +120,10 @@ function upgradeCommand(cwd: string): Commands[string] {
|
|
|
119
120
|
'root': ROOT,
|
|
120
121
|
}, { positionals: ['[dir]'], exits: [[0, 'every file was rewritten and nothing is left to do by hand'], [1, 'bun install failed, or steps are left to do by hand (printed)'], USAGE_EXIT] })
|
|
121
122
|
const root = rootOf(cwd, values.root, dir)
|
|
122
|
-
const { upgradeProject } = await import('./upgrade')
|
|
123
|
+
const { notAnApp, upgradeProject } = await import('./upgrade')
|
|
124
|
+
const refused = notAnApp(root)
|
|
125
|
+
if (refused !== undefined)
|
|
126
|
+
return fail(refused, 1, 'run prunelle upgrade in the app\'s folder, or pass that folder as [dir]')
|
|
123
127
|
const res = upgradeProject(root)
|
|
124
128
|
for (const file of res.changed)
|
|
125
129
|
console.log(` ${file}`)
|
|
@@ -189,6 +193,25 @@ function buildCommand(cwd: string): Commands[string] {
|
|
|
189
193
|
}
|
|
190
194
|
}
|
|
191
195
|
|
|
196
|
+
function ecoCommand(cwd: string): Commands[string] {
|
|
197
|
+
return {
|
|
198
|
+
summary: 'judge the RGESN eco-design criteria prunelle can measure, and draft the declaration',
|
|
199
|
+
run: async (args) => {
|
|
200
|
+
const { values, positionals: [dir] } = parse(args, 'prunelle eco [options] [dir]: builds the app and judges the RGESN 2024 criteria prunelle can measure', {
|
|
201
|
+
declaration: { type: 'string', optional: { bare: '' }, description: 'write an editable RGESN 2024 eco-design declaration page (default: src/routes/ecoconception.tsx)' },
|
|
202
|
+
service: { type: 'string', description: 'the service\'s name, written into --declaration' },
|
|
203
|
+
org: { type: 'string', description: 'the entity running the evaluation, written into --declaration' },
|
|
204
|
+
contact: { type: 'string', description: 'the contact email, written into --declaration' },
|
|
205
|
+
root: ROOT,
|
|
206
|
+
}, { positionals: ['[dir]'], exits: [OK, [1, 'the build failed'], USAGE_EXIT] })
|
|
207
|
+
const { formatEcoResult, runEco } = await import('../eco/index')
|
|
208
|
+
const result = await failing('eco', () => runEco({ root: rootOf(cwd, values.root, dir), declaration: values.declaration, service: values.service, organization: values.org, contactEmail: values.contact }))
|
|
209
|
+
console.log(formatEcoResult(result))
|
|
210
|
+
return 0
|
|
211
|
+
},
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
192
215
|
const SERVE_EXITS: ExitRow[] = [[0, 'the server started'], [1, 'the config or the server failed to load'], USAGE_EXIT]
|
|
193
216
|
|
|
194
217
|
function startCommand(cwd: string): Commands[string] {
|
|
@@ -207,6 +230,10 @@ function startCommand(cwd: string): Commands[string] {
|
|
|
207
230
|
const { app, server } = await failing('start', async () => startServer({ root, port, hostname }))
|
|
208
231
|
handleSignals(app, server)
|
|
209
232
|
console.log(`prunelle server listening on http://${hostname}:${server.port}`)
|
|
233
|
+
const { loopbackBindNotice } = await import('../server/security')
|
|
234
|
+
const notice = process.env.NODE_ENV === 'production' ? loopbackBindNotice(hostname, values.host !== undefined || Boolean(process.env.HOST)) : undefined
|
|
235
|
+
if (notice !== undefined)
|
|
236
|
+
console.warn(notice)
|
|
210
237
|
return 0
|
|
211
238
|
},
|
|
212
239
|
}
|
|
@@ -223,7 +250,7 @@ function devCommand(cwd: string): Commands[string] {
|
|
|
223
250
|
const port = parsePort(values.port ?? (process.env.PORT || config.port), 3000)
|
|
224
251
|
const hostname = values.host ?? (process.env.HOST || '127.0.0.1')
|
|
225
252
|
const { devSupervisor } = await import('../dev/supervisor')
|
|
226
|
-
const dev = await failing('dev', async () => devSupervisor({ root, port, hostname, maxRequestBodySize: resolveServerConfig(config, {}).maxRequestBodySize }))
|
|
253
|
+
const dev = await failing('dev', async () => devSupervisor({ root, port, hostname, maxRequestBodySize: resolveServerConfig(config, {}).maxRequestBodySize, allowedOrigins: [config.site, ...config.trustedOrigins ?? []] }))
|
|
227
254
|
for (const signal of ['SIGINT', 'SIGTERM'] as const)
|
|
228
255
|
process.once(signal, () => void dev.stop().finally(() => process.exit(0)))
|
|
229
256
|
return 0
|
|
@@ -315,6 +342,7 @@ export function builtinCommands(cwd: string): Commands {
|
|
|
315
342
|
mcp: mcpCommand(cwd),
|
|
316
343
|
dev: devCommand(cwd),
|
|
317
344
|
build: buildCommand(cwd),
|
|
345
|
+
eco: ecoCommand(cwd),
|
|
318
346
|
start: startCommand(cwd),
|
|
319
347
|
upgrade: upgradeCommand(cwd),
|
|
320
348
|
}
|
package/src/cli/docs.ts
CHANGED
|
@@ -330,6 +330,9 @@ export function searchLlmsDocs(
|
|
|
330
330
|
query: string,
|
|
331
331
|
options?: { limit?: number | undefined },
|
|
332
332
|
): DocsSearchResult {
|
|
333
|
+
const limit = options?.limit ?? DEFAULT_LIMIT
|
|
334
|
+
if (!Number.isInteger(limit) || limit <= 0)
|
|
335
|
+
throw new Error(`prunelle docs: invalid limit ${limit}: give a positive integer`)
|
|
333
336
|
const docs = discoverLlmsDocs(rootDir)
|
|
334
337
|
const packages = docs.map(doc => ({ name: doc.packageName, version: doc.version, file: doc.relFile }))
|
|
335
338
|
const words = query.trim().toLowerCase().split(WORD_SPLIT_RE).filter(Boolean)
|
|
@@ -375,9 +378,7 @@ export function searchLlmsDocs(
|
|
|
375
378
|
return a.line - b.line
|
|
376
379
|
})
|
|
377
380
|
|
|
378
|
-
|
|
379
|
-
const limited = limit >= 0 ? matches.slice(0, limit) : matches
|
|
380
|
-
return { query, words, packages, matches: limited }
|
|
381
|
+
return { query, words, packages, matches: matches.slice(0, limit) }
|
|
381
382
|
}
|
|
382
383
|
|
|
383
384
|
function formatPackageLabel(name: string, version: string | undefined): string {
|