prunelle 0.8.0 → 0.9.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/llms.txt +61 -44
- package/package.json +7 -2
- package/src/a11y/declaration.ts +6 -10
- package/src/a11y/index.ts +69 -125
- package/src/animate.ts +127 -0
- package/src/build/asides.ts +51 -0
- package/src/build/bundle.ts +88 -134
- package/src/build/client-entries.ts +6 -6
- package/src/build/client-outputs.ts +75 -0
- package/src/build/client-plugin.ts +9 -4
- package/src/build/ecoindex.ts +4 -2
- package/src/build/files.ts +18 -0
- package/src/build/graph.ts +14 -6
- package/src/build/index.ts +20 -10
- package/src/build/islands.ts +4 -1
- package/src/build/key-types.ts +31 -0
- package/src/build/manifest.ts +19 -1
- package/src/build/plugin-host.ts +2 -0
- package/src/build/prerender.ts +2 -2
- package/src/build/reach.ts +14 -1
- package/src/build/report.ts +1 -1
- package/src/build/route-types.ts +16 -0
- package/src/build/routes.ts +24 -15
- package/src/build/seed-ids.ts +65 -0
- package/src/build/seed-writes.ts +111 -0
- package/src/build/static-headers.ts +2 -2
- package/src/build/static.ts +1 -1
- package/src/cli/check-cache.ts +51 -0
- package/src/cli/check-consent.ts +95 -0
- package/src/cli/check-forms.ts +2 -2
- package/src/cli/check-links-patterns.ts +101 -0
- package/src/cli/check-links.ts +16 -100
- package/src/cli/check-regions.ts +185 -0
- package/src/cli/check-security.ts +50 -6
- package/src/cli/check.ts +40 -18
- package/src/cli/commands.ts +134 -14
- package/src/cli/docs.ts +21 -2
- package/src/cli/index.ts +1 -1
- package/src/cli/inspect.ts +2 -0
- package/src/cli/mcp-tools.ts +2 -2
- package/src/cli/new.ts +9 -5
- package/src/cli/upgrade-names.ts +14 -2
- package/src/cli/upgrade.ts +3 -0
- package/src/compiler/analyze.ts +2 -2
- package/src/compiler/cacheability.ts +24 -2
- package/src/compiler/compliance-contrast.ts +284 -0
- package/src/compiler/compliance-empty.ts +24 -0
- package/src/compiler/compliance-rgaa-content.ts +95 -0
- package/src/compiler/compliance-rgaa-criteria.ts +45 -0
- package/src/compiler/compliance-rgaa-pages.ts +140 -0
- package/src/compiler/compliance-rgaa.ts +19 -0
- package/src/compiler/compliance-third-party.ts +59 -0
- package/src/compiler/compliance-urls.ts +52 -0
- package/src/compiler/compliance.ts +70 -42
- package/src/compiler/cookie-inventory.ts +119 -0
- package/src/compiler/foreign-imports.ts +5 -3
- package/src/compiler/mistakes.ts +18 -9
- package/src/compiler/props-pattern.ts +211 -0
- package/src/compiler/props.ts +177 -346
- package/src/compiler/ssr-emit.ts +510 -0
- package/src/compiler/ssr-helpers.ts +170 -121
- package/src/compiler/ssr.ts +25 -440
- package/src/context.ts +14 -1
- package/src/dev/child.ts +1 -1
- package/src/dev/hot-islands.ts +71 -0
- package/src/dev/index.ts +31 -18
- package/src/dev/protocol.ts +1 -1
- package/src/dev/queue.ts +3 -2
- package/src/dev/reload.ts +1 -1
- package/src/dev/supervisor.ts +3 -1
- package/src/dev/watchers.ts +6 -2
- package/src/dom/action.ts +97 -14
- package/src/dom/extras.ts +2 -1
- package/src/dom/field-marks.ts +24 -0
- package/src/dom/hot.ts +9 -0
- package/src/dom/index.ts +25 -5
- package/src/dom/island-hot.ts +29 -0
- package/src/dom/island.ts +13 -2
- package/src/dom/prefetch.ts +132 -0
- package/src/dom/regions.ts +498 -0
- package/src/dom/swap.ts +245 -0
- package/src/dom/trusted.ts +22 -0
- package/src/dom/upload.ts +44 -0
- package/src/eco/declaration.ts +39 -40
- package/src/eco/index.ts +5 -5
- package/src/href.ts +31 -0
- package/src/index.ts +9 -3
- package/src/plugins/config.ts +1 -1
- package/src/plugins/context.ts +7 -1
- package/src/plugins/daily.ts +27 -0
- package/src/plugins/index.ts +3 -3
- package/src/plugins/order.ts +1 -1
- package/src/plugins/public.ts +8 -5
- package/src/plugins/services.ts +88 -14
- package/src/plugins/types.ts +120 -9
- package/src/reactivity/hmr.ts +90 -0
- package/src/reactivity/index.ts +38 -18
- package/src/reactivity/resource.ts +115 -0
- package/src/reactivity/seed.ts +39 -0
- package/src/reactivity/server-seed.ts +194 -0
- package/src/reactivity/store.ts +55 -1
- package/src/rgpd/draft.ts +171 -0
- package/src/rgpd/forms.ts +85 -0
- package/src/rgpd/index.ts +57 -0
- package/src/server/action-flash.ts +1 -0
- package/src/server/action-registry.ts +6 -8
- package/src/server/action.ts +51 -19
- package/src/server/app-secret.ts +14 -8
- package/src/server/cache-invalidation.ts +96 -0
- package/src/server/compress.ts +3 -1
- package/src/server/consent.ts +16 -2
- package/src/server/cookie-inventory.ts +78 -0
- package/src/server/cookies.ts +50 -0
- package/src/server/csp-report.ts +86 -0
- package/src/server/discard.ts +13 -0
- package/src/server/document.ts +2 -2
- package/src/server/env.ts +1 -1
- package/src/server/errors.ts +9 -2
- package/src/server/field-errors.ts +91 -0
- package/src/server/form-schema.ts +16 -11
- package/src/server/health.ts +33 -12
- package/src/server/http.ts +25 -10
- package/src/server/index.ts +101 -298
- package/src/server/loader.ts +1 -0
- package/src/server/page.ts +3 -9
- package/src/server/plugin-host.ts +26 -8
- package/src/server/public.ts +14 -3
- package/src/server/rate-limit.ts +39 -10
- package/src/server/region.ts +3 -0
- package/src/server/request-handler.ts +370 -0
- package/src/server/request-log.ts +94 -0
- package/src/server/route-cache.ts +41 -6
- package/src/server/route-input.ts +54 -0
- package/src/server/route-table.ts +35 -19
- package/src/server/routing.ts +12 -11
- package/src/server/sanitize-html.ts +1 -1
- package/src/server/security.ts +38 -8
- package/src/server/serve-handlers.ts +9 -5
- package/src/server/shared-store.ts +314 -0
- package/src/server/start.ts +12 -5
- package/src/server/static-dir.ts +14 -10
- package/src/server/stream.ts +2 -1
- package/src/server/surface.ts +39 -0
- package/src/server/webhook.ts +48 -0
- package/src/server/workers.ts +168 -0
- package/src/ssr/consent-banner.ts +20 -16
- package/src/ssr/consent-texts.ts +40 -0
- package/src/ssr/context.ts +26 -3
- package/src/ssr/cookie-table.ts +75 -0
- package/src/ssr/index.ts +23 -13
- package/src/ssr/navigation.ts +161 -14
- package/src/test/browser.ts +50 -22
- package/src/test/build-reuse.ts +70 -0
- package/src/test/index.ts +45 -6
- package/src/test/mount.ts +53 -0
- package/src/test/outside.ts +94 -0
- package/templates/_shared/AGENTS.md +1 -1
- package/templates/_shared/Dockerfile +22 -0
- package/templates/_shared/dockerignore +9 -0
- package/templates/_shared/gitignore +2 -0
- package/templates/app/.env.example +3 -1
- package/templates/app/compose.yaml +32 -0
- package/templates/app/db/migrations/001_notes.sql +7 -0
- package/templates/app/db/schema.ts +11 -0
- package/templates/app/package.json +1 -0
- package/templates/app/prunelle.config.ts +6 -0
- package/templates/app/src/actions/notes.ts +26 -0
- package/templates/app/src/auth.ts +4 -2
- package/templates/app/src/db.ts +5 -0
- package/templates/app/src/routes/dashboard/index.tsx +26 -1
- package/templates/app/src/routes/privacy.tsx +6 -2
- package/templates/app/tests/app.test.ts +14 -3
- package/templates/plugin/AGENTS.md +11 -0
- package/templates/plugin/CLAUDE.md +1 -0
- package/templates/plugin/README.md +27 -0
- package/templates/plugin/gitignore +2 -0
- package/templates/plugin/llms.txt +19 -0
- package/templates/plugin/package.json +33 -0
- package/templates/plugin/src/index.ts +40 -0
- package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
- package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
- package/templates/plugin/tests/plugin.test.ts +42 -0
- package/templates/plugin/tsconfig.json +19 -0
- package/ts-plugin.cjs +3674 -2196
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// The app's own forms that collect an email or a phone number, one processing per file for `prunelle rgpd`.
|
|
2
|
+
|
|
3
|
+
import type { JSXElement, Node } from 'oxc-parser'
|
|
4
|
+
import type { ProcessingDeclaration } from '../plugins/types'
|
|
5
|
+
import { readFileSync } from 'node:fs'
|
|
6
|
+
import { basename, join } from 'node:path'
|
|
7
|
+
import { parseSync } from 'oxc-parser'
|
|
8
|
+
import { isNotSourceDir, relPosix, walkFiles, walkRoutes } from '../build/files'
|
|
9
|
+
import { fileToRoutePath } from '../build/routes'
|
|
10
|
+
import { walk } from '../compiler/ast'
|
|
11
|
+
import { isPersonalDataInput } from '../compiler/compliance'
|
|
12
|
+
import { findAttr, staticStringValueOf } from '../compiler/compliance-rgaa'
|
|
13
|
+
import { jsxTagName } from '../compiler/shared'
|
|
14
|
+
|
|
15
|
+
const FIELD_TAGS = new Set(['input', 'textarea', 'select'])
|
|
16
|
+
|
|
17
|
+
function attr(el: JSXElement, name: string): string | undefined {
|
|
18
|
+
const found = findAttr(el.openingElement.attributes, name)
|
|
19
|
+
return found === undefined ? undefined : staticStringValueOf(found.value)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// `adresse e-mail (champ email)` for a field collecting an email, `champ message` for any other named one.
|
|
23
|
+
function describeField(el: JSXElement): string | undefined {
|
|
24
|
+
const name = attr(el, 'name')
|
|
25
|
+
if (!isPersonalDataInput(el))
|
|
26
|
+
return name === undefined ? undefined : `champ ${name}`
|
|
27
|
+
const kind = attr(el, 'type')?.toLowerCase() === 'email' || name?.toLowerCase() === 'email' ? 'adresse e-mail' : 'numéro de téléphone'
|
|
28
|
+
return name === undefined ? kind : `${kind} (champ ${name})`
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function fieldsOf(form: JSXElement): JSXElement[] {
|
|
32
|
+
const fields: JSXElement[] = []
|
|
33
|
+
walk(form, (node): undefined => {
|
|
34
|
+
if (node.type === 'JSXElement' && FIELD_TAGS.has(jsxTagName(node.openingElement.name)))
|
|
35
|
+
fields.push(node)
|
|
36
|
+
return undefined
|
|
37
|
+
})
|
|
38
|
+
return fields
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Every field of a form that holds a personal-data input, and such an input outside any form; a form posting under a plugin's path is that plugin's processing.
|
|
42
|
+
function collectedData(program: Node, claimed: readonly string[]): string[] {
|
|
43
|
+
const data = new Set<string>()
|
|
44
|
+
walk(program, (node): boolean | undefined => {
|
|
45
|
+
if (node.type !== 'JSXElement')
|
|
46
|
+
return undefined
|
|
47
|
+
if (jsxTagName(node.openingElement.name) === 'form') {
|
|
48
|
+
const action = attr(node, 'action')
|
|
49
|
+
const fields = fieldsOf(node)
|
|
50
|
+
if (!claimed.some(path => action?.startsWith(path) === true) && fields.some(isPersonalDataInput)) {
|
|
51
|
+
for (const described of fields.map(describeField)) {
|
|
52
|
+
if (described !== undefined)
|
|
53
|
+
data.add(described)
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return false
|
|
57
|
+
}
|
|
58
|
+
if (isPersonalDataInput(node))
|
|
59
|
+
data.add(describeField(node)!)
|
|
60
|
+
return undefined
|
|
61
|
+
})
|
|
62
|
+
return [...data]
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function formProcessing(root: string, routesDir: string, claimed: readonly string[]): ProcessingDeclaration[] {
|
|
66
|
+
const keep = { skipDir: isNotSourceDir, keep: (entry: { name: string }) => entry.name.endsWith('.tsx') }
|
|
67
|
+
const files = [...new Set([...walkFiles(join(root, 'src'), keep), ...walkFiles(routesDir, keep)])].sort()
|
|
68
|
+
const pages = new Set(walkRoutes(routesDir).filter(file => !basename(file).startsWith('_')))
|
|
69
|
+
const processing: ProcessingDeclaration[] = []
|
|
70
|
+
for (const file of files) {
|
|
71
|
+
const code = readFileSync(file, 'utf8')
|
|
72
|
+
if (!code.includes('<input'))
|
|
73
|
+
continue
|
|
74
|
+
const data = collectedData(parseSync(file, code, { lang: 'tsx' }).program, claimed)
|
|
75
|
+
if (data.length === 0)
|
|
76
|
+
continue
|
|
77
|
+
processing.push({
|
|
78
|
+
name: pages.has(file) ? `Formulaire de la page ${fileToRoutePath(routesDir, file)}` : `Formulaire de ${relPosix(root, file)}`,
|
|
79
|
+
purpose: '[à compléter : finalité du formulaire]',
|
|
80
|
+
people: 'les personnes qui remplissent ce formulaire',
|
|
81
|
+
data,
|
|
82
|
+
})
|
|
83
|
+
}
|
|
84
|
+
return processing
|
|
85
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// `prunelle rgpd`: the personal data the plugins declare and the app's forms collect, and the privacy notice and record of processing drafted from it.
|
|
2
|
+
|
|
3
|
+
import type { ProcessingDeclaration } from '../plugins/types'
|
|
4
|
+
import type { PrivacyNoticeDraft } from './draft'
|
|
5
|
+
import { resolve } from 'node:path'
|
|
6
|
+
import { loadConfig } from '../plugins/load'
|
|
7
|
+
import { draftPrivacyNotice } from './draft'
|
|
8
|
+
import { formProcessing } from './forms'
|
|
9
|
+
|
|
10
|
+
export { draftPrivacyNotice, REGISTER_PATH } from './draft'
|
|
11
|
+
export type { DraftedFile, PrivacyNoticeDraft, PrivacyNoticeOptions } from './draft'
|
|
12
|
+
|
|
13
|
+
export interface RgpdRunOptions {
|
|
14
|
+
root: string
|
|
15
|
+
/** Draft the notice, at this path (`''` for `<routesDir>/confidentialite.tsx`), and the record of processing. */
|
|
16
|
+
draft?: string | undefined
|
|
17
|
+
force?: boolean | undefined
|
|
18
|
+
organization?: string | undefined
|
|
19
|
+
contactEmail?: string | undefined
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface RgpdRunResult {
|
|
23
|
+
processing: ProcessingDeclaration[]
|
|
24
|
+
drafted?: PrivacyNoticeDraft | undefined
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function runRgpd(options: RgpdRunOptions): Promise<RgpdRunResult> {
|
|
28
|
+
const root = resolve(options.root)
|
|
29
|
+
const config = await loadConfig(root)
|
|
30
|
+
const routesDir = resolve(root, config.routesDir ?? 'src/routes')
|
|
31
|
+
const declared = (config.plugins ?? []).flatMap(plugin => typeof plugin.processing === 'function' ? plugin.processing({ site: config.site }) : plugin.processing ?? [])
|
|
32
|
+
const processing = [...declared, ...formProcessing(root, routesDir, declared.flatMap(p => p.formActions ?? []))]
|
|
33
|
+
if (options.draft === undefined)
|
|
34
|
+
return { processing }
|
|
35
|
+
const drafted = draftPrivacyNotice({
|
|
36
|
+
root,
|
|
37
|
+
routesDir,
|
|
38
|
+
outPath: options.draft === '' ? undefined : options.draft,
|
|
39
|
+
processing,
|
|
40
|
+
organization: options.organization,
|
|
41
|
+
contactEmail: options.contactEmail,
|
|
42
|
+
force: options.force,
|
|
43
|
+
})
|
|
44
|
+
return { processing, drafted }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function formatRgpdResult(result: RgpdRunResult): string {
|
|
48
|
+
const lines = ['prunelle rgpd: the personal data the plugins declare and the app\'s forms collect']
|
|
49
|
+
for (const p of result.processing)
|
|
50
|
+
lines.push(` ${p.name}: ${p.data.join(', ')}`)
|
|
51
|
+
if (result.processing.length === 0)
|
|
52
|
+
lines.push(' none found')
|
|
53
|
+
lines.push(result.drafted === undefined
|
|
54
|
+
? 'prunelle rgpd --draft writes the privacy notice and the record of processing from it.'
|
|
55
|
+
: `prunelle rgpd: drafted the privacy notice at ${result.drafted.notice.relativePath} and the record of processing at ${result.drafted.register.relativePath}: fill in each [à compléter ...] before publishing the notice, and keep the record out of the site.`)
|
|
56
|
+
return lines.join('\n')
|
|
57
|
+
}
|
|
@@ -5,6 +5,7 @@ import { signPayload, verifyPayload } from './app-secret'
|
|
|
5
5
|
import { extractFormSchema, isRecord } from './form-schema'
|
|
6
6
|
|
|
7
7
|
export const ACTION_ERROR_COOKIE = '__pru_action_err'
|
|
8
|
+
export const ACTION_ERROR_MAX_AGE = 60
|
|
8
9
|
|
|
9
10
|
const FLASH_PURPOSE = 'action-flash'
|
|
10
11
|
const MAX_FLASH_COOKIE_BYTES = 3500
|
|
@@ -16,6 +16,8 @@ export interface ActionRegistry {
|
|
|
16
16
|
/** Gives `act` its name and live URL and records the middlewares a request to it runs behind. */
|
|
17
17
|
register: (act: ServerAction<unknown, unknown>, name: string, url: string, dirMiddlewares: Middleware[], pluginMiddlewares: readonly Middleware[]) => void
|
|
18
18
|
byUrl: (url: string) => RegisteredAction | undefined
|
|
19
|
+
/** Whether a registered action counts its calls with `rateLimit`. */
|
|
20
|
+
rateLimited: () => boolean
|
|
19
21
|
/** Runs an action with schema validation behind its folder's `_middleware.ts` chain, as an island call would. */
|
|
20
22
|
invoke: <I, O>(act: ServerAction<I, O>, input: I, ctx: RequestContext) => Promise<ActionResult<O>>
|
|
21
23
|
/** Runs `fn` as part of the request `ctx`, so the actions it calls run in that request. */
|
|
@@ -41,21 +43,16 @@ export function createActionRegistry(): ActionRegistry {
|
|
|
41
43
|
// A directory `_middleware.ts` short-circuited the request (e.g. 401/403 auth guard).
|
|
42
44
|
const ct = (res.headers.get('content-type') ?? '').toLowerCase()
|
|
43
45
|
if (ct.includes('application/json')) {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
+
const body = await res.clone().json().catch(() => null) as Record<string, unknown> | null
|
|
47
|
+
if (body !== null) {
|
|
46
48
|
return {
|
|
47
49
|
ok: false,
|
|
48
50
|
status: res.status,
|
|
49
51
|
error: typeof body.error === 'string' ? body.error : res.statusText || 'Forbidden',
|
|
50
52
|
}
|
|
51
53
|
}
|
|
52
|
-
catch {}
|
|
53
54
|
}
|
|
54
|
-
|
|
55
|
-
try {
|
|
56
|
-
text = await res.clone().text()
|
|
57
|
-
}
|
|
58
|
-
catch {}
|
|
55
|
+
const text = await res.clone().text().catch(() => '')
|
|
59
56
|
return {
|
|
60
57
|
ok: false,
|
|
61
58
|
status: res.status,
|
|
@@ -71,6 +68,7 @@ export function createActionRegistry(): ActionRegistry {
|
|
|
71
68
|
handlers.set(url, { act, middlewares: [...pluginMiddlewares, ...dirMiddlewares] })
|
|
72
69
|
},
|
|
73
70
|
byUrl: url => handlers.get(url),
|
|
71
|
+
rateLimited: () => [...handlers.values()].some(({ act }) => act.rateLimit !== undefined),
|
|
74
72
|
invoke,
|
|
75
73
|
run: (ctx, fn) => runInRequest({ ctx, actions: registry }, fn),
|
|
76
74
|
}
|
package/src/server/action.ts
CHANGED
|
@@ -3,12 +3,13 @@
|
|
|
3
3
|
import type { ActionProtectOptions } from './action-protect'
|
|
4
4
|
import type { Cookies } from './cookies'
|
|
5
5
|
import type { RequestContext } from './http'
|
|
6
|
-
import type { PrunelleLocals } from './
|
|
6
|
+
import type { PrunelleLocals } from './public'
|
|
7
7
|
import type { RateLimit, RateLimiter } from './rate-limit'
|
|
8
8
|
import type { TrustProxy } from './security'
|
|
9
9
|
import type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1, ValidationFailure, ValidationResult } from './standard-schema'
|
|
10
|
-
import { ACTION_ERROR_COOKIE, buildActionErrorFlash, flashAllowlist } from './action-flash'
|
|
10
|
+
import { ACTION_ERROR_COOKIE, ACTION_ERROR_MAX_AGE, buildActionErrorFlash, flashAllowlist } from './action-flash'
|
|
11
11
|
import { assertActionProtect, needsProtectBody, verifyActionProtection } from './action-protect'
|
|
12
|
+
import { extractFormSchema } from './form-schema'
|
|
12
13
|
import { isExternalRedirect, wantsJson } from './http'
|
|
13
14
|
import { assertRateLimit, hitFor, tooManyRequests } from './rate-limit'
|
|
14
15
|
import { currentRequest } from './request-scope'
|
|
@@ -18,7 +19,7 @@ import { validateSchema } from './standard-schema'
|
|
|
18
19
|
export { ACTION_ERROR_COOKIE, hydrateActionErrorFlash } from './action-flash'
|
|
19
20
|
export type { ActionProtectOptions } from './action-protect'
|
|
20
21
|
|
|
21
|
-
declare module './
|
|
22
|
+
declare module './public' {
|
|
22
23
|
interface PrunelleLocals {
|
|
23
24
|
actionError?: ActionErrorFlash | undefined
|
|
24
25
|
}
|
|
@@ -293,6 +294,33 @@ function setField(target: Record<string, unknown>, key: string, value: unknown):
|
|
|
293
294
|
Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true })
|
|
294
295
|
}
|
|
295
296
|
|
|
297
|
+
// Coerces known array fields declared in the schema's JSON Schema before validation so single-checked or unchecked checkbox groups work regardless of custom/localized error messages.
|
|
298
|
+
function coerceFormArraysFromSchema(schema: StandardSchemaV1, body: Record<string, unknown>): { body: Record<string, unknown>, hasJsonSchema: boolean } {
|
|
299
|
+
const extracted = extractFormSchema(schema)
|
|
300
|
+
if (!extracted.ok)
|
|
301
|
+
return { body, hasJsonSchema: false }
|
|
302
|
+
let out: Record<string, unknown> | undefined
|
|
303
|
+
for (const [pathKey, constraint] of extracted.fields) {
|
|
304
|
+
if (constraint.isArray !== true)
|
|
305
|
+
continue
|
|
306
|
+
const path = pathKey.split('.')
|
|
307
|
+
if (path.length > MAX_NESTED_DEPTH || path.some(p => p.length === 0 || (path.length > 1 && UNSAFE_NESTED_KEYS.has(p))))
|
|
308
|
+
continue
|
|
309
|
+
const current = getAtPath(out ?? body, path)
|
|
310
|
+
if (current.has) {
|
|
311
|
+
if (Array.isArray(current.value))
|
|
312
|
+
continue
|
|
313
|
+
out ??= { ...body }
|
|
314
|
+
setAtPath(out, path, [current.value])
|
|
315
|
+
}
|
|
316
|
+
else if (constraint.required === true) {
|
|
317
|
+
out ??= { ...body }
|
|
318
|
+
setAtPath(out, path, [])
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
return { body: out ?? body, hasJsonSchema: true }
|
|
322
|
+
}
|
|
323
|
+
|
|
296
324
|
const ARRAY_WORD_RE = /\barray\b/i
|
|
297
325
|
const MISSING_WORD_RE = /\b(?:required|missing|undefined)\b/i
|
|
298
326
|
const NON_ARRAY_TYPE_RE = /\b(?:string|number|boolean|object|file|date|bigint|symbol)\b/i
|
|
@@ -391,20 +419,22 @@ export async function invokeActionCore<I, O>(
|
|
|
391
419
|
const ok = result.status >= 200 && result.status < 300
|
|
392
420
|
const ct = (result.headers.get('content-type') ?? '').toLowerCase()
|
|
393
421
|
if (ct.includes('application/json')) {
|
|
394
|
-
|
|
395
|
-
|
|
422
|
+
// A body that is not JSON after all falls through to the status-only result below.
|
|
423
|
+
const body = await result.clone().json().catch(() => undefined) as Record<string, unknown> | null | undefined
|
|
424
|
+
if (body !== undefined) {
|
|
396
425
|
if (typeof body === 'object' && body !== null && 'ok' in body)
|
|
397
426
|
return body as unknown as ActionResult<O>
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
}
|
|
427
|
+
if (ok)
|
|
428
|
+
return { ok: true, data: body as O }
|
|
429
|
+
if (body !== null) {
|
|
430
|
+
return {
|
|
431
|
+
ok: false,
|
|
432
|
+
status: result.status,
|
|
433
|
+
error: typeof body.error === 'string' ? body.error : result.statusText,
|
|
434
|
+
...(body.fieldErrors !== undefined ? { fieldErrors: body.fieldErrors as Record<string, string> } : {}),
|
|
435
|
+
}
|
|
436
|
+
}
|
|
406
437
|
}
|
|
407
|
-
catch {}
|
|
408
438
|
}
|
|
409
439
|
return ok
|
|
410
440
|
? { ok: true, data: undefined as O }
|
|
@@ -429,14 +459,14 @@ export async function executeAction(
|
|
|
429
459
|
ctx.cookies.set(ACTION_ERROR_COOKIE, buildActionErrorFlash(act.url, error, fieldErrors, flattenFlashBody(rawBody), flashAllowlist(act)), {
|
|
430
460
|
httpOnly: true,
|
|
431
461
|
sameSite: 'lax',
|
|
432
|
-
maxAge:
|
|
462
|
+
maxAge: ACTION_ERROR_MAX_AGE,
|
|
433
463
|
category: 'essential',
|
|
434
464
|
})
|
|
435
465
|
return new Response(null, { status: 303, headers: { location: back.href } })
|
|
436
466
|
}
|
|
437
467
|
|
|
438
468
|
// Enforce rate limit before parsing bodies or running schema/protection checks so invalid floods cannot bypass throttling.
|
|
439
|
-
const retryAfter = limiter !== undefined && act.rateLimit !== undefined ? hitFor(limiter, act.rateLimit, ctx) : 0
|
|
469
|
+
const retryAfter = limiter !== undefined && act.rateLimit !== undefined ? await hitFor(limiter, act.rateLimit, ctx) : 0
|
|
440
470
|
if (retryAfter > 0) {
|
|
441
471
|
const redirected = flashAndRedirect('Too many requests', undefined, undefined)
|
|
442
472
|
if (redirected === undefined)
|
|
@@ -471,9 +501,11 @@ export async function executeAction(
|
|
|
471
501
|
}
|
|
472
502
|
|
|
473
503
|
if (act.schema !== undefined) {
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
504
|
+
const formBody = !isJsonBody(request) && isPlainRecord(cleanBody) ? cleanBody : undefined
|
|
505
|
+
const coerced = formBody !== undefined ? coerceFormArraysFromSchema(act.schema, formBody) : undefined
|
|
506
|
+
let checked = await validateSchema(act.schema, coerced !== undefined ? coerced.body : cleanBody)
|
|
507
|
+
if (!checked.ok && formBody !== undefined && coerced !== undefined && !coerced.hasJsonSchema)
|
|
508
|
+
checked = await retryWithFormArrays(act.schema, formBody, checked)
|
|
477
509
|
if (!checked.ok) {
|
|
478
510
|
// Zero-JS progressive HTML <form> submit: flash fieldErrors + safe submitted values (<4KB) and redirect 303 back to trusted Referer
|
|
479
511
|
const redirected = flashAndRedirect('Validation failed', checked.fieldErrors, cleanBody)
|
package/src/server/app-secret.ts
CHANGED
|
@@ -1,23 +1,29 @@
|
|
|
1
1
|
// The app's signing secret, and one key per purpose derived from it with HKDF so a token made for one use never verifies for another.
|
|
2
2
|
// HMAC goes through Bun.CryptoHasher, never `node:crypto`, which would add 2 MB to the server's RSS.
|
|
3
3
|
|
|
4
|
+
import { workerOf, WORKERS_SECRET_ENV } from './workers'
|
|
5
|
+
|
|
4
6
|
const EPHEMERAL_SECRET_KEY = Symbol.for('pru.form.secret')
|
|
5
7
|
const keyCache = new Map<string, Buffer>()
|
|
6
8
|
|
|
7
|
-
const hmac = (key: string | Buffer, data: string | Buffer): Buffer => new Bun.CryptoHasher('sha256', key).update(data).digest()
|
|
9
|
+
export const hmac = (key: string | Buffer, data: string | Buffer): Buffer => new Bun.CryptoHasher('sha256', key).update(data).digest()
|
|
8
10
|
|
|
9
|
-
/**
|
|
10
|
-
export function
|
|
11
|
-
const configured = process.env.PRUNELLE_FORM_SECRET || process.env.AUTH_SECRET
|
|
12
|
-
if (configured)
|
|
13
|
-
return { secret: configured, ephemeral: false }
|
|
11
|
+
/** A random secret that dies with this start: the process's, or the one a `prunelle start --workers` gives all its workers. A plugin derives its own ephemeral keys from it with `deriveKey`, so the workers agree on them. */
|
|
12
|
+
export function startSecret(): string {
|
|
14
13
|
const g = globalThis as Record<symbol, string | undefined>
|
|
15
|
-
|
|
14
|
+
// Read in a worker only: a value left in the shell of a lone process would make its secret fixed and known.
|
|
15
|
+
let secret = g[EPHEMERAL_SECRET_KEY] ?? (workerOf() === undefined ? undefined : process.env[WORKERS_SECRET_ENV])
|
|
16
16
|
if (secret === undefined) {
|
|
17
17
|
secret = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('hex')
|
|
18
18
|
g[EPHEMERAL_SECRET_KEY] = secret
|
|
19
19
|
}
|
|
20
|
-
return
|
|
20
|
+
return secret
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** The configured secret (`PRUNELLE_FORM_SECRET`, then `AUTH_SECRET`), or `startSecret()`. */
|
|
24
|
+
export function appSecret(): { secret: string, ephemeral: boolean } {
|
|
25
|
+
const configured = process.env.PRUNELLE_FORM_SECRET || process.env.AUTH_SECRET
|
|
26
|
+
return configured ? { secret: configured, ephemeral: false } : { secret: startSecret(), ephemeral: true }
|
|
21
27
|
}
|
|
22
28
|
|
|
23
29
|
/** A 32-byte key for `purpose` (`"form-timestamp"`, `"action-flash"`), HKDF-SHA256 (RFC 5869) of the app secret (or of `secret`, for a plugin with a secret of its own) with `"prunelle"` as salt and the purpose as `info`. */
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// `invalidateCache()`: drops cached route renders in this process and, through the shared store, in every other.
|
|
2
|
+
|
|
3
|
+
import type { AppRuntimeContext } from '../plugins/context'
|
|
4
|
+
import type { RouteCache } from './route-cache'
|
|
5
|
+
import type { SharedStore } from './shared-store'
|
|
6
|
+
import { getAppContext } from '../plugins/context'
|
|
7
|
+
import { serviceKey } from '../plugins/services'
|
|
8
|
+
import { SHARED_STORE } from './shared-store'
|
|
9
|
+
|
|
10
|
+
/** A path (`'/posts/hello'`), the pages under one (`'/posts/*'`), or a tag the route declares in `export const cache = { maxAge, tags }`. */
|
|
11
|
+
export type CacheTarget = string | { tag: string }
|
|
12
|
+
|
|
13
|
+
type Invalidate = (targets: readonly CacheTarget[]) => Promise<void>
|
|
14
|
+
|
|
15
|
+
const CACHE_INVALIDATION = serviceKey<Invalidate>('prunelle.cacheInvalidation')
|
|
16
|
+
const CHANNEL = 'cache'
|
|
17
|
+
const BASE = 'http://prunelle.invalid'
|
|
18
|
+
|
|
19
|
+
// Compared without a trailing slash, so `/posts/a` also drops the render of `/posts/a/`, and `/` becomes the empty prefix of every path.
|
|
20
|
+
const trimmed = (pathname: string): string => pathname.endsWith('/') ? pathname.slice(0, -1) : pathname
|
|
21
|
+
|
|
22
|
+
function pathnameOf(target: string): string {
|
|
23
|
+
if (!target.startsWith('/'))
|
|
24
|
+
throw new Error(`prunelle: invalidateCache() takes a path starting with "/", not "${target}": write '/${target}', '/${target}/*' for the pages under it, or { tag: '...' }.`)
|
|
25
|
+
if (/[?#]/.test(target))
|
|
26
|
+
throw new Error(`prunelle: invalidateCache() takes a path without its query or hash, not "${target}": a path drops the renders of every query.`)
|
|
27
|
+
return trimmed(new URL(target, BASE).pathname)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Whether a render of `pathname`, from a route declaring `tags`, is one of `targets`; throws on a target that names nothing. */
|
|
31
|
+
export function cacheTargetMatcher(targets: readonly CacheTarget[]): (pathname: string, tags: readonly string[]) => boolean {
|
|
32
|
+
const paths = new Set<string>()
|
|
33
|
+
const prefixes: string[] = []
|
|
34
|
+
const tags = new Set<string>()
|
|
35
|
+
for (const target of targets) {
|
|
36
|
+
if (typeof target !== 'string') {
|
|
37
|
+
if (typeof target.tag !== 'string' || target.tag === '')
|
|
38
|
+
throw new Error('prunelle: invalidateCache() got an empty tag: name one a route declares in `export const cache = { maxAge, tags }`.')
|
|
39
|
+
tags.add(target.tag)
|
|
40
|
+
continue
|
|
41
|
+
}
|
|
42
|
+
const star = target.indexOf('*')
|
|
43
|
+
if (star !== -1 && (star !== target.length - 1 || !target.endsWith('/*')))
|
|
44
|
+
throw new Error(`prunelle: invalidateCache() takes a "*" only at the end, after a "/", not "${target}": write '/posts/*' for every page under /posts.`)
|
|
45
|
+
if (star === -1)
|
|
46
|
+
paths.add(pathnameOf(target))
|
|
47
|
+
else
|
|
48
|
+
prefixes.push(pathnameOf(target.slice(0, -1)))
|
|
49
|
+
}
|
|
50
|
+
return (pathname, routeTags) => {
|
|
51
|
+
const path = trimmed(pathname)
|
|
52
|
+
return paths.has(path)
|
|
53
|
+
|| prefixes.some(prefix => path === prefix || path.startsWith(`${prefix}/`))
|
|
54
|
+
|| routeTags.some(tag => tags.has(tag))
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Gives the server's `invalidateCache()` its route cache, and the store that carries it to the other processes once the plugins opened it. */
|
|
59
|
+
export function serveCacheInvalidation(appCtx: AppRuntimeContext, routeCache: RouteCache | undefined): void {
|
|
60
|
+
let failing = false
|
|
61
|
+
appCtx.provide(CACHE_INVALIDATION, (targets) => {
|
|
62
|
+
routeCache?.invalidate(cacheTargetMatcher(targets))
|
|
63
|
+
const shared = appCtx.inject(SHARED_STORE)
|
|
64
|
+
if (shared === undefined)
|
|
65
|
+
return Promise.resolve()
|
|
66
|
+
return shared.publish(CHANNEL, JSON.stringify(targets)).then(() => {
|
|
67
|
+
failing = false
|
|
68
|
+
}, (error: unknown) => {
|
|
69
|
+
if (!failing)
|
|
70
|
+
console.error('prunelle: invalidateCache() dropped the renders of this process, but could not reach the others through the shared store:', error)
|
|
71
|
+
failing = true
|
|
72
|
+
})
|
|
73
|
+
})
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Drops in this process the renders another process's `invalidateCache()` named. */
|
|
77
|
+
export function receiveCacheInvalidation(shared: SharedStore | undefined, routeCache: RouteCache | undefined): void {
|
|
78
|
+
if (shared === undefined || routeCache === undefined)
|
|
79
|
+
return
|
|
80
|
+
shared.subscribe(CHANNEL, (payload) => {
|
|
81
|
+
try {
|
|
82
|
+
routeCache.invalidate(cacheTargetMatcher(JSON.parse(payload) as CacheTarget[]))
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
console.error('prunelle: a cache invalidation from another process could not be read:', error)
|
|
86
|
+
}
|
|
87
|
+
})
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Drops the cached renders of the `export const cache` routes any target matches, in this process at once and in every process sharing `store` once the promise settles; it never rejects, logging a store it cannot reach. */
|
|
91
|
+
export function invalidateCache(...targets: [CacheTarget, ...CacheTarget[]]): Promise<void> {
|
|
92
|
+
const invalidate = getAppContext()?.inject(CACHE_INVALIDATION)
|
|
93
|
+
if (invalidate === undefined)
|
|
94
|
+
throw new Error('prunelle: invalidateCache() ran outside the app\'s server: call it from an action, a route, load() or a plugin\'s server code.')
|
|
95
|
+
return invalidate(targets)
|
|
96
|
+
}
|
package/src/server/compress.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// Zero-dependency native HTTP compression (Bun.zstdCompressSync / Bun.gzipSync) with bounded byte-budget LRU.
|
|
2
2
|
// `node:zlib` (3 MB of RSS) loads only with the first page streamed to a client taking gzip and not zstd, as Bun has no streaming gzip of its own that flushes.
|
|
3
3
|
|
|
4
|
+
import { markHandled } from './discard'
|
|
5
|
+
|
|
4
6
|
export type CompressionEncoding = 'zstd' | 'gzip'
|
|
5
7
|
export type PrecompressedEncoding = 'br' | 'gzip'
|
|
6
8
|
|
|
@@ -134,7 +136,7 @@ export async function readBufferedOrPassThrough(
|
|
|
134
136
|
|
|
135
137
|
while (true) {
|
|
136
138
|
const readPromise = reader.read()
|
|
137
|
-
|
|
139
|
+
markHandled(readPromise)
|
|
138
140
|
const tick = Promise.resolve().then(() => Promise.resolve()).then((): typeof PENDING => PENDING)
|
|
139
141
|
const outcome = await Promise.race([readPromise, tick])
|
|
140
142
|
if (outcome === PENDING) {
|
package/src/server/consent.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import type { PluginRouteOptions } from '../plugins/types'
|
|
4
4
|
import type { RequestContext } from './http'
|
|
5
5
|
import type { TrustProxy } from './security'
|
|
6
|
+
import { expireCookiesOf } from './cookies'
|
|
6
7
|
import { wantsJson } from './http'
|
|
7
8
|
import { isTrustedOrigin, safeRedirect } from './security'
|
|
8
9
|
|
|
@@ -37,6 +38,8 @@ export interface RequestConsent {
|
|
|
37
38
|
readonly labels: Readonly<Record<string, string>>
|
|
38
39
|
/** Path the consent form posts to. */
|
|
39
40
|
readonly endpoint: string
|
|
41
|
+
/** The app's `lang`, which picks the language of the default texts of `<ConsentBanner>` and `<ConsentPreferences>`. */
|
|
42
|
+
readonly lang: string
|
|
40
43
|
has(category: string): boolean
|
|
41
44
|
all(): Record<string, boolean>
|
|
42
45
|
}
|
|
@@ -49,6 +52,7 @@ export interface NormalizedConsentConfig {
|
|
|
49
52
|
readonly maxAge: number
|
|
50
53
|
readonly endpoint: string
|
|
51
54
|
readonly version: string
|
|
55
|
+
readonly lang: string
|
|
52
56
|
}
|
|
53
57
|
|
|
54
58
|
const EMPTY_CONSENT: RequestConsent = {
|
|
@@ -57,11 +61,12 @@ const EMPTY_CONSENT: RequestConsent = {
|
|
|
57
61
|
categories: [],
|
|
58
62
|
labels: {},
|
|
59
63
|
endpoint: DEFAULT_CONSENT_ENDPOINT,
|
|
64
|
+
lang: 'en',
|
|
60
65
|
has: category => category === 'essential',
|
|
61
66
|
all: () => ({}),
|
|
62
67
|
}
|
|
63
68
|
|
|
64
|
-
export function normalizeConsentConfig(config: ConsentConfig | undefined): NormalizedConsentConfig | undefined {
|
|
69
|
+
export function normalizeConsentConfig(config: ConsentConfig | undefined, lang = 'en'): NormalizedConsentConfig | undefined {
|
|
65
70
|
if (config === undefined)
|
|
66
71
|
return undefined
|
|
67
72
|
const rawList = Array.isArray(config.categories) ? config.categories : Object.keys(config.categories)
|
|
@@ -94,6 +99,7 @@ export function normalizeConsentConfig(config: ConsentConfig | undefined): Norma
|
|
|
94
99
|
maxAge: config.maxAge ?? DEFAULT_CONSENT_MAX_AGE,
|
|
95
100
|
endpoint,
|
|
96
101
|
version,
|
|
102
|
+
lang,
|
|
97
103
|
}
|
|
98
104
|
}
|
|
99
105
|
|
|
@@ -133,7 +139,11 @@ export function serializeConsentCookie(granted: ReadonlySet<string>, declared: r
|
|
|
133
139
|
return `${COOKIE_PREFIX}${Math.floor(decidedAt.getTime() / 1000)}:${version}:${ordered.join(',')}`
|
|
134
140
|
}
|
|
135
141
|
|
|
136
|
-
export function createRequestConsent(
|
|
142
|
+
export function createRequestConsent(
|
|
143
|
+
rawCookie: string | undefined,
|
|
144
|
+
config: NormalizedConsentConfig | undefined,
|
|
145
|
+
resolveLang?: () => string | undefined,
|
|
146
|
+
): RequestConsent {
|
|
137
147
|
if (config === undefined)
|
|
138
148
|
return EMPTY_CONSENT
|
|
139
149
|
const { decided, decidedAt, granted } = parseConsentCookie(rawCookie, config.categorySet, config.version)
|
|
@@ -143,6 +153,9 @@ export function createRequestConsent(rawCookie: string | undefined, config: Norm
|
|
|
143
153
|
categories: config.categories,
|
|
144
154
|
labels: config.labels,
|
|
145
155
|
endpoint: config.endpoint,
|
|
156
|
+
get lang(): string {
|
|
157
|
+
return resolveLang?.() ?? config.lang
|
|
158
|
+
},
|
|
146
159
|
has(category: string): boolean {
|
|
147
160
|
return category === 'essential' || granted.has(category)
|
|
148
161
|
},
|
|
@@ -281,6 +294,7 @@ export function registerConsentRoute(
|
|
|
281
294
|
maxAge: config.maxAge,
|
|
282
295
|
category: 'essential',
|
|
283
296
|
})
|
|
297
|
+
expireCookiesOf(ctx.cookies, config.categories.filter(category => !parsed.granted.has(category)))
|
|
284
298
|
|
|
285
299
|
if (wantsJson(ctx.request)) {
|
|
286
300
|
const consent: Record<string, boolean> = {}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// The cookies `<CookieTable>` lists: prunelle's own, each plugin's and the app's, gathered once per server into its app context.
|
|
2
|
+
|
|
3
|
+
import type { BuildManifest } from '../build/manifest'
|
|
4
|
+
import type { AppRuntimeContext, CreateAppContextOptions } from '../plugins/context'
|
|
5
|
+
import type { PrunellePlugin } from '../plugins/types'
|
|
6
|
+
import type { NormalizedConsentConfig } from './consent'
|
|
7
|
+
import { createAppContext } from '../plugins/context'
|
|
8
|
+
import { serviceKey } from '../plugins/services'
|
|
9
|
+
import { ACTION_ERROR_COOKIE, ACTION_ERROR_MAX_AGE } from './action-flash'
|
|
10
|
+
|
|
11
|
+
/** One row of the table; a field left out could not be read from the app's source. */
|
|
12
|
+
export interface CookieRow {
|
|
13
|
+
name?: string | undefined
|
|
14
|
+
purpose?: string | Readonly<Record<string, string>> | undefined
|
|
15
|
+
category?: string | undefined
|
|
16
|
+
lifetime?: number | 'session' | undefined
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface CookieInventory {
|
|
20
|
+
readonly rows: readonly CookieRow[]
|
|
21
|
+
/** The app's `lang`, which picks the language of the table. */
|
|
22
|
+
readonly lang: string
|
|
23
|
+
/** The consent categories' labels, shown in the category column. */
|
|
24
|
+
readonly labels: Readonly<Record<string, string>>
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export const COOKIE_INVENTORY = serviceKey<CookieInventory>('prunelle.cookies')
|
|
28
|
+
|
|
29
|
+
const CONSENT_PURPOSE = {
|
|
30
|
+
en: 'Keeps your cookie choices, so you are not asked again on each page.',
|
|
31
|
+
fr: 'Garde vos choix de cookies, pour ne pas vous les redemander à chaque page.',
|
|
32
|
+
}
|
|
33
|
+
const ACTION_ERROR_PURPOSE = {
|
|
34
|
+
en: 'Shows the error of a form sent without JavaScript on the page it returns to.',
|
|
35
|
+
fr: 'Affiche l\'erreur d\'un formulaire envoyé sans JavaScript sur la page où il revient.',
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface CookieInventoryOptions {
|
|
39
|
+
consent: NormalizedConsentConfig | undefined
|
|
40
|
+
manifest: Pick<BuildManifest, 'actions' | 'cookies'>
|
|
41
|
+
plugins: readonly PrunellePlugin[]
|
|
42
|
+
site: string | undefined
|
|
43
|
+
lang: string
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function cookieInventory({ consent, manifest, plugins, site, lang }: CookieInventoryOptions): CookieInventory {
|
|
47
|
+
const rows: CookieRow[] = []
|
|
48
|
+
if (consent !== undefined)
|
|
49
|
+
rows.push({ name: consent.cookieName, purpose: CONSENT_PURPOSE, category: 'essential', lifetime: consent.maxAge })
|
|
50
|
+
if (manifest.actions.length > 0)
|
|
51
|
+
rows.push({ name: ACTION_ERROR_COOKIE, purpose: ACTION_ERROR_PURPOSE, category: 'essential', lifetime: ACTION_ERROR_MAX_AGE })
|
|
52
|
+
for (const plugin of plugins) {
|
|
53
|
+
const declared = typeof plugin.cookies === 'function' ? plugin.cookies({ site }) : plugin.cookies ?? []
|
|
54
|
+
for (const cookie of declared)
|
|
55
|
+
rows.push({ name: cookie.name, purpose: cookie.purpose, category: cookie.category, lifetime: cookie.maxAge ?? 'session' })
|
|
56
|
+
}
|
|
57
|
+
rows.push(...manifest.cookies ?? [])
|
|
58
|
+
return { rows, lang, labels: consent?.labels ?? {} }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface ServerAppContextOptions extends Omit<CreateAppContextOptions, 'onRegisterPublicFile'>, Omit<CookieInventoryOptions, 'site'> {
|
|
62
|
+
/** The build's context when the server runs inside one, told of each public file a plugin writes. */
|
|
63
|
+
parent: AppRuntimeContext | undefined
|
|
64
|
+
registerPublicFromDisk: (publicDir: string, rel: string) => void
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The server's app context, holding the cookie inventory `<CookieTable>` renders. */
|
|
68
|
+
export function createServerAppContext({ parent, registerPublicFromDisk, consent, manifest, plugins, lang, ...options }: ServerAppContextOptions): AppRuntimeContext {
|
|
69
|
+
const appCtx = createAppContext({
|
|
70
|
+
...options,
|
|
71
|
+
onRegisterPublicFile: (rel) => {
|
|
72
|
+
parent?.registerPublicFile(rel)
|
|
73
|
+
registerPublicFromDisk(options.publicDir, rel)
|
|
74
|
+
},
|
|
75
|
+
})
|
|
76
|
+
appCtx.provide(COOKIE_INVENTORY, cookieInventory({ consent, manifest, plugins, site: options.site, lang }))
|
|
77
|
+
return appCtx
|
|
78
|
+
}
|