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.
Files changed (128) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +48 -43
  3. package/package.json +4 -1
  4. package/src/a11y/declaration.ts +106 -72
  5. package/src/a11y/index.ts +59 -39
  6. package/src/a11y/rgaa-map.ts +95 -49
  7. package/src/build/bundle.ts +8 -4
  8. package/src/build/byte-size.ts +11 -0
  9. package/src/build/client-plugin.ts +3 -1
  10. package/src/build/compile.ts +2 -1
  11. package/src/build/ecoindex.ts +15 -14
  12. package/src/build/files.ts +6 -0
  13. package/src/build/first-load.ts +83 -11
  14. package/src/build/graph.ts +29 -39
  15. package/src/build/index.ts +57 -18
  16. package/src/build/island-promote.ts +229 -0
  17. package/src/build/islands.ts +9 -201
  18. package/src/build/manifest.ts +4 -125
  19. package/src/build/plugin-host.ts +21 -8
  20. package/src/build/precompress.ts +1 -1
  21. package/src/build/prerender.ts +97 -44
  22. package/src/build/reach.ts +136 -0
  23. package/src/build/render-rules.ts +2 -2
  24. package/src/build/report.ts +19 -3
  25. package/src/build/static-headers.ts +93 -0
  26. package/src/build/static.ts +2 -0
  27. package/src/cli/check-forms.ts +97 -48
  28. package/src/cli/check-imports.ts +25 -0
  29. package/src/cli/check-links.ts +2 -2
  30. package/src/cli/check-security.ts +64 -0
  31. package/src/cli/check.ts +33 -7
  32. package/src/cli/commands.ts +35 -7
  33. package/src/cli/docs.ts +4 -3
  34. package/src/cli/inspect.ts +2 -1
  35. package/src/cli/mcp-tools.ts +7 -5
  36. package/src/cli/mcp.ts +1 -1
  37. package/src/cli/new.ts +14 -3
  38. package/src/cli/render.ts +14 -19
  39. package/src/cli/upgrade.ts +22 -5
  40. package/src/compiler/analyze.ts +26 -5
  41. package/src/compiler/cacheability.ts +2 -2
  42. package/src/compiler/compliance-eco.ts +71 -0
  43. package/src/compiler/compliance-rgaa.ts +110 -4
  44. package/src/compiler/compliance-urls.ts +145 -0
  45. package/src/compiler/compliance.ts +168 -116
  46. package/src/compiler/foreign-imports.ts +88 -0
  47. package/src/compiler/mistakes.ts +19 -1
  48. package/src/compiler/props-body.ts +52 -0
  49. package/src/compiler/shared.ts +2 -2
  50. package/src/compiler/ssr.ts +2 -2
  51. package/src/context.ts +34 -0
  52. package/src/dev/error-log.ts +90 -64
  53. package/src/dev/host-check.ts +26 -0
  54. package/src/dev/index.ts +12 -5
  55. package/src/dev/open-editor.ts +15 -11
  56. package/src/dev/protocol.ts +2 -0
  57. package/src/dev/supervisor.ts +8 -0
  58. package/src/dev/watchers.ts +27 -2
  59. package/src/dom/action.ts +4 -1
  60. package/src/dom/extras.ts +1 -2
  61. package/src/dom/index.ts +13 -2
  62. package/src/dom/island.ts +22 -10
  63. package/src/dom/loop.ts +25 -16
  64. package/src/eco/declaration.ts +257 -0
  65. package/src/eco/index.ts +65 -0
  66. package/src/index.ts +2 -2
  67. package/src/jsx-runtime.ts +2 -2
  68. package/src/plugins/config.ts +1 -1
  69. package/src/plugins/context.ts +16 -1
  70. package/src/plugins/load.ts +4 -3
  71. package/src/plugins/public.ts +2 -2
  72. package/src/plugins/services.ts +3 -0
  73. package/src/plugins/types.ts +17 -2
  74. package/src/server/action-flash.ts +158 -0
  75. package/src/server/action-protect.ts +38 -37
  76. package/src/server/action.ts +11 -127
  77. package/src/server/app-secret.ts +63 -0
  78. package/src/server/compress.ts +5 -1
  79. package/src/server/consent.ts +59 -22
  80. package/src/server/cookies.ts +16 -2
  81. package/src/server/env.ts +14 -0
  82. package/src/server/errors.ts +3 -1
  83. package/src/server/form-schema.ts +1 -1
  84. package/src/server/health.ts +46 -15
  85. package/src/server/http.ts +47 -7
  86. package/src/server/index.ts +52 -30
  87. package/src/server/loader.ts +6 -2
  88. package/src/server/plugin-host.ts +3 -1
  89. package/src/server/public.ts +4 -3
  90. package/src/server/rate-limit.ts +52 -9
  91. package/src/server/route-cache.ts +26 -4
  92. package/src/server/route-table.ts +7 -3
  93. package/src/server/routing.ts +3 -87
  94. package/src/server/sanitize-html.ts +309 -0
  95. package/src/server/security.ts +71 -20
  96. package/src/server/serve-handlers.ts +14 -4
  97. package/src/server/start.ts +1 -1
  98. package/src/server/static-dir.ts +27 -4
  99. package/src/server/stream.ts +28 -6
  100. package/src/ssr/consent-banner.ts +58 -0
  101. package/src/ssr/context.ts +20 -4
  102. package/src/ssr/index.ts +18 -0
  103. package/src/ssr/navigation.ts +2 -2
  104. package/src/style.ts +32 -1
  105. package/templates/_shared/gitignore +5 -0
  106. package/templates/_shared/src/routes/legal.tsx +10 -1
  107. package/templates/app/.env.example +4 -0
  108. package/templates/app/package.json +2 -1
  109. package/templates/app/prunelle.config.ts +2 -0
  110. package/templates/app/src/auth.ts +4 -6
  111. package/templates/app/src/mail.ts +4 -0
  112. package/templates/app/src/routes/_layout.tsx +9 -1
  113. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  114. package/templates/app/src/routes/login.tsx +49 -30
  115. package/templates/app/src/routes/privacy.tsx +25 -0
  116. package/templates/app/src/styles/app.css +8 -1
  117. package/templates/app/tests/app.test.ts +44 -3
  118. package/templates/blog/package.json +1 -1
  119. package/templates/blog/src/routes/_layout.tsx +6 -1
  120. package/templates/blog/src/routes/index.tsx +1 -1
  121. package/templates/blog/src/styles/app.css +6 -1
  122. package/templates/fullstack/package.json +1 -1
  123. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  124. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  125. package/templates/fullstack/src/styles/app.css +11 -1
  126. package/templates/minimal/package.json +1 -1
  127. package/templates/minimal/src/routes/_layout.tsx +4 -0
  128. package/templates/minimal/src/styles/app.css +11 -1
