prunelle 0.1.1 → 0.7.2
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 +137 -40
- package/package.json +11 -2
- package/src/a11y/declaration.ts +373 -0
- package/src/a11y/index.ts +477 -0
- package/src/a11y/rgaa-map.ts +230 -0
- package/src/attrs.ts +11 -3
- package/src/build/bundle.ts +89 -41
- package/src/build/byte-size.ts +11 -0
- package/src/build/client-entries.ts +3 -2
- package/src/build/client-plugin.ts +11 -5
- package/src/build/client-prune.ts +56 -6
- package/src/build/compile.ts +13 -10
- package/src/build/ecoindex.ts +238 -0
- package/src/build/files.ts +15 -0
- package/src/build/first-load.ts +85 -14
- package/src/build/graph.ts +29 -39
- package/src/build/index.ts +225 -122
- package/src/build/island-promote.ts +311 -0
- package/src/build/islands.ts +14 -203
- package/src/build/manifest.ts +56 -116
- package/src/build/output.ts +3 -6
- package/src/build/plugin-host.ts +115 -41
- package/src/build/precompress.ts +16 -3
- package/src/build/prerender.ts +177 -39
- package/src/build/reach.ts +200 -0
- package/src/build/render-rules.ts +2 -2
- package/src/build/report.ts +48 -5
- package/src/build/resolve.ts +8 -6
- package/src/build/routes.ts +175 -10
- package/src/build/static-headers.ts +112 -0
- package/src/build/static.ts +139 -39
- package/src/build/status-pages.ts +127 -0
- package/src/build/style-bundles.ts +526 -0
- package/src/cli/check-forms.ts +636 -0
- package/src/cli/check-imports.ts +31 -0
- package/src/cli/check-links.ts +632 -0
- package/src/cli/check-security.ts +64 -0
- package/src/cli/check.ts +101 -26
- package/src/cli/commands.ts +120 -11
- package/src/cli/docs.ts +403 -0
- package/src/cli/inspect.ts +105 -15
- package/src/cli/mcp-tools.ts +492 -0
- package/src/cli/mcp.ts +205 -0
- package/src/cli/new.ts +16 -5
- package/src/cli/render.ts +416 -0
- package/src/cli/upgrade-names.ts +73 -13
- package/src/cli/upgrade.ts +156 -22
- package/src/compiler/analyze.ts +87 -54
- package/src/compiler/browser-globals.ts +140 -17
- package/src/compiler/cacheability-private.ts +566 -0
- package/src/compiler/cacheability.ts +335 -0
- package/src/compiler/compliance-eco.ts +71 -0
- package/src/compiler/compliance-rgaa.ts +614 -0
- package/src/compiler/compliance-urls.ts +148 -0
- package/src/compiler/compliance.ts +407 -352
- package/src/compiler/data-keys.ts +199 -192
- package/src/compiler/dev-source.ts +87 -0
- package/src/compiler/dom-attrs.ts +138 -65
- package/src/compiler/dom.ts +517 -442
- package/src/compiler/expr-context.ts +260 -81
- package/src/compiler/foreign-imports.ts +88 -0
- package/src/compiler/mistakes.ts +23 -2
- package/src/compiler/props-body.ts +60 -0
- package/src/compiler/props.ts +87 -36
- package/src/compiler/scope.ts +400 -333
- package/src/compiler/server-only.ts +190 -151
- package/src/compiler/shared.ts +42 -14
- package/src/compiler/signal-reads.ts +6 -2
- package/src/compiler/spread-handlers.ts +295 -0
- package/src/compiler/ssr-prunelle-tags.ts +27 -14
- package/src/compiler/ssr.ts +220 -89
- package/src/context.ts +34 -0
- package/src/dev/error-log.ts +177 -0
- package/src/dev/host-check.ts +32 -0
- package/src/dev/index.ts +94 -34
- package/src/dev/open-editor.ts +228 -0
- package/src/dev/protocol.ts +3 -0
- package/src/dev/reload.ts +5 -3
- package/src/dev/supervisor.ts +50 -25
- package/src/dev/watchers.ts +74 -13
- package/src/dom/action.ts +47 -21
- package/src/dom/attrs.ts +15 -3
- package/src/dom/extras.ts +57 -40
- package/src/dom/index.ts +54 -14
- package/src/dom/island.ts +102 -68
- package/src/dom/loop.ts +66 -32
- package/src/eco/declaration.ts +328 -0
- package/src/eco/index.ts +69 -0
- package/src/index.ts +2 -2
- package/src/jsx-runtime.ts +2 -2
- package/src/plugins/config.ts +18 -12
- package/src/plugins/context.ts +44 -1
- package/src/plugins/index.ts +2 -2
- package/src/plugins/load.ts +30 -10
- package/src/plugins/order.ts +38 -1
- package/src/plugins/public.ts +6 -3
- package/src/plugins/services.ts +84 -0
- package/src/plugins/types.ts +51 -2
- package/src/reactivity/graph.ts +10 -0
- package/src/reactivity/index.ts +24 -16
- package/src/reactivity/selector.ts +31 -4
- package/src/reactivity/store.ts +64 -20
- package/src/server/action-flash.ts +158 -0
- package/src/server/action-protect.ts +199 -0
- package/src/server/action-registry.ts +1 -1
- package/src/server/action.ts +188 -152
- package/src/server/app-secret.ts +63 -0
- package/src/server/assets.ts +34 -2
- package/src/server/compress.ts +96 -10
- package/src/server/consent.ts +59 -22
- package/src/server/cookies.ts +16 -2
- package/src/server/document.ts +25 -10
- package/src/server/env.ts +14 -0
- package/src/server/errors.ts +308 -65
- package/src/server/form-schema.ts +337 -0
- package/src/server/health.ts +275 -0
- package/src/server/http.ts +186 -39
- package/src/server/index.ts +272 -273
- package/src/server/loader.ts +15 -2
- package/src/server/page.ts +15 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +125 -88
- package/src/server/public.ts +6 -5
- package/src/server/rate-limit.ts +102 -36
- package/src/server/request-body.ts +1 -1
- package/src/server/route-cache.ts +541 -0
- package/src/server/route-table.ts +356 -11
- package/src/server/router.ts +125 -40
- package/src/server/routing.ts +112 -63
- package/src/server/sanitize-html.ts +309 -0
- package/src/server/security.ts +279 -52
- package/src/server/serve-handlers.ts +31 -7
- package/src/server/standard-schema.ts +17 -0
- package/src/server/start.ts +60 -16
- package/src/server/static-dir.ts +91 -12
- package/src/server/stream.ts +68 -27
- package/src/ssr/consent-banner.ts +58 -0
- package/src/ssr/context.ts +106 -8
- package/src/ssr/index.ts +151 -4
- package/src/ssr/navigation.ts +2 -2
- package/src/ssr/region.ts +40 -19
- package/src/style.ts +64 -1
- package/src/test/browser.ts +28 -13
- package/src/test/index.ts +97 -12
- package/src/ts-plugin/diagnostics.ts +505 -0
- package/src/ts-plugin/fixes.ts +364 -0
- package/src/ts-plugin/index.ts +194 -0
- package/templates/_shared/AGENTS.md +2 -2
- package/templates/_shared/gitignore +5 -0
- package/templates/_shared/mcp.json +11 -0
- package/templates/_shared/src/routes/legal.tsx +15 -1
- package/templates/_shared/tsconfig.json +5 -0
- 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/prunelle.config.ts +1 -1
- package/templates/blog/src/routes/_layout.tsx +6 -1
- package/templates/blog/src/routes/index.tsx +5 -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/ts-plugin.cjs +4277 -0
|
@@ -0,0 +1,636 @@
|
|
|
1
|
+
// Static form validation for `prunelle check` and `prunelle build`:
|
|
2
|
+
// - Checks `<form action={fn}>` fields against the action's Standard Schema JSON Schema (unknown fields, missing required fields, `<select>` enum options)
|
|
3
|
+
// - Warns once per schema vendor lacking JSON Schema output
|
|
4
|
+
// - Warns on unguarded public form actions without `protect` / `rateLimit` / `_middleware.ts`
|
|
5
|
+
|
|
6
|
+
import type { JSXAttribute, JSXElement, Node, Program } from 'oxc-parser'
|
|
7
|
+
import type { ModuleGraph } from '../build/graph'
|
|
8
|
+
import type { ModuleAnalysis } from '../compiler/analyze'
|
|
9
|
+
import type { ComplianceConfig, FormWarningRule } from '../compiler/compliance'
|
|
10
|
+
import type { ServerAction } from '../server/action'
|
|
11
|
+
import { readFileSync } from 'node:fs'
|
|
12
|
+
import { basename, dirname } from 'node:path'
|
|
13
|
+
import { isInNodeModules, isTsFile, relPosix } from '../build/files'
|
|
14
|
+
import { resolveExportTarget } from '../build/island-promote'
|
|
15
|
+
import { isInside } from '../build/is-inside'
|
|
16
|
+
import { resolvePrunelleSpecifier } from '../build/resolve'
|
|
17
|
+
import { walk } from '../compiler/ast'
|
|
18
|
+
import { isIgnoredAt, isRuleIgnored, parsePrunelleIgnores } from '../compiler/compliance'
|
|
19
|
+
import { calleeName, formatDiagnostic, formatLoc, isComponentTag, jsxTagName, resolvePrunelleTag, unwrapTsExpr } from '../compiler/shared'
|
|
20
|
+
import { staticLiteralOrTemplate, staticOptionText } from '../compiler/ssr-helpers'
|
|
21
|
+
import { closestName } from '../plugins/config'
|
|
22
|
+
import { isServerAction } from '../server/action'
|
|
23
|
+
import { FORM_TIMESTAMP_FIELD, honeypotFieldName } from '../server/action-protect'
|
|
24
|
+
import { extractFormSchema, isRecord, lookupFieldConstraint } from '../server/form-schema'
|
|
25
|
+
|
|
26
|
+
export interface FormCheckInput {
|
|
27
|
+
root: string
|
|
28
|
+
routesDir: string
|
|
29
|
+
routeFiles: readonly string[]
|
|
30
|
+
graph: ModuleGraph
|
|
31
|
+
/** Optional pre-read source map (falls back to `graph.source(file)`). */
|
|
32
|
+
sources?: ReadonlyMap<string, string> | undefined
|
|
33
|
+
/** `compliance.ignore` silences a form warning across the app. */
|
|
34
|
+
compliance?: ComplianceConfig | undefined
|
|
35
|
+
}
|
|
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
|
+
|
|
40
|
+
export interface FormCheckResult {
|
|
41
|
+
errors: string[]
|
|
42
|
+
warnings: string[]
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
interface ActionRef { file: string, exportName: string }
|
|
46
|
+
interface SelectOptionInfo { value: string, file: string, offset: number }
|
|
47
|
+
interface CollectedField { name: string, tag: string, file: string, offset: number, options?: SelectOptionInfo[] | undefined }
|
|
48
|
+
interface CollectedForm { action: ActionRef, file: string, offset: number, fields: CollectedField[], hasOpaqueFields: boolean }
|
|
49
|
+
interface PropsScope { bindings: ReadonlyMap<string, string>, propsParam?: string | undefined, destructured: ReadonlyMap<string, string> }
|
|
50
|
+
interface ModuleActionResolver { resolveExpr(node: Node): ActionRef | undefined }
|
|
51
|
+
|
|
52
|
+
const PRUNELLE_SPECIFIER_RE = /^prunelle(?:\/|$)/
|
|
53
|
+
const EMPTY_MAP: ReadonlyMap<string, string> = new Map()
|
|
54
|
+
const EMPTY_PROPS_SCOPE: PropsScope = { bindings: EMPTY_MAP, destructured: EMPTY_MAP }
|
|
55
|
+
const UI_FORM_CONTROL_TAGS = new Set(['Checkbox', 'RadioGroup', 'Switch', 'Select'])
|
|
56
|
+
const NON_INPUT_UI_TAGS = new Set([
|
|
57
|
+
'Button', 'Icon', 'Stack', 'Cluster', 'Notice', 'Badge', 'Card', 'CardHeader', 'CardBody', 'CardFooter',
|
|
58
|
+
'Divider', 'Spinner', 'Field', 'Grid', 'Sidebar', 'Split', 'Accordion', 'AccordionItem', 'Popover', 'Progress',
|
|
59
|
+
'Tabs', 'Dialog', 'ControlledDialog', 'Drawer', 'ControlledDrawer', 'Menu', 'DataTable', 'CommandPalette',
|
|
60
|
+
'Toaster', 'Alert', 'Tooltip', 'Separator', 'Spacer', 'Box', 'Flex', 'Container', 'Heading', 'Text', 'Avatar',
|
|
61
|
+
'Skeleton', 'Image', 'Picture', 'Link',
|
|
62
|
+
])
|
|
63
|
+
|
|
64
|
+
async function tryDirectImport(file: string, hash: string): Promise<Record<string, unknown> | undefined> {
|
|
65
|
+
try { return await import(`${file}?pru-form=${hash}`) as Record<string, unknown> }
|
|
66
|
+
catch { return undefined }
|
|
67
|
+
}
|
|
68
|
+
|
|
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
|
+
}
|
|
83
|
+
|
|
84
|
+
async function importActionModule(file: string): Promise<LoadedModule> {
|
|
85
|
+
let hash = '0'
|
|
86
|
+
try { hash = Bun.hash(readFileSync(file)).toString(36) }
|
|
87
|
+
catch (error) { return { failure: messageOf(error) } }
|
|
88
|
+
|
|
89
|
+
const direct = await tryDirectImport(file, hash)
|
|
90
|
+
if (direct !== undefined) return { mod: direct }
|
|
91
|
+
|
|
92
|
+
try {
|
|
93
|
+
const built = await Bun.build({
|
|
94
|
+
entrypoints: [file],
|
|
95
|
+
target: 'bun',
|
|
96
|
+
plugins: [{
|
|
97
|
+
name: 'prunelle-form-check-resolve',
|
|
98
|
+
setup(b) {
|
|
99
|
+
b.onResolve({ filter: PRUNELLE_SPECIFIER_RE }, (args) => {
|
|
100
|
+
const resolved = resolvePrunelleSpecifier(args.path)
|
|
101
|
+
return resolved !== undefined ? { path: resolved, external: true } : undefined
|
|
102
|
+
})
|
|
103
|
+
},
|
|
104
|
+
}],
|
|
105
|
+
})
|
|
106
|
+
const output = built.outputs[0]
|
|
107
|
+
if (!built.success || output === undefined) return { failure: built.logs.map(log => log.message).join('; ') || 'it does not bundle' }
|
|
108
|
+
const js = await output.text()
|
|
109
|
+
return { mod: await import(`data:text/javascript;base64,${Buffer.from(js, 'utf8').toString('base64')}`) as Record<string, unknown> }
|
|
110
|
+
}
|
|
111
|
+
catch (error) { return { failure: messageOf(error) } }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function isExportedAction(graph: ModuleGraph, target: ActionRef): boolean {
|
|
115
|
+
const analysis = graph.analyses.get(target.file)
|
|
116
|
+
return analysis !== undefined && analysis.exportedActions.includes(target.exportName)
|
|
117
|
+
}
|
|
118
|
+
|
|
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 }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function createActionResolver(file: string, analysis: ModuleAnalysis, graph: ModuleGraph): ModuleActionResolver {
|
|
125
|
+
const directActions = new Map<string, ActionRef>()
|
|
126
|
+
const namespaceImports = new Map<string, string>()
|
|
127
|
+
const useActionVars = new Map<string, ActionRef>()
|
|
128
|
+
const useActionCallees = new Set<string>()
|
|
129
|
+
const prunelleNamespaces = new Set<string>()
|
|
130
|
+
|
|
131
|
+
for (const name of analysis.exportedActions)
|
|
132
|
+
directActions.set(name, { file, exportName: name })
|
|
133
|
+
|
|
134
|
+
for (const imp of analysis.imports) {
|
|
135
|
+
if (imp.source === 'prunelle') {
|
|
136
|
+
for (const spec of imp.specifiers) {
|
|
137
|
+
if (spec.imported === 'useAction') useActionCallees.add(spec.local)
|
|
138
|
+
else if (spec.imported === '*') prunelleNamespaces.add(spec.local)
|
|
139
|
+
}
|
|
140
|
+
continue
|
|
141
|
+
}
|
|
142
|
+
const target = graph.resolve(file, imp.source)
|
|
143
|
+
if (target === undefined || !isTsFile(target) || !graph.analyses.has(target)) continue
|
|
144
|
+
for (const spec of imp.specifiers) {
|
|
145
|
+
if (spec.imported === '*') { namespaceImports.set(spec.local, target); continue }
|
|
146
|
+
const resolved = safeExportTarget(graph, target, spec.imported)
|
|
147
|
+
if (isExportedAction(graph, resolved)) directActions.set(spec.local, resolved)
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const resolveBase = (node: Node): ActionRef | undefined => {
|
|
152
|
+
const inner = unwrapTsExpr(node)
|
|
153
|
+
if (inner.type === 'Identifier') return directActions.get(inner.name)
|
|
154
|
+
if (inner.type === 'MemberExpression' && !inner.computed && inner.object.type === 'Identifier' && inner.property.type === 'Identifier') {
|
|
155
|
+
if (inner.property.name === 'action' && useActionVars.has(inner.object.name))
|
|
156
|
+
return useActionVars.get(inner.object.name)
|
|
157
|
+
const nsFile = namespaceImports.get(inner.object.name)
|
|
158
|
+
if (nsFile !== undefined) {
|
|
159
|
+
const resolved = safeExportTarget(graph, nsFile, inner.property.name)
|
|
160
|
+
if (isExportedAction(graph, resolved)) return resolved
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return undefined
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const isUseActionCall = (node: Node): boolean => {
|
|
167
|
+
if (node.type !== 'CallExpression') return false
|
|
168
|
+
const name = calleeName(node.callee)
|
|
169
|
+
return useActionCallees.has(name) || (name.endsWith('.useAction') && prunelleNamespaces.has(name.slice(0, -'.useAction'.length)))
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
walk(analysis.program, (node) => {
|
|
173
|
+
if (node.type !== 'VariableDeclarator' || node.init === null) return
|
|
174
|
+
const init = unwrapTsExpr(node.init)
|
|
175
|
+
if (isUseActionCall(init) && init.type === 'CallExpression' && init.arguments.length >= 1) {
|
|
176
|
+
const arg = init.arguments[0]
|
|
177
|
+
const target = arg !== undefined && arg.type !== 'SpreadElement' ? resolveBase(arg) : undefined
|
|
178
|
+
if (target === undefined) return
|
|
179
|
+
if (node.id.type === 'Identifier') { useActionVars.set(node.id.name, target); return }
|
|
180
|
+
if (node.id.type === 'ObjectPattern') {
|
|
181
|
+
for (const prop of node.id.properties) {
|
|
182
|
+
if (prop.type === 'Property' && !prop.computed && prop.key.type === 'Identifier' && prop.key.name === 'action' && prop.value.type === 'Identifier')
|
|
183
|
+
directActions.set(prop.value.name, target)
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return
|
|
187
|
+
}
|
|
188
|
+
if (node.id.type === 'Identifier') {
|
|
189
|
+
const ref = resolveBase(init)
|
|
190
|
+
if (ref !== undefined) directActions.set(node.id.name, ref)
|
|
191
|
+
}
|
|
192
|
+
})
|
|
193
|
+
|
|
194
|
+
return { resolveExpr: resolveBase }
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function findAttr(attrs: readonly JSXElement['openingElement']['attributes'][number][], name: string): JSXAttribute | undefined {
|
|
198
|
+
for (const attr of attrs)
|
|
199
|
+
if (attr.type === 'JSXAttribute' && jsxTagName(attr.name).toLowerCase() === name) return attr
|
|
200
|
+
return undefined
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function extractPropsScope(fnNode: Node, bindings: ReadonlyMap<string, string>): PropsScope {
|
|
204
|
+
if (bindings.size === 0) return EMPTY_PROPS_SCOPE
|
|
205
|
+
const inner = unwrapTsExpr(fnNode)
|
|
206
|
+
if (inner.type !== 'FunctionDeclaration' && inner.type !== 'FunctionExpression' && inner.type !== 'ArrowFunctionExpression')
|
|
207
|
+
return EMPTY_PROPS_SCOPE
|
|
208
|
+
const rawFirst = inner.params[0]
|
|
209
|
+
if (rawFirst === undefined) return EMPTY_PROPS_SCOPE
|
|
210
|
+
const first = rawFirst.type === 'AssignmentPattern' ? rawFirst.left : rawFirst
|
|
211
|
+
if (first.type === 'Identifier') return { bindings, propsParam: first.name, destructured: EMPTY_MAP }
|
|
212
|
+
if (first.type !== 'ObjectPattern') return EMPTY_PROPS_SCOPE
|
|
213
|
+
const destructured = new Map<string, string>()
|
|
214
|
+
for (const prop of first.properties) {
|
|
215
|
+
if (prop.type !== 'Property' || prop.computed) continue
|
|
216
|
+
const key = prop.key.type === 'Identifier' ? prop.key.name : prop.key.type === 'Literal' && typeof prop.key.value === 'string' ? prop.key.value : undefined
|
|
217
|
+
const val = prop.value.type === 'AssignmentPattern' ? prop.value.left : prop.value
|
|
218
|
+
if (key !== undefined && val.type === 'Identifier') destructured.set(val.name, key)
|
|
219
|
+
}
|
|
220
|
+
return { bindings, destructured }
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function resolveStaticStringAttr(attr: JSXAttribute | undefined, props: PropsScope): { known: true, value: string } | { known: false } {
|
|
224
|
+
if (attr === undefined || attr.value === null) return { known: false }
|
|
225
|
+
if (attr.value.type === 'Literal' && typeof attr.value.value === 'string') return { known: true, value: attr.value.value }
|
|
226
|
+
if (attr.value.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
|
|
227
|
+
const expr = unwrapTsExpr(attr.value.expression)
|
|
228
|
+
const lit = staticLiteralOrTemplate(expr)
|
|
229
|
+
if (lit.ok && typeof lit.value === 'string') return { known: true, value: lit.value }
|
|
230
|
+
if (expr.type === 'Identifier') {
|
|
231
|
+
const propKey = props.destructured.get(expr.name)
|
|
232
|
+
if (propKey !== undefined && props.bindings.has(propKey)) return { known: true, value: props.bindings.get(propKey)! }
|
|
233
|
+
}
|
|
234
|
+
if (expr.type === 'MemberExpression' && !expr.computed && expr.object.type === 'Identifier' && props.propsParam !== undefined && expr.object.name === props.propsParam && expr.property.type === 'Identifier' && props.bindings.has(expr.property.name))
|
|
235
|
+
return { known: true, value: props.bindings.get(expr.property.name)! }
|
|
236
|
+
}
|
|
237
|
+
return { known: false }
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function isKnownNonInputExternal(tag: string, attrs: readonly JSXElement['openingElement']['attributes'][number][], analysis: ModuleAnalysis): boolean {
|
|
241
|
+
const hasNameAttr = findAttr(attrs, 'name') !== undefined
|
|
242
|
+
const dotIdx = tag.indexOf('.')
|
|
243
|
+
for (const imp of analysis.imports) {
|
|
244
|
+
if (imp.source.startsWith('.') || imp.source.startsWith('/')) continue
|
|
245
|
+
for (const spec of imp.specifiers) {
|
|
246
|
+
let importedName: string | undefined
|
|
247
|
+
if (dotIdx === -1 && spec.local === tag && spec.imported !== '*')
|
|
248
|
+
importedName = spec.imported === 'default' ? tag : spec.imported
|
|
249
|
+
else if (dotIdx !== -1 && spec.imported === '*' && spec.local === tag.slice(0, dotIdx))
|
|
250
|
+
importedName = tag.slice(dotIdx + 1)
|
|
251
|
+
if (importedName === undefined) continue
|
|
252
|
+
if (imp.source === '@prunellejs/icons' || imp.source.startsWith('@prunellejs/icons/') || imp.source === '@prunellejs/images' || imp.source.startsWith('@prunellejs/images/'))
|
|
253
|
+
return true
|
|
254
|
+
if (imp.source === '@prunellejs/ui' || imp.source.startsWith('@prunellejs/ui/'))
|
|
255
|
+
return !UI_FORM_CONTROL_TAGS.has(importedName) && (importedName !== 'Button' || !hasNameAttr)
|
|
256
|
+
return (NON_INPUT_UI_TAGS.has(importedName) || NON_INPUT_UI_TAGS.has(tag)) && (importedName !== 'Button' || !hasNameAttr)
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
return false
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function findLocalComponentNode(program: Program, localName: string): Node | undefined {
|
|
263
|
+
for (const stmt of program.body) {
|
|
264
|
+
if (stmt.type === 'ExportDefaultDeclaration' && localName === 'default')
|
|
265
|
+
return unwrapTsExpr(stmt.declaration)
|
|
266
|
+
const decl = stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt
|
|
267
|
+
if (decl?.type === 'FunctionDeclaration' && decl.id?.name === localName) return decl
|
|
268
|
+
if (decl?.type === 'VariableDeclaration') {
|
|
269
|
+
for (const d of decl.declarations)
|
|
270
|
+
if (d.id.type === 'Identifier' && d.id.name === localName && d.init !== null) return unwrapTsExpr(d.init)
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return undefined
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function resolveComponentTarget(
|
|
277
|
+
tag: string,
|
|
278
|
+
file: string,
|
|
279
|
+
analysis: ModuleAnalysis,
|
|
280
|
+
graph: ModuleGraph,
|
|
281
|
+
): { file: string, node: Node, key: string } | undefined {
|
|
282
|
+
const local = findLocalComponentNode(analysis.program, tag)
|
|
283
|
+
if (local !== undefined) return { file, node: local, key: `${file}\0${tag}` }
|
|
284
|
+
|
|
285
|
+
const dotIdx = tag.indexOf('.')
|
|
286
|
+
for (const imp of analysis.imports) {
|
|
287
|
+
const targetFile = graph.resolve(file, imp.source)
|
|
288
|
+
if (targetFile === undefined || !isTsFile(targetFile) || !graph.analyses.has(targetFile)) continue
|
|
289
|
+
for (const spec of imp.specifiers) {
|
|
290
|
+
const exported = dotIdx === -1 && spec.local === tag && spec.imported !== '*'
|
|
291
|
+
? spec.imported
|
|
292
|
+
: dotIdx !== -1 && spec.imported === '*' && spec.local === tag.slice(0, dotIdx)
|
|
293
|
+
? tag.slice(dotIdx + 1)
|
|
294
|
+
: undefined
|
|
295
|
+
if (exported === undefined) continue
|
|
296
|
+
const resolved = graph.exportTarget(targetFile, exported)
|
|
297
|
+
const targetAnalysis = graph.analyses.get(resolved.file)
|
|
298
|
+
if (targetAnalysis === undefined) continue
|
|
299
|
+
const localName = targetAnalysis.exportLocals.get(resolved.exportName) ?? resolved.exportName
|
|
300
|
+
const fnNode = findLocalComponentNode(targetAnalysis.program, localName)
|
|
301
|
+
if (fnNode !== undefined) return { file: resolved.file, node: fnNode, key: `${resolved.file}\0${localName}` }
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return undefined
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function collectSelectOptions(selectEl: JSXElement, file: string): SelectOptionInfo[] {
|
|
308
|
+
const options: SelectOptionInfo[] = []
|
|
309
|
+
walk(selectEl.children, (node) => {
|
|
310
|
+
if (node.type !== 'JSXElement') return undefined
|
|
311
|
+
const tag = jsxTagName(node.openingElement.name)
|
|
312
|
+
if (tag === 'select') return false
|
|
313
|
+
if (tag !== 'option') return undefined
|
|
314
|
+
const valueAttr = findAttr(node.openingElement.attributes, 'value')
|
|
315
|
+
if (valueAttr !== undefined) {
|
|
316
|
+
if (valueAttr.value?.type === 'Literal' && typeof valueAttr.value.value === 'string') {
|
|
317
|
+
options.push({ value: valueAttr.value.value, file, offset: valueAttr.start })
|
|
318
|
+
}
|
|
319
|
+
else if (valueAttr.value?.type === 'JSXExpressionContainer' && valueAttr.value.expression.type !== 'JSXEmptyExpression') {
|
|
320
|
+
const lit = staticLiteralOrTemplate(valueAttr.value.expression)
|
|
321
|
+
if (lit.ok && (typeof lit.value === 'string' || typeof lit.value === 'number'))
|
|
322
|
+
options.push({ value: String(lit.value), file, offset: valueAttr.start })
|
|
323
|
+
}
|
|
324
|
+
return false
|
|
325
|
+
}
|
|
326
|
+
const text = staticOptionText(node.children)
|
|
327
|
+
if (text !== undefined) options.push({ value: text, file, offset: node.start })
|
|
328
|
+
return false
|
|
329
|
+
})
|
|
330
|
+
return options
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function controlFormMatch(
|
|
334
|
+
attrs: readonly JSXElement['openingElement']['attributes'][number][],
|
|
335
|
+
propsScope: PropsScope,
|
|
336
|
+
formId: string | undefined,
|
|
337
|
+
hasDynamicId: boolean,
|
|
338
|
+
externalOnly: boolean,
|
|
339
|
+
): 'match' | 'skip' | 'opaque' {
|
|
340
|
+
const formAttr = findAttr(attrs, 'form')
|
|
341
|
+
if (formAttr === undefined) return externalOnly ? 'skip' : 'match'
|
|
342
|
+
const target = resolveStaticStringAttr(formAttr, propsScope)
|
|
343
|
+
if (!target.known) return 'opaque'
|
|
344
|
+
if (formId !== undefined && target.value === formId) return 'match'
|
|
345
|
+
return hasDynamicId ? 'opaque' : 'skip'
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function recordControlField(node: JSXElement, tag: string, file: string, propsScope: PropsScope, fields: CollectedField[]): boolean {
|
|
349
|
+
const attrs = node.openingElement.attributes
|
|
350
|
+
const nameAttr = findAttr(attrs, 'name')
|
|
351
|
+
const hasSpread = attrs.some(a => a.type === 'JSXSpreadAttribute')
|
|
352
|
+
if (tag === 'button') {
|
|
353
|
+
if (nameAttr === undefined) return false
|
|
354
|
+
const typeVal = resolveStaticStringAttr(findAttr(attrs, 'type'), propsScope)
|
|
355
|
+
if (typeVal.known && (typeVal.value.toLowerCase() === 'button' || typeVal.value.toLowerCase() === 'reset')) return false
|
|
356
|
+
}
|
|
357
|
+
if (nameAttr === undefined) return hasSpread && tag !== 'button'
|
|
358
|
+
const resolvedName = resolveStaticStringAttr(nameAttr, propsScope)
|
|
359
|
+
if (!resolvedName.known) return true
|
|
360
|
+
if (resolvedName.value !== '') {
|
|
361
|
+
fields.push({
|
|
362
|
+
name: resolvedName.value,
|
|
363
|
+
tag,
|
|
364
|
+
file,
|
|
365
|
+
offset: nameAttr.start,
|
|
366
|
+
...(tag === 'select' ? { options: collectSelectOptions(node, file) } : {}),
|
|
367
|
+
})
|
|
368
|
+
}
|
|
369
|
+
return false
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function collectFormFields(formNode: JSXElement, enclosingRoot: Node, rootFile: string, graph: ModuleGraph): { fields: CollectedField[], hasOpaqueFields: boolean } {
|
|
373
|
+
const fields: CollectedField[] = []
|
|
374
|
+
let hasOpaqueFields = false
|
|
375
|
+
const formAttrs = formNode.openingElement.attributes
|
|
376
|
+
const idAttr = findAttr(formAttrs, 'id')
|
|
377
|
+
const idVal = resolveStaticStringAttr(idAttr, EMPTY_PROPS_SCOPE)
|
|
378
|
+
const formId = idVal.known && idVal.value !== '' ? idVal.value : undefined
|
|
379
|
+
const hasDynamicId = (idAttr !== undefined && !idVal.known) || (idAttr === undefined && formAttrs.some(a => a.type === 'JSXSpreadAttribute'))
|
|
380
|
+
|
|
381
|
+
const visitTree = (target: Node | readonly Node[], file: string, propsScope: PropsScope, visited: ReadonlySet<string>, externalOnly: boolean): void => {
|
|
382
|
+
const analysis = graph.analyses.get(file)
|
|
383
|
+
if (analysis === undefined) return
|
|
384
|
+
|
|
385
|
+
walk(target, (node) => {
|
|
386
|
+
if (node.type !== 'JSXElement') return undefined
|
|
387
|
+
if (node === formNode) return false
|
|
388
|
+
const tag = jsxTagName(node.openingElement.name)
|
|
389
|
+
if (!externalOnly && tag === 'form') return false
|
|
390
|
+
|
|
391
|
+
if (tag === 'input' || tag === 'select' || tag === 'textarea' || tag === 'button') {
|
|
392
|
+
const match = controlFormMatch(node.openingElement.attributes, propsScope, formId, hasDynamicId, externalOnly)
|
|
393
|
+
if (match === 'opaque') hasOpaqueFields = true
|
|
394
|
+
else if (match === 'match' && recordControlField(node, tag, file, propsScope, fields)) hasOpaqueFields = true
|
|
395
|
+
return tag === 'select' ? false : undefined
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
if (isComponentTag(tag)) {
|
|
399
|
+
if (node.children.length > 0) visitTree(node.children, file, propsScope, visited, externalOnly)
|
|
400
|
+
if (resolvePrunelleTag(tag, analysis.imports) !== undefined) return false
|
|
401
|
+
const resolved = resolveComponentTarget(tag, file, analysis, graph)
|
|
402
|
+
if (resolved === undefined) {
|
|
403
|
+
if (!externalOnly && !isKnownNonInputExternal(tag, node.openingElement.attributes, analysis)) hasOpaqueFields = true
|
|
404
|
+
return false
|
|
405
|
+
}
|
|
406
|
+
if (visited.has(resolved.key)) return false
|
|
407
|
+
const nextBindings = new Map<string, string>()
|
|
408
|
+
for (const attr of node.openingElement.attributes) {
|
|
409
|
+
if (attr.type !== 'JSXAttribute') continue
|
|
410
|
+
const val = resolveStaticStringAttr(attr, propsScope)
|
|
411
|
+
if (val.known) nextBindings.set(jsxTagName(attr.name), val.value)
|
|
412
|
+
}
|
|
413
|
+
const nextVisited = new Set(visited)
|
|
414
|
+
nextVisited.add(resolved.key)
|
|
415
|
+
visitTree(resolved.node, resolved.file, extractPropsScope(resolved.node, nextBindings), nextVisited, externalOnly)
|
|
416
|
+
return false
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
return undefined
|
|
420
|
+
})
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
visitTree(formNode.children, rootFile, EMPTY_PROPS_SCOPE, new Set(), false)
|
|
424
|
+
if (formId !== undefined || hasDynamicId)
|
|
425
|
+
visitTree(enclosingRoot, rootFile, EMPTY_PROPS_SCOPE, new Set(), true)
|
|
426
|
+
return { fields, hasOpaqueFields }
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
function collectModuleForms(file: string, analysis: ModuleAnalysis, graph: ModuleGraph): CollectedForm[] {
|
|
430
|
+
const resolver = createActionResolver(file, analysis, graph)
|
|
431
|
+
const forms: CollectedForm[] = []
|
|
432
|
+
|
|
433
|
+
walk(analysis.program, (node) => {
|
|
434
|
+
if (node.type !== 'JSXElement' || jsxTagName(node.openingElement.name) !== 'form') return undefined
|
|
435
|
+
const actionAttr = findAttr(node.openingElement.attributes, 'action')
|
|
436
|
+
if (actionAttr?.value?.type !== 'JSXExpressionContainer' || actionAttr.value.expression.type === 'JSXEmptyExpression') return undefined
|
|
437
|
+
const actionRef = resolver.resolveExpr(actionAttr.value.expression)
|
|
438
|
+
if (actionRef === undefined) return undefined
|
|
439
|
+
const enclosingRoot = analysis.program.body.find(stmt => node.start >= stmt.start && node.end <= stmt.end) ?? analysis.program
|
|
440
|
+
const { fields, hasOpaqueFields } = collectFormFields(node, enclosingRoot, file, graph)
|
|
441
|
+
forms.push({ action: actionRef, file, offset: node.start, fields, hasOpaqueFields })
|
|
442
|
+
return undefined
|
|
443
|
+
})
|
|
444
|
+
|
|
445
|
+
return forms
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function buildMiddlewareLookup(routesDir: string, routeFiles: readonly string[], graph: ModuleGraph) {
|
|
449
|
+
const middlewareDirs = new Set<string>()
|
|
450
|
+
const layoutByDir = new Map<string, string>()
|
|
451
|
+
const pageRouteSet = new Set<string>()
|
|
452
|
+
for (const file of routeFiles) {
|
|
453
|
+
const base = basename(file)
|
|
454
|
+
if (base === '_middleware.ts' || base === '_middleware.tsx') middlewareDirs.add(dirname(file))
|
|
455
|
+
else if (base === '_layout.tsx') layoutByDir.set(dirname(file), file)
|
|
456
|
+
else if (!base.startsWith('_') && graph.analyses.get(file)?.exportedNames.includes('default')) pageRouteSet.add(file)
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
const walkAncestorDirs = (file: string, onDir: (dir: string) => boolean | void): boolean => {
|
|
460
|
+
if (!isInside(routesDir, file)) return false
|
|
461
|
+
let dir = dirname(file)
|
|
462
|
+
while (true) {
|
|
463
|
+
if (onDir(dir) === true) return true
|
|
464
|
+
if (dir === routesDir) return false
|
|
465
|
+
const parent = dirname(dir)
|
|
466
|
+
if (parent === dir || !isInside(routesDir, parent, { orSame: true })) return false
|
|
467
|
+
dir = parent
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
const hasAncestorMiddleware = (file: string): boolean => walkAncestorDirs(file, dir => middlewareDirs.has(dir))
|
|
472
|
+
|
|
473
|
+
const importers = new Map<string, Set<string>>()
|
|
474
|
+
const addImporter = (dep: string, owner: string): void => {
|
|
475
|
+
let set = importers.get(dep)
|
|
476
|
+
if (set === undefined) { set = new Set(); importers.set(dep, set) }
|
|
477
|
+
set.add(owner)
|
|
478
|
+
}
|
|
479
|
+
for (const file of graph.analyses.keys())
|
|
480
|
+
for (const dep of graph.localDeps(file)) addImporter(dep, file)
|
|
481
|
+
for (const page of pageRouteSet) {
|
|
482
|
+
walkAncestorDirs(page, (dir) => {
|
|
483
|
+
const layout = layoutByDir.get(dir)
|
|
484
|
+
if (layout !== undefined) addImporter(layout, page)
|
|
485
|
+
})
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
// Every page that renders `file`, through imports and through the layouts above it.
|
|
489
|
+
const pagesRendering = (file: string): string[] => {
|
|
490
|
+
const seen = new Set<string>([file])
|
|
491
|
+
const queue = [file]
|
|
492
|
+
for (let i = 0; i < queue.length; i++) {
|
|
493
|
+
for (const parent of importers.get(queue[i]!) ?? [])
|
|
494
|
+
if (!seen.has(parent)) { seen.add(parent); queue.push(parent) }
|
|
495
|
+
}
|
|
496
|
+
return queue.filter(cur => pageRouteSet.has(cur))
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
return { hasAncestorMiddleware, pagesRendering }
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/** The `patternProperties` keys of a schema as regexes: a field name one matches is a key the schema accepts. */
|
|
503
|
+
function fieldPatterns(patternProperties: unknown): RegExp[] {
|
|
504
|
+
if (!isRecord(patternProperties))
|
|
505
|
+
return []
|
|
506
|
+
return Object.keys(patternProperties).flatMap((source) => {
|
|
507
|
+
try {
|
|
508
|
+
return [new RegExp(source, 'u')]
|
|
509
|
+
}
|
|
510
|
+
catch {
|
|
511
|
+
return []
|
|
512
|
+
}
|
|
513
|
+
})
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
function checkFormAgainstAction(
|
|
517
|
+
form: CollectedForm,
|
|
518
|
+
act: ServerAction<unknown, unknown>,
|
|
519
|
+
locAt: (file: string, offset: number) => string,
|
|
520
|
+
warnedVendors: Set<string>,
|
|
521
|
+
errors: string[],
|
|
522
|
+
warn: WarnAt,
|
|
523
|
+
): void {
|
|
524
|
+
const { exportName } = form.action
|
|
525
|
+
if (act.schema === undefined) return
|
|
526
|
+
|
|
527
|
+
const extracted = extractFormSchema(act.schema)
|
|
528
|
+
if (!extracted.ok) {
|
|
529
|
+
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.`))
|
|
530
|
+
warnedVendors.add(extracted.vendor)
|
|
531
|
+
return
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
const hpField = honeypotFieldName(act.protect)
|
|
535
|
+
const knownFields = [...extracted.fields.keys()]
|
|
536
|
+
const extra = extracted.jsonSchema.additionalProperties
|
|
537
|
+
const checkUnknown = extra !== true && !isRecord(extra) && (extracted.fields.size > 0 || extra === false)
|
|
538
|
+
const patterns = fieldPatterns(extracted.jsonSchema.patternProperties)
|
|
539
|
+
const sentFields = new Set<string>()
|
|
540
|
+
|
|
541
|
+
for (const field of form.fields) {
|
|
542
|
+
if (field.name === FORM_TIMESTAMP_FIELD || (hpField !== undefined && field.name === hpField)) continue
|
|
543
|
+
const normalized = field.name.endsWith('[]') ? field.name.slice(0, -2) : field.name
|
|
544
|
+
sentFields.add(field.name)
|
|
545
|
+
sentFields.add(normalized)
|
|
546
|
+
|
|
547
|
+
const constraint = lookupFieldConstraint(extracted.fields, field.name)
|
|
548
|
+
if (constraint === undefined && checkUnknown && !patterns.some(re => re.test(normalized))) {
|
|
549
|
+
const near = closestName(normalized, knownFields)
|
|
550
|
+
const hint = near !== undefined ? `did you mean "${near}"?` : knownFields.length > 0 ? `known fields: ${knownFields.join(', ')}.` : 'the schema accepts no fields.'
|
|
551
|
+
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'))
|
|
552
|
+
continue
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
if (field.options !== undefined && constraint?.enumValues !== undefined && constraint.enumValues.length > 0) {
|
|
556
|
+
const allowed = new Set(constraint.enumValues)
|
|
557
|
+
for (const opt of field.options) {
|
|
558
|
+
if (opt.value === '' || allowed.has(opt.value)) continue
|
|
559
|
+
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(', ')}).`)
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
if (!form.hasOpaqueFields) {
|
|
565
|
+
const sentList = [...sentFields]
|
|
566
|
+
for (const reqField of extracted.required) {
|
|
567
|
+
if (sentFields.has(reqField)) continue
|
|
568
|
+
const near = closestName(reqField, sentList)
|
|
569
|
+
const hint = near !== undefined ? ` (found "${near}")` : ''
|
|
570
|
+
errors.push(formatDiagnostic(locAt(form.file, form.offset), `[form/missing-field] Form bound to action "${exportName}" never sends required schema field "${reqField}"${hint}.`, 'error'))
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/** A `protect.minTime` form on a prerendered or cached page: its signed `_pru_ts` is rendered once and handed to every visitor. */
|
|
576
|
+
function frozenTimestampErrors(form: CollectedForm, pages: readonly string[], graph: ModuleGraph, loc: string, relOf: (file: string) => string): string[] {
|
|
577
|
+
const errors: string[] = []
|
|
578
|
+
for (const page of pages) {
|
|
579
|
+
const analysis = graph.analyses.get(page)
|
|
580
|
+
const frozenBy = analysis?.hasPrerender === true ? 'prerender = true' : analysis?.cache !== undefined ? 'cache' : undefined
|
|
581
|
+
if (frozenBy === undefined) continue
|
|
582
|
+
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'))
|
|
583
|
+
}
|
|
584
|
+
return errors
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
/** Checks every `<form action={fn}>` across the app against its action's schema and public protection config. */
|
|
588
|
+
export async function checkAppForms(input: FormCheckInput): Promise<FormCheckResult> {
|
|
589
|
+
const { root, routesDir, routeFiles, graph, sources } = input
|
|
590
|
+
const errors: string[] = []
|
|
591
|
+
const warnings: string[] = []
|
|
592
|
+
const moduleCache = new Map<string, LoadedModule>()
|
|
593
|
+
const unimportable = new Set<string>()
|
|
594
|
+
const warnedVendors = new Set<string>()
|
|
595
|
+
const { hasAncestorMiddleware, pagesRendering } = buildMiddlewareLookup(routesDir, routeFiles, graph)
|
|
596
|
+
|
|
597
|
+
const sourceOf = (file: string): string => sources?.get(file) ?? graph.source(file)
|
|
598
|
+
const locAt = (targetFile: string, offset: number): string => formatLoc(relPosix(root, targetFile), sourceOf(targetFile), offset)
|
|
599
|
+
const ignoresByFile = new Map<string, ReturnType<typeof parsePrunelleIgnores>>()
|
|
600
|
+
const warn: WarnAt = (rule, file, offset, message) => {
|
|
601
|
+
if (isRuleIgnored(rule, input.compliance)) return false
|
|
602
|
+
let ignores = ignoresByFile.get(file)
|
|
603
|
+
if (ignores === undefined) { ignores = parsePrunelleIgnores(sourceOf(file)); ignoresByFile.set(file, ignores) }
|
|
604
|
+
if (isIgnoredAt(ignores, rule, offset)) return false
|
|
605
|
+
warnings.push(formatDiagnostic(locAt(file, offset), `[${rule}] ${message}`, 'warning'))
|
|
606
|
+
return true
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
for (const [file, analysis] of graph.analyses) {
|
|
610
|
+
if (isInNodeModules(file) || !file.endsWith('.tsx') || !analysis.hasJsx) continue
|
|
611
|
+
const forms = collectModuleForms(file, analysis, graph)
|
|
612
|
+
if (forms.length === 0) continue
|
|
613
|
+
|
|
614
|
+
const pages = pagesRendering(file)
|
|
615
|
+
const publicPage = pages.some(page => !hasAncestorMiddleware(page))
|
|
616
|
+
for (const form of forms) {
|
|
617
|
+
const loaded = await loadActionModule(form.action.file, moduleCache)
|
|
618
|
+
if ('failure' in loaded) {
|
|
619
|
+
if (!unimportable.has(form.action.file) && 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.`))
|
|
620
|
+
unimportable.add(form.action.file)
|
|
621
|
+
continue
|
|
622
|
+
}
|
|
623
|
+
const act = loaded.mod[form.action.exportName]
|
|
624
|
+
if (!isServerAction(act)) continue
|
|
625
|
+
|
|
626
|
+
checkFormAgainstAction(form, act, locAt, warnedVendors, errors, warn)
|
|
627
|
+
if (act.protect?.minTime !== undefined)
|
|
628
|
+
errors.push(...frozenTimestampErrors(form, pages, graph, locAt(form.file, form.offset), page => relPosix(root, page)))
|
|
629
|
+
|
|
630
|
+
if (publicPage && !hasAncestorMiddleware(form.action.file) && act.protect === undefined && act.rateLimit === undefined)
|
|
631
|
+
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.`)
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
return { errors, warnings }
|
|
636
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
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
|
+
import { assertNoForeignImport } from '../compiler/foreign-imports'
|
|
5
|
+
import { collectMistakes } from '../compiler/mistakes'
|
|
6
|
+
|
|
7
|
+
const SKIPPED = /^(?:prunelle(?:\/|$)|@kayjs\/|~icons\/|virtual:)/
|
|
8
|
+
|
|
9
|
+
function isRefusedForeignImport(file: string, source: string, specifiers: readonly { imported: string }[]): boolean {
|
|
10
|
+
return specifiers.some(s => collectMistakes(() => assertNoForeignImport(source, s.imported, file)).error !== undefined)
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** The problem with an import specifier Bun's resolver finds nothing for, or undefined when it resolves or prunelle resolves it itself. */
|
|
14
|
+
export function unresolvedImport(file: string, rel: string, source: string, specifiers: readonly { imported: string }[] = []): string | undefined {
|
|
15
|
+
if (SKIPPED.test(source) || isRefusedForeignImport(file, source, specifiers))
|
|
16
|
+
return undefined
|
|
17
|
+
try {
|
|
18
|
+
Bun.resolveSync(source, dirname(file))
|
|
19
|
+
return undefined
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return source.startsWith('.')
|
|
23
|
+
? `prunelle check: import '${source}' in ${rel} does not resolve to a file: create it, or fix the path.`
|
|
24
|
+
: `prunelle check: import '${source}' in ${rel} does not resolve to a package: run bun add ${packageName(source)}, or fix the name.`
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function packageName(source: string): string {
|
|
29
|
+
const parts = source.split('/')
|
|
30
|
+
return source.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0]!
|
|
31
|
+
}
|