@@ -0,0 +1,145 @@
1
+ // The third-party URLs a JSX element makes the browser load, for the rgpd/third-party-url rule.
2
+
3
+ import type { Expression, JSXAttribute, JSXAttributeItem, JSXElement } from 'oxc-parser'
4
+ import { findAttr } from './compliance-rgaa'
5
+ import { unwrapTsExpr } from './shared'
6
+
7
+ // Hosts that only ever mean this machine, never a third party.
8
+ const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]', '0.0.0.0'])
9
+ const LOADING_LINK_RELS = new Set(['stylesheet', 'preload', 'preconnect', 'dns-prefetch', 'modulepreload', 'prefetch', 'prerender', 'icon', 'apple-touch-icon', 'manifest'])
10
+ const SRC_TAGS = new Set(['script', 'iframe', 'img', 'video', 'audio', 'source', 'embed', 'track'])
11
+ const SRCSET_TAGS = new Set(['img', 'source'])
12
+ // SVG elements whose href fetches a resource.
13
+ const SVG_HREF_TAGS = new Set(['image', 'use', 'feImage'])
14
+ export const CSS_IMPORT_RE = /@import\s+(?:url\(\s*)?(?:'([^']+)'|"([^"]+)"|([^'"\s);]+))/gi
15
+ export const CSS_URL_RE = /url\(\s*(?:'([^']+)'|"([^"]+)"|([^'"\s)]+))\s*\)/gi
16
+
17
+ export interface ThirdPartyLoad {
18
+ attr: string
19
+ url: string
20
+ origin: string
21
+ start: number
22
+ }
23
+
24
+ export function parseOrigin(url: string | undefined): string | undefined {
25
+ if (url === undefined || url.trim() === '')
26
+ return undefined
27
+ try {
28
+ return new URL(url.trim()).origin
29
+ }
30
+ catch {
31
+ return undefined
32
+ }
33
+ }
34
+
35
+ /** Returns the external origin when `rawUrl` points to a non-localhost third-party URL, or `undefined` otherwise. */
36
+ export function thirdPartyOrigin(rawUrl: string): string | undefined {
37
+ const trimmed = rawUrl.trim()
38
+ if (!/^(?:https?:)?\/\//i.test(trimmed))
39
+ return undefined
40
+ try {
41
+ const parsed = new URL(trimmed.startsWith('//') ? `https:${trimmed}` : trimmed)
42
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
43
+ return undefined
44
+ const host = parsed.hostname.toLowerCase()
45
+ if (LOCAL_HOSTS.has(host) || host.endsWith('.localhost'))
46
+ return undefined
47
+ return parsed.origin
48
+ }
49
+ catch {
50
+ return undefined
51
+ }
52
+ }
53
+
54
+ // Every string an expression can evaluate to, as far as the source shows it: a template literal gives its leading text, which holds the origin.
55
+ function expressionStrings(expr: Expression): string[] {
56
+ const node = unwrapTsExpr(expr)
57
+ if (node.type === 'Literal')
58
+ return typeof node.value === 'string' ? [node.value] : []
59
+ if (node.type === 'TemplateLiteral')
60
+ return [node.quasis[0]?.value.cooked ?? '']
61
+ if (node.type === 'ConditionalExpression')
62
+ return [...expressionStrings(node.consequent), ...expressionStrings(node.alternate)]
63
+ if (node.type === 'LogicalExpression')
64
+ return [...expressionStrings(node.left), ...expressionStrings(node.right)]
65
+ if (node.type === 'ObjectExpression') {
66
+ return node.properties.flatMap(prop => prop.type === 'Property' ? expressionStrings(prop.value) : [])
67
+ }
68
+ return []
69
+ }
70
+
71
+ function attrStrings(attr: JSXAttribute): string[] {
72
+ const value = attr.value
73
+ if (value === null)
74
+ return []
75
+ if (value.type === 'Literal')
76
+ return typeof value.value === 'string' ? [value.value] : []
77
+ if (value.type === 'JSXExpressionContainer' && value.expression.type !== 'JSXEmptyExpression')
78
+ return expressionStrings(value.expression)
79
+ return []
80
+ }
81
+
82
+ function matches(re: RegExp, text: string): string[] {
83
+ const out: string[] = []
84
+ re.lastIndex = 0
85
+ for (let m = re.exec(text); m !== null; m = re.exec(text)) {
86
+ const url = m[1] ?? m[2] ?? m[3]
87
+ if (url !== undefined)
88
+ out.push(url)
89
+ }
90
+ return out
91
+ }
92
+
93
+ type UrlsOf = (text: string) => string[]
94
+ const whole: UrlsOf = text => [text]
95
+ const srcsetUrls: UrlsOf = text => text.split(',').map(part => part.trim().split(/\s+/, 1)[0] ?? '').filter(Boolean)
96
+ const cssUrls: UrlsOf = text => matches(CSS_URL_RE, text)
97
+
98
+ // `xlink:href`, the only namespaced href there is.
99
+ function findXlinkHref(attributes: readonly JSXAttributeItem[]): JSXAttribute | undefined {
100
+ for (const attr of attributes) {
101
+ if (attr.type === 'JSXAttribute' && attr.name.type === 'JSXNamespacedName' && attr.name.name.name === 'href')
102
+ return attr
103
+ }
104
+ return undefined
105
+ }
106
+
107
+ // The attributes of `tag` that load a resource, each with how its value lists URLs.
108
+ function loadingAttrs(element: JSXElement, tag: string): Array<[string, JSXAttribute | undefined, UrlsOf]> {
109
+ const attrs = element.openingElement.attributes
110
+ const out: Array<[string, JSXAttribute | undefined, UrlsOf]> = [['style', findAttr(attrs, 'style'), cssUrls]]
111
+ if (SRC_TAGS.has(tag))
112
+ out.push(['src', findAttr(attrs, 'src'), whole])
113
+ if (SRCSET_TAGS.has(tag))
114
+ out.push(['srcset', findAttr(attrs, 'srcset'), srcsetUrls])
115
+ if (tag === 'video')
116
+ out.push(['poster', findAttr(attrs, 'poster'), whole])
117
+ if (tag === 'object')
118
+ out.push(['data', findAttr(attrs, 'data'), whole])
119
+ if (SVG_HREF_TAGS.has(tag))
120
+ out.push(['href', findAttr(attrs, 'href'), whole], ['xlink:href', findXlinkHref(attrs), whole])
121
+ if (tag === 'link') {
122
+ const rel = findAttr(attrs, 'rel')
123
+ const loads = rel !== undefined && attrStrings(rel).some(value => value.toLowerCase().split(/\s+/).some(r => LOADING_LINK_RELS.has(r)))
124
+ if (loads)
125
+ out.push(['href', findAttr(attrs, 'href'), whole])
126
+ }
127
+ return out
128
+ }
129
+
130
+ /** The first third-party URL each loading attribute of a plain element points at. */
131
+ export function thirdPartyLoads(element: JSXElement, tag: string): ThirdPartyLoad[] {
132
+ const out: ThirdPartyLoad[] = []
133
+ for (const [name, attr, urlsOf] of loadingAttrs(element, tag)) {
134
+ if (attr === undefined)
135
+ continue
136
+ for (const url of attrStrings(attr).flatMap(urlsOf)) {
137
+ const origin = thirdPartyOrigin(url)
138
+ if (origin !== undefined) {
139
+ out.push({ attr: name, url, origin, start: attr.start })
140
+ break
141
+ }
142
+ }
143
+ }
144
+ return out
145
+ }
@@ -1,16 +1,18 @@
1
1
  // French web law compliance checks (RGAA, RGPD, LCEN): static TSX/CSS warnings and route-level checks with explicit silencing.
2
2
 
3
- import type { JSXAttribute, JSXElement, Node, Program } from 'oxc-parser'
3
+ import type { JSXElement, Node, Program } from 'oxc-parser'
4
4
  import type { ModuleAnalysis } from './analyze'
5
+ import type { EcoJsxRule } from './compliance-eco'
5
6
  import type { RgaaJsxRule, RgaaScope } from './compliance-rgaa'
6
7
  import type { CompilerWarning } from './mistakes'
7
8
  import { existsSync, readFileSync } from 'node:fs'
8
- import { basename } from 'node:path'
9
+ import { basename, join } from 'node:path'
9
10
  import { visitorKeys } from 'oxc-parser'
10
11
  import { relPosix, walkFiles } from '../build/files'
11
12
  import { fileToRoutePath } from '../build/routes'
12
13
  import {
13
14
  attrTargetKey,
15
+ checkRgaaComponent,
14
16
  checkRgaaElement,
15
17
  cloneRgaaScope,
16
18
  createRgaaScope,
@@ -21,13 +23,27 @@ import {
21
23
  RGAA_JSX_RULES,
22
24
  staticStringValueOf,
23
25
  } from './compliance-rgaa'
26
+ import { STATEMENT_PLACEHOLDER } from '../a11y/declaration'
27
+ import { checkEcoElement, ECO_JSX_RULES, largePublicFileWarnings } from './compliance-eco'
28
+ import { CSS_IMPORT_RE, CSS_URL_RE, parseOrigin, thirdPartyLoads, thirdPartyOrigin } from './compliance-urls'
24
29
  import { formatDiagnostic, formatLoc, getLineStarts, isComponentTag, jsxTagName, lineIndexAtOffset, unwrapTsExpr } from './shared'
25
30
 
26
31
  export type ComplianceRule =
27
32
  | RgaaJsxRule
33
+ | EcoJsxRule
34
+ | 'rgesn/large-public-file'
35
+ | 'rgesn/declaration'
36
+ | 'rgesn/island-by-value'
28
37
  | 'rgpd/third-party-url'
38
+ | 'rgpd/consent-retention'
39
+ | 'rgpd/privacy-notice'
29
40
  | 'lcen/legal-notice'
41
+ | 'rgaa/document-lang'
30
42
  | 'rgaa/accessibility-statement'
43
+ | FormWarningRule
44
+
45
+ /** The warnings of the form-vs-action check (`cli/check-forms.ts`), silenced like the compliance rules. */
46
+ export type FormWarningRule = 'action/unguarded-public-form' | 'form/invalid-option' | 'form/schema-unsupported' | 'form/unchecked'
31
47
 
32
48
  export interface ComplianceConfig {
33
49
  /** Compliance rules to silence across the app. */
@@ -36,29 +52,52 @@ export interface ComplianceConfig {
36
52
  publicBody?: boolean | undefined
37
53
  /** Custom route path for the legal notice page, or `false` to silence `lcen/legal-notice`. */
38
54
  legalNotice?: string | false | undefined
55
+ /** Custom route path for the privacy notice page, or `false` to silence `rgpd/privacy-notice`. */
56
+ privacyNotice?: string | false | undefined
39
57
  }
40
58
 
41
59
  const COMPLIANCE_RULES = new Set<ComplianceRule>([
42
60
  ...RGAA_JSX_RULES,
61
+ ...ECO_JSX_RULES,
62
+ 'rgesn/large-public-file',
63
+ 'rgesn/declaration',
64
+ 'rgesn/island-by-value',
43
65
  'rgpd/third-party-url',
66
+ 'rgpd/consent-retention',
67
+ 'rgpd/privacy-notice',
44
68
  'lcen/legal-notice',
69
+ 'rgaa/document-lang',
45
70
  'rgaa/accessibility-statement',
71
+ 'action/unguarded-public-form',
72
+ 'form/invalid-option',
73
+ 'form/schema-unsupported',
74
+ 'form/unchecked',
46
75
  ])
47
76
 
48
- const THIRD_PARTY_LINK_RELS = new Set(['stylesheet', 'preload', 'preconnect', 'dns-prefetch', 'modulepreload', 'icon'])
49
- const THIRD_PARTY_SRC_TAGS = new Set(['script', 'iframe', 'img', 'video', 'audio', 'source', 'embed'])
50
- const THIRD_PARTY_SRCSET_TAGS = new Set(['img', 'source'])
77
+ // The CNIL recommends keeping a cookie choice, consent or refusal, 6 months before asking again.
78
+ const CNIL_CHOICE_MAX_AGE = 15_552_000
51
79
  const INLINE_MAP_METHODS = new Set(['map', 'flatMap'])
52
- const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]', '0.0.0.0'])
53
- const DEFAULT_LEGAL_PATHS = new Set(['/mentions-legales', '/legal', '/legal-notice', '/imprint', '/impressum', '/cgu', '/cgv'])
80
+ const DEFAULT_LEGAL_PATHS = new Set(['/mentions-legales', '/legal', '/legal-notice', '/imprint', '/impressum'])
81
+ const DEFAULT_PRIVACY_PATHS = new Set(['/privacy', '/privacy-policy', '/confidentialite', '/politique-de-confidentialite', '/donnees-personnelles', '/datenschutz'])
82
+ // A component named Label (or ui.Label) wraps its control like <label>.
83
+ const LABEL_COMPONENT_RE = /(?:^|\.)Label$/
84
+ // An <input> collecting an email or a phone number, by its type or its name.
85
+ const PERSONAL_DATA_INPUT_RE = /<input\b[^>]*?\b(?:type=["'](?:email|tel)["']|name=["'](?:email|phone|tel)["'])/
54
86
  const ACCESSIBILITY_PATHS = new Set(['/accessibilite', '/accessibility', '/declaration-accessibilite', '/accessibility-statement'])
87
+ const ECO_DECLARATION_PATHS = new Set(['/ecoconception', '/declaration-ecoconception', '/eco-design'])
88
+ // The marker the `prunelle new` legal and privacy notices put in front of every detail the publisher must supply.
89
+ const TEMPLATE_PLACEHOLDER = '[to fill in'
90
+
91
+ interface NoticeDetails { rule: ComplianceRule, page: string, law: string, marker: string }
92
+ const LEGAL_NOTICE_DETAILS: NoticeDetails = { rule: 'lcen/legal-notice', page: 'legal notice', law: 'French law (LCEN art. 1-1) requires the publisher\'s identity, address and phone, the publication director and the host\'s name, address and phone', marker: TEMPLATE_PLACEHOLDER }
93
+ const PRIVACY_NOTICE_DETAILS: NoticeDetails = { rule: 'rgpd/privacy-notice', page: 'privacy notice', law: 'the RGPD (art. 13) requires the controller\'s identity and contact, the purposes and legal basis, the retention periods, the recipients and the rights of the people concerned', marker: TEMPLATE_PLACEHOLDER }
94
+ const ECO_DECLARATION_DETAILS: NoticeDetails = { rule: 'rgesn/declaration', page: 'eco-design declaration', law: 'the RGESN 2024 asks it to name the service, the evaluating entity and a contact, the minimum hardware profile and the planned actions, and to justify each criterion', marker: STATEMENT_PLACEHOLDER }
95
+ const STATEMENT_DETAILS: NoticeDetails = { rule: 'rgaa/accessibility-statement', page: 'accessibility statement', law: 'the RGAA requires it to name the publisher, the site it covers and the pages audited, and to give a contact for accessibility feedback', marker: STATEMENT_PLACEHOLDER }
55
96
  const LOCALE_PREFIX_RE = /^\/(?:[a-z]{2}(?:-[a-z]{2})?|:[a-z_]\w*(?:=[^/]+)?\??|\[\[?[^\]]+\]\]?)(\/.+)$/i
56
97
 
57
98
  const LINE_IGNORE_RE = /(?:^|[\s{;(,])\/\/\s*prunelle-ignore(-file)?[ \t]+([^\r\n]+)/g
58
99
  const BLOCK_IGNORE_RE = /\/\*\s*prunelle-ignore(-file)?\s+([\s\S]*?)\*\//g
59
100
  const CSS_COMMENT_RE = /\/\*[\s\S]*?\*\//g
60
- const CSS_IMPORT_RE = /@import\s+(?:url\(\s*)?(?:'([^']+)'|"([^"]+)"|([^'"\s);]+))/gi
61
- const CSS_URL_RE = /url\(\s*(?:'([^']+)'|"([^"]+)"|([^'"\s)]+))\s*\)/gi
62
101
 
63
102
  interface IgnoreMap {
64
103
  lineStarts: readonly number[]
@@ -110,7 +149,7 @@ export function parsePrunelleIgnores(code: string): IgnoreMap {
110
149
  return { lineStarts, fileRules, lineRules }
111
150
  }
112
151
 
113
- function isIgnoredAt(ignores: IgnoreMap, rule: ComplianceRule, offset: number): boolean {
152
+ export function isIgnoredAt(ignores: IgnoreMap, rule: ComplianceRule, offset: number): boolean {
114
153
  if (ignores.fileRules.has(rule))
115
154
  return true
116
155
  const line = lineIndexAtOffset(ignores.lineStarts, offset) + 1
@@ -120,39 +159,11 @@ function isIgnoredAt(ignores: IgnoreMap, rule: ComplianceRule, offset: number):
120
159
  export function isRuleIgnored(rule: ComplianceRule, compliance?: ComplianceConfig | undefined): boolean {
121
160
  if (rule === 'lcen/legal-notice' && compliance?.legalNotice === false)
122
161
  return true
162
+ if (rule === 'rgpd/privacy-notice' && compliance?.privacyNotice === false)
163
+ return true
123
164
  return compliance?.ignore?.includes(rule) === true
124
165
  }
125
166
 
126
- export function parseOrigin(url: string | undefined): string | undefined {
127
- if (url === undefined || url.trim() === '')
128
- return undefined
129
- try {
130
- return new URL(url.trim()).origin
131
- }
132
- catch {
133
- return undefined
134
- }
135
- }
136
-
137
- /** Returns the external origin when `rawUrl` points to a non-localhost third-party URL, or `undefined` otherwise. */
138
- export function thirdPartyOrigin(rawUrl: string): string | undefined {
139
- const trimmed = rawUrl.trim()
140
- if (!/^(?:https?:)?\/\//i.test(trimmed))
141
- return undefined
142
- try {
143
- const parsed = new URL(trimmed.startsWith('//') ? `https:${trimmed}` : trimmed)
144
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
145
- return undefined
146
- const host = parsed.hostname.toLowerCase()
147
- if (LOCAL_HOSTS.has(host) || host.endsWith('.localhost'))
148
- return undefined
149
- return parsed.origin
150
- }
151
- catch {
152
- return undefined
153
- }
154
- }
155
-
156
167
  /** Whether a compiler warning should be surfaced given `compliance` and `site` config. */
157
168
  export function shouldEmitWarning(warning: CompilerWarning, compliance?: ComplianceConfig | undefined, site?: string | undefined): boolean {
158
169
  if (warning.rule !== undefined && isRuleIgnored(warning.rule, compliance))
@@ -231,61 +242,28 @@ function collectDirectLabelTargets(root: Node | null | undefined): Set<string> {
231
242
  return targets
232
243
  }
233
244
 
234
- function reportThirdPartyAttr(
245
+ function checkThirdPartyElement(
246
+ element: JSXElement,
235
247
  tag: string,
236
- attrName: string,
237
- attr: JSXAttribute | undefined,
238
248
  filename: string,
239
249
  ignores: IgnoreMap,
240
250
  warnings: CompilerWarning[],
241
- isSrcset = false,
242
251
  ): void {
243
- if (attr === undefined)
244
- return
245
- const raw = staticStringValueOf(attr.value)
246
- if (raw === undefined)
247
- return
248
- const urls = isSrcset
249
- ? raw.split(',').map(part => part.trim().split(/\s+/, 1)[0] ?? '').filter(Boolean)
250
- : [raw]
251
- for (const url of urls) {
252
- const origin = thirdPartyOrigin(url)
253
- if (origin === undefined)
252
+ for (const load of thirdPartyLoads(element, tag)) {
253
+ if (isIgnoredAt(ignores, 'rgpd/third-party-url', load.start))
254
254
  continue
255
- if (!isIgnoredAt(ignores, 'rgpd/third-party-url', attr.start)) {
256
- warnings.push({
257
- rule: 'rgpd/third-party-url',
258
- urlOrigin: origin,
259
- start: attr.start,
260
- message: `[rgpd/third-party-url] <${tag} ${attrName}="${url}"> in ${filename} loads a third-party resource without consent: self-host it (e.g. @prunellejs/seo fonts or public/) or wrap it in <ConsentGate category="...">.`,
261
- })
262
- }
263
- return
255
+ warnings.push({
256
+ rule: 'rgpd/third-party-url',
257
+ urlOrigin: load.origin,
258
+ start: load.start,
259
+ message: `[rgpd/third-party-url] <${tag} ${load.attr}="${load.url}"> in ${filename} loads a third-party resource without consent: self-host it (e.g. @prunellejs/seo fonts or public/) or wrap it in <ConsentGate category="...">.`,
260
+ })
264
261
  }
265
262
  }
266
263
 
267
- function checkThirdPartyElement(
268
- element: JSXElement,
269
- tag: string,
270
- filename: string,
271
- ignores: IgnoreMap,
272
- warnings: CompilerWarning[],
273
- ): void {
274
- const attrs = element.openingElement.attributes
275
- if (THIRD_PARTY_SRC_TAGS.has(tag))
276
- reportThirdPartyAttr(tag, 'src', findAttr(attrs, 'src'), filename, ignores, warnings)
277
- if (THIRD_PARTY_SRCSET_TAGS.has(tag))
278
- reportThirdPartyAttr(tag, 'srcset', findAttr(attrs, 'srcset'), filename, ignores, warnings, true)
279
- if (tag === 'object')
280
- reportThirdPartyAttr(tag, 'data', findAttr(attrs, 'data'), filename, ignores, warnings)
281
- if (tag === 'link') {
282
- const relVal = staticStringValueOf(findAttr(attrs, 'rel')?.value ?? null)
283
- if (relVal === undefined)
284
- return
285
- const rels = relVal.toLowerCase().split(/\s+/)
286
- if (rels.some(r => THIRD_PARTY_LINK_RELS.has(r)))
287
- reportThirdPartyAttr(tag, 'href', findAttr(attrs, 'href'), filename, ignores, warnings)
288
- }
264
+ // A gate on the essential category always renders its children, so it holds nothing back until consent.
265
+ function opensConsentGate(element: JSXElement, resolvedTag: string | undefined): boolean {
266
+ return resolvedTag === 'ConsentGate' && staticStringValueOf(findAttr(element.openingElement.attributes, 'category')?.value ?? null) !== 'essential'
289
267
  }
290
268
 
291
269
  function definitelyExits(stmt: Node): boolean {
@@ -307,7 +285,7 @@ export function checkCompliance(
307
285
  resolveTag: (tag: string) => string | undefined,
308
286
  ): void {
309
287
  const ignores = parsePrunelleIgnores(code)
310
- const isIgnored = (rule: RgaaJsxRule, elementStart: number, attrStart?: number): boolean =>
288
+ const isIgnored = (rule: RgaaJsxRule | EcoJsxRule, elementStart: number, attrStart?: number): boolean =>
311
289
  isIgnoredAt(ignores, rule, elementStart) || (attrStart !== undefined && isIgnoredAt(ignores, rule, attrStart))
312
290
 
313
291
  const visitChildren = (node: Node, ancestors: AncestorState, scope: RgaaScope, labelTargets: ReadonlySet<string>): void => {
@@ -382,8 +360,8 @@ export function checkCompliance(
382
360
  if (node.type === 'JSXElement') {
383
361
  const tag = jsxTagName(node.openingElement.name)
384
362
  const attrs = node.openingElement.attributes
385
- if (tag !== '' && !isComponentTag(tag)) {
386
- checkRgaaElement(node, tag, {
363
+ if (tag !== '') {
364
+ const ctx = {
387
365
  filename,
388
366
  inLabel: ancestors.labelDepth > 0,
389
367
  inLoop: ancestors.inLoop,
@@ -392,18 +370,25 @@ export function checkCompliance(
392
370
  scope,
393
371
  isIgnored,
394
372
  warnings,
395
- })
396
- if (ancestors.consentGateDepth === 0)
397
- checkThirdPartyElement(node, tag, filename, ignores, warnings)
373
+ }
374
+ if (isComponentTag(tag)) {
375
+ checkRgaaComponent(node, tag, ctx)
376
+ }
377
+ else {
378
+ checkRgaaElement(node, tag, ctx)
379
+ checkEcoElement(node, tag, ctx)
380
+ if (ancestors.consentGateDepth === 0)
381
+ checkThirdPartyElement(node, tag, filename, ignores, warnings)
382
+ }
398
383
  }
399
384
  visit(attrs, ancestors, scope, labelTargets)
400
- const opensLabel = tag === 'label' || (isComponentTag(tag) && hasNonEmptyAttr(attrs, 'label'))
401
- const opensConsentGate = resolveTag(tag) === 'ConsentGate'
385
+ const opensLabel = tag === 'label' || (isComponentTag(tag) && (LABEL_COMPONENT_RE.test(tag) || hasNonEmptyAttr(attrs, 'label')))
386
+ const opensGate = opensConsentGate(node, resolveTag(tag))
402
387
  const nextInteractive = INTERACTIVE_ANCESTORS.has(tag) ? tag : ancestors.interactiveAncestor
403
- const childAncestors = opensLabel || opensConsentGate || nextInteractive !== ancestors.interactiveAncestor
388
+ const childAncestors = opensLabel || opensGate || nextInteractive !== ancestors.interactiveAncestor
404
389
  ? {
405
390
  labelDepth: ancestors.labelDepth + (opensLabel ? 1 : 0),
406
- consentGateDepth: ancestors.consentGateDepth + (opensConsentGate ? 1 : 0),
391
+ consentGateDepth: ancestors.consentGateDepth + (opensGate ? 1 : 0),
407
392
  interactiveAncestor: nextInteractive,
408
393
  inLoop: ancestors.inLoop,
409
394
  }
@@ -483,18 +468,33 @@ function stripLocalePrefix(normalizedPath: string): string {
483
468
  return m !== null ? m[1]! : normalizedPath
484
469
  }
485
470
 
471
+ function matchesNoticePath(routePath: string, custom: string | false | undefined, defaults: ReadonlySet<string>): boolean {
472
+ const path = normalizePath(routePath)
473
+ const bare = stripLocalePrefix(path)
474
+ if (typeof custom === 'string') {
475
+ const wanted = normalizePath(custom)
476
+ return path === wanted || bare === wanted
477
+ }
478
+ return defaults.has(path) || defaults.has(bare)
479
+ }
480
+
481
+ function isLegalNoticePath(routePath: string, compliance: ComplianceConfig | undefined): boolean {
482
+ return matchesNoticePath(routePath, compliance?.legalNotice, DEFAULT_LEGAL_PATHS)
483
+ }
484
+
485
+ function isStatementPath(routePath: string): boolean {
486
+ return matchesNoticePath(routePath, undefined, ACCESSIBILITY_PATHS)
487
+ }
488
+
486
489
  /** Checks project-level LCEN legal notice and RGAA accessibility statement routes. */
487
490
  export function checkRouteCompliance(pageRoutePaths: readonly string[], compliance?: ComplianceConfig | undefined): string[] {
488
491
  if (pageRoutePaths.length === 0)
489
492
  return []
490
- const normalized = new Set(pageRoutePaths.map(normalizePath))
491
493
  const out: string[] = []
492
494
 
493
495
  if (!isRuleIgnored('lcen/legal-notice', compliance)) {
494
496
  const custom = typeof compliance?.legalNotice === 'string' ? normalizePath(compliance.legalNotice) : undefined
495
- const hasLegal = custom !== undefined
496
- ? normalized.has(custom) || [...normalized].some(p => stripLocalePrefix(p) === custom)
497
- : [...normalized].some(p => DEFAULT_LEGAL_PATHS.has(p) || DEFAULT_LEGAL_PATHS.has(stripLocalePrefix(p)))
497
+ const hasLegal = pageRoutePaths.some(p => isLegalNoticePath(p, compliance))
498
498
  if (!hasLegal) {
499
499
  const expected = custom ?? '/mentions-legales (or /legal)'
500
500
  out.push(formatDiagnostic('prunelle.config.ts:1:1', `[lcen/legal-notice] App has no legal notice route: add ${expected}, set compliance.legalNotice, or silence with compliance: { legalNotice: false }.`, 'warning'))
@@ -502,8 +502,7 @@ export function checkRouteCompliance(pageRoutePaths: readonly string[], complian
502
502
  }
503
503
 
504
504
  if (compliance?.publicBody === true && !isRuleIgnored('rgaa/accessibility-statement', compliance)) {
505
- const hasA11y = [...normalized].some(p => ACCESSIBILITY_PATHS.has(p) || ACCESSIBILITY_PATHS.has(stripLocalePrefix(p)))
506
- if (!hasA11y) {
505
+ if (!pageRoutePaths.some(isStatementPath)) {
507
506
  out.push(formatDiagnostic('prunelle.config.ts:1:1', '[rgaa/accessibility-statement] Public-body site (compliance.publicBody: true) has no accessibility statement route: add /accessibilite (or /accessibility), or draft one with `prunelle a11y --draft`.', 'warning'))
508
507
  }
509
508
  }
@@ -518,23 +517,38 @@ export interface ProjectComplianceInput {
518
517
  routeFiles: readonly string[]
519
518
  analyses: ReadonlyMap<string, ModuleAnalysis>
520
519
  compliance?: ComplianceConfig | undefined
520
+ /** `consent.maxAge` from the config, in seconds. */
521
+ consentMaxAge?: number | undefined
521
522
  site?: string | undefined
523
+ /** `lang` from the config. */
524
+ lang?: string | undefined
525
+ /** A plugin sets `<html lang>` per request, so a missing `lang` is not a mistake. */
526
+ langFromPlugin?: boolean | undefined
527
+ }
528
+
529
+ /** True when a plugin sets `<html lang>` from the request's locale (`@prunellejs/i18n`). */
530
+ export function pluginSetsLang(plugins: readonly { name: string }[]): boolean {
531
+ return plugins.some(p => p.name === '@prunellejs/i18n')
522
532
  }
523
533
 
524
- /** Collects project-level CSS third-party URL warnings and LCEN/RGAA route warnings for `prunelle check` and production `prunelle build`. */
534
+ /** Collects project-level CSS third-party URL warnings and the LCEN, RGPD and RGAA notice warnings for `prunelle check` and production `prunelle build`. */
525
535
  export function collectProjectComplianceWarnings(input: ProjectComplianceInput): string[] {
526
- const { root, srcDir, routesDir, routeFiles, analyses, compliance, site } = input
536
+ const { root, srcDir, routesDir, routeFiles, analyses, compliance, consentMaxAge, site, lang, langFromPlugin } = input
527
537
  const warnings: string[] = []
528
-
529
- if (existsSync(srcDir)) {
530
- const cssFiles = walkFiles(srcDir, {
531
- skipDir: name => name === 'node_modules' || name === 'dist' || name.startsWith('.'),
532
- keep: entry => entry.name.endsWith('.css'),
533
- }).sort()
534
- for (const cssFile of cssFiles) {
535
- const code = readFileSync(cssFile, 'utf8')
536
- warnings.push(...checkCssCompliance(relPosix(root, cssFile), code, compliance, site))
537
- }
538
+ if (consentMaxAge !== undefined && consentMaxAge > CNIL_CHOICE_MAX_AGE && !isRuleIgnored('rgpd/consent-retention', compliance))
539
+ warnings.push(formatDiagnostic('prunelle.config.ts:1:1', `[rgpd/consent-retention] consent.maxAge keeps the visitor's choice ${Math.round(consentMaxAge / 86_400)} days, past the 6 months the CNIL recommends before asking again: lower it to 15552000 (180 days) or remove it.`, 'warning'))
540
+
541
+ const srcFiles = existsSync(srcDir)
542
+ ? walkFiles(srcDir, {
543
+ skipDir: name => name === 'node_modules' || name === 'dist' || name.startsWith('.'),
544
+ keep: entry => entry.name.endsWith('.css') || entry.name.endsWith('.tsx'),
545
+ }).sort()
546
+ : []
547
+ // public/ is served as is, so its stylesheets load whatever they point at too.
548
+ const publicCss = walkFiles(join(root, 'public'), { keep: entry => entry.name.endsWith('.css') }).sort()
549
+ for (const cssFile of [...srcFiles.filter(file => file.endsWith('.css')), ...publicCss]) {
550
+ const code = readFileSync(cssFile, 'utf8')
551
+ warnings.push(...checkCssCompliance(relPosix(root, cssFile), code, compliance, site))
538
552
  }
539
553
 
540
554
  const pagePaths: string[] = []
@@ -542,9 +556,47 @@ export function collectProjectComplianceWarnings(input: ProjectComplianceInput):
542
556
  if (basename(file).startsWith('_'))
543
557
  continue
544
558
  const analysis = analyses.get(file)
545
- if (analysis !== undefined && analysis.exportedNames.includes('default'))
546
- pagePaths.push(fileToRoutePath(routesDir, file))
559
+ if (analysis === undefined || !analysis.exportedNames.includes('default'))
560
+ continue
561
+ const routePath = fileToRoutePath(routesDir, file)
562
+ pagePaths.push(routePath)
563
+ if (isLegalNoticePath(routePath, compliance) && !isRuleIgnored('lcen/legal-notice', compliance))
564
+ warnings.push(...placeholderWarnings(relPosix(root, file), readFileSync(file, 'utf8'), LEGAL_NOTICE_DETAILS))
565
+ if (matchesNoticePath(routePath, compliance?.privacyNotice, DEFAULT_PRIVACY_PATHS) && !isRuleIgnored('rgpd/privacy-notice', compliance))
566
+ warnings.push(...placeholderWarnings(relPosix(root, file), readFileSync(file, 'utf8'), PRIVACY_NOTICE_DETAILS))
567
+ // Any site that publishes a statement, public body or not, publishes what it says.
568
+ if (isStatementPath(routePath) && !isRuleIgnored('rgaa/accessibility-statement', compliance))
569
+ warnings.push(...placeholderWarnings(relPosix(root, file), readFileSync(file, 'utf8'), STATEMENT_DETAILS))
570
+ if (matchesNoticePath(routePath, undefined, ECO_DECLARATION_PATHS) && !isRuleIgnored('rgesn/declaration', compliance))
571
+ warnings.push(...placeholderWarnings(relPosix(root, file), readFileSync(file, 'utf8'), ECO_DECLARATION_DETAILS))
547
572
  }
548
573
  warnings.push(...checkRouteCompliance(pagePaths, compliance))
574
+ if (pagePaths.length > 0 && lang === undefined && langFromPlugin !== true && !isRuleIgnored('rgaa/document-lang', compliance))
575
+ warnings.push(formatDiagnostic('prunelle.config.ts:1:1', '[rgaa/document-lang] No lang in prunelle.config.ts, so every page says <html lang="en"> and @prunellejs/ui speaks English: set lang: \'fr\' (or the language your pages are written in).', 'warning'))
576
+ warnings.push(...largePublicFileWarnings(root, isRuleIgnored('rgesn/large-public-file', compliance)))
577
+ if (!isRuleIgnored('rgpd/privacy-notice', compliance) && !pagePaths.some(p => matchesNoticePath(p, compliance?.privacyNotice, DEFAULT_PRIVACY_PATHS)))
578
+ warnings.push(...privacyNoticeWarnings(root, srcFiles.filter(file => file.endsWith('.tsx')), compliance?.privacyNotice))
549
579
  return warnings
550
580
  }
581
+
582
+ // One warning, at the first form field collecting an email or a phone number: a single privacy page covers every form.
583
+ function privacyNoticeWarnings(root: string, tsxFiles: readonly string[], custom: string | false | undefined): string[] {
584
+ for (const file of tsxFiles) {
585
+ const code = readFileSync(file, 'utf8')
586
+ const match = PERSONAL_DATA_INPUT_RE.exec(code)
587
+ if (match === null)
588
+ continue
589
+ const relFile = relPosix(root, file)
590
+ const expected = typeof custom === 'string' ? normalizePath(custom) : '/privacy (or /confidentialite)'
591
+ return [formatDiagnostic(formatLoc(relFile, code, match.index), `[rgpd/privacy-notice] ${relFile} collects an email or a phone number but the app has no privacy notice route: RGPD art. 13 requires telling people, as their data is collected, who processes it, why, for how long and what their rights are; add ${expected} and link it beside the form, set compliance.privacyNotice, or silence with compliance: { privacyNotice: false }.`, 'warning')]
592
+ }
593
+ return []
594
+ }
595
+
596
+ // One warning for the first unfilled detail: the publisher fills them all in one pass.
597
+ function placeholderWarnings(relFile: string, code: string, notice: NoticeDetails): string[] {
598
+ const offset = code.indexOf(notice.marker)
599
+ if (offset === -1)
600
+ return []
601
+ return [formatDiagnostic(formatLoc(relFile, code, offset), `[${notice.rule}] The ${notice.page} still holds "${notice.marker} ...]" placeholders: ${notice.law}; replace every placeholder in ${relFile}.`, 'warning')]
602
+ }