@crombolo/server 0.39.1 → 0.40.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/package.json +13 -13
- package/src/actions.ts +193 -0
- package/src/adapters/documents.ts +1 -0
- package/src/adapters/health.ts +23 -0
- package/src/config.ts +7 -1
- package/src/form-submit.ts +41 -18
- package/src/index.ts +1 -0
- package/src/islands.ts +1 -1
- package/src/ports.ts +4 -0
- package/src/routes.ts +1 -1
- package/src/server.ts +40 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crombolo/server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.40.0",
|
|
4
4
|
"description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. The crombolo HTTP server: routing, configuration, media stores and background jobs.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Crombolo",
|
|
@@ -31,18 +31,18 @@
|
|
|
31
31
|
"access": "public"
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
34
|
-
"@crombolo/api-delivery": "0.
|
|
35
|
-
"@crombolo/api-management": "0.
|
|
36
|
-
"@crombolo/auth": "0.
|
|
37
|
-
"@crombolo/backoffice-host": "0.
|
|
38
|
-
"@crombolo/common": "0.
|
|
39
|
-
"@crombolo/content": "0.
|
|
40
|
-
"@crombolo/contracts": "0.
|
|
41
|
-
"@crombolo/core": "0.
|
|
42
|
-
"@crombolo/data": "0.
|
|
43
|
-
"@crombolo/render": "0.
|
|
44
|
-
"@crombolo/schema": "0.
|
|
45
|
-
"@crombolo/transfer": "0.
|
|
34
|
+
"@crombolo/api-delivery": "0.40.0",
|
|
35
|
+
"@crombolo/api-management": "0.40.0",
|
|
36
|
+
"@crombolo/auth": "0.40.0",
|
|
37
|
+
"@crombolo/backoffice-host": "0.40.0",
|
|
38
|
+
"@crombolo/common": "0.40.0",
|
|
39
|
+
"@crombolo/content": "0.40.0",
|
|
40
|
+
"@crombolo/contracts": "0.40.0",
|
|
41
|
+
"@crombolo/core": "0.40.0",
|
|
42
|
+
"@crombolo/data": "0.40.0",
|
|
43
|
+
"@crombolo/render": "0.40.0",
|
|
44
|
+
"@crombolo/schema": "0.40.0",
|
|
45
|
+
"@crombolo/transfer": "0.40.0",
|
|
46
46
|
"@logtape/logtape": "^2.3.8",
|
|
47
47
|
"jose": "^6.2.12"
|
|
48
48
|
}
|
package/src/actions.ts
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server actions (story 219): `POST /crombolo/actions/{id}`, through route
|
|
3
|
+
* handlers' pipeline, so CSRF, the rate limit, the time limit and the signal
|
|
4
|
+
* are theirs. A form post is answered with a 303 back, its result in a signed
|
|
5
|
+
* flash cookie; a call asking for JSON with the result itself.
|
|
6
|
+
* docs/rendering.md, "Server actions".
|
|
7
|
+
*/
|
|
8
|
+
import {
|
|
9
|
+
ACTIONS_PATH,
|
|
10
|
+
type ActionState,
|
|
11
|
+
isOutcome,
|
|
12
|
+
Ok,
|
|
13
|
+
type Outcome,
|
|
14
|
+
type RouteContext,
|
|
15
|
+
route,
|
|
16
|
+
type ServerAction,
|
|
17
|
+
} from '@crombolo/common'
|
|
18
|
+
import { readSignedFlash, writeSignedFlash } from './form-submit.ts'
|
|
19
|
+
import type { DeclaredRoute } from './routes.ts'
|
|
20
|
+
|
|
21
|
+
/** The cookie an action's result returns to the page in. */
|
|
22
|
+
export const ACTION_FLASH_COOKIE = 'crombolo-action'
|
|
23
|
+
|
|
24
|
+
/** The fields an action's form carries for Crombolo, taken out before the action sees them. */
|
|
25
|
+
export const RETURN_FIELD = '__return'
|
|
26
|
+
export const ANTIFORGERY_FIELD = '__antiforgery'
|
|
27
|
+
|
|
28
|
+
/** Fields whose values are never sent back to the page: what a password field is called. */
|
|
29
|
+
const SECRET_FIELD = /pass(word)?|secret|pin$/i
|
|
30
|
+
|
|
31
|
+
/** The site's actions, by id and by function. */
|
|
32
|
+
export interface ActionRegistry {
|
|
33
|
+
ids: readonly string[]
|
|
34
|
+
/** The id a listed function answers at, or undefined for one the config does not list. */
|
|
35
|
+
idOf(action: unknown): string | undefined
|
|
36
|
+
byId(id: string): ServerAction | undefined
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** A flash: which action answered, and what. */
|
|
40
|
+
export interface ActionFlash {
|
|
41
|
+
id: string
|
|
42
|
+
state: ActionState
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The config's action modules as a registry, and why any of it cannot be
|
|
47
|
+
* mounted: an export that is not a function, a module key with a dot in it,
|
|
48
|
+
* or one function listed twice.
|
|
49
|
+
*/
|
|
50
|
+
export function actionRegistry(modules: Record<string, Record<string, unknown>> | undefined): {
|
|
51
|
+
registry: ActionRegistry
|
|
52
|
+
problems: string[]
|
|
53
|
+
} {
|
|
54
|
+
const byId = new Map<string, ServerAction>()
|
|
55
|
+
const ids = new Map<unknown, string>()
|
|
56
|
+
const problems: string[] = []
|
|
57
|
+
for (const [moduleKey, exports] of Object.entries(modules ?? {})) {
|
|
58
|
+
if (moduleKey.includes('.')) {
|
|
59
|
+
problems.push(
|
|
60
|
+
`The action module "${moduleKey}" has a dot in its key; an action's id is the key, a dot, and the export's name.`,
|
|
61
|
+
)
|
|
62
|
+
continue
|
|
63
|
+
}
|
|
64
|
+
for (const [name, action] of Object.entries(exports ?? {})) {
|
|
65
|
+
const id = `${moduleKey}.${name}`
|
|
66
|
+
if (typeof action !== 'function') {
|
|
67
|
+
problems.push(
|
|
68
|
+
`"${id}" is not a function: every export of an action module is an action, so move anything else to a module of its own.`,
|
|
69
|
+
)
|
|
70
|
+
continue
|
|
71
|
+
}
|
|
72
|
+
const listed = ids.get(action)
|
|
73
|
+
if (listed) {
|
|
74
|
+
problems.push(`One function is listed as two actions, "${listed}" and "${id}".`)
|
|
75
|
+
continue
|
|
76
|
+
}
|
|
77
|
+
ids.set(action, id)
|
|
78
|
+
byId.set(id, action as ServerAction)
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
registry: {
|
|
83
|
+
ids: [...byId.keys()],
|
|
84
|
+
idOf: (action) => ids.get(action),
|
|
85
|
+
byId: (id) => byId.get(id),
|
|
86
|
+
},
|
|
87
|
+
problems,
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Where an action's form returns: a path on this site, else the home page. */
|
|
92
|
+
export function returnPath(value: FormDataEntryValue | null): string {
|
|
93
|
+
if (typeof value !== 'string') return '/'
|
|
94
|
+
if (!value.startsWith('/') || value.startsWith('//') || value.startsWith('/\\')) return '/'
|
|
95
|
+
return value
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const wantsJson = (request: Request) =>
|
|
99
|
+
(request.headers.get('accept') ?? '').includes('application/json')
|
|
100
|
+
|
|
101
|
+
/** What was submitted, to fill the form again: strings only, secrets left out. */
|
|
102
|
+
function submitted(form: FormData): Record<string, string> {
|
|
103
|
+
const values: Record<string, string> = {}
|
|
104
|
+
for (const [name, value] of form)
|
|
105
|
+
if (typeof value === 'string' && !SECRET_FIELD.test(name)) values[name] = value
|
|
106
|
+
return values
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The route each action answers at, through the site's route pipeline. */
|
|
110
|
+
export function actionRoutes(
|
|
111
|
+
registry: ActionRegistry,
|
|
112
|
+
flashSecret: string,
|
|
113
|
+
secureCookies: boolean,
|
|
114
|
+
) {
|
|
115
|
+
const flashCookie = (flash: ActionFlash) => {
|
|
116
|
+
const value = writeSignedFlash(flashSecret, flash, [
|
|
117
|
+
{ state: { ...flash.state, values: {} } },
|
|
118
|
+
{ state: { ...flash.state, values: {}, value: undefined } },
|
|
119
|
+
])
|
|
120
|
+
return `${ACTION_FLASH_COOKIE}=${value}; Path=/; Max-Age=60; HttpOnly; SameSite=Lax${secureCookies ? '; Secure' : ''}`
|
|
121
|
+
}
|
|
122
|
+
const back = (location: string, flash: ActionFlash) =>
|
|
123
|
+
new Response(null, {
|
|
124
|
+
status: 303,
|
|
125
|
+
headers: { location, 'set-cookie': flashCookie(flash), 'cache-control': 'no-store' },
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
const entries = new Map<string, DeclaredRoute>()
|
|
129
|
+
for (const id of registry.ids) {
|
|
130
|
+
const action = registry.byId(id) as ServerAction
|
|
131
|
+
const handler = async (request: Request, context: RouteContext): Promise<Response> => {
|
|
132
|
+
const json = wantsJson(request)
|
|
133
|
+
const form = await request.formData().catch(() => undefined)
|
|
134
|
+
if (!form)
|
|
135
|
+
return Response.json(
|
|
136
|
+
{ ok: false, status: 400, message: 'An action is posted as a form.' },
|
|
137
|
+
{ status: 400 },
|
|
138
|
+
)
|
|
139
|
+
const to = returnPath(form.get(RETURN_FIELD))
|
|
140
|
+
form.delete(RETURN_FIELD)
|
|
141
|
+
form.delete(ANTIFORGERY_FIELD)
|
|
142
|
+
const { params: _, ...actionContext } = context
|
|
143
|
+
let answer: Response | Ok<unknown> | Outcome | unknown
|
|
144
|
+
try {
|
|
145
|
+
answer = await action(form, actionContext)
|
|
146
|
+
} catch (error) {
|
|
147
|
+
// `redirect()` and `notFound()` throw their outcome, as in a page.
|
|
148
|
+
if (!isOutcome(error)) throw error
|
|
149
|
+
answer = error
|
|
150
|
+
}
|
|
151
|
+
if (answer instanceof Response) return answer
|
|
152
|
+
if (isOutcome(answer)) {
|
|
153
|
+
if (answer.isRedirect)
|
|
154
|
+
return json
|
|
155
|
+
? Response.json({ ok: true, redirect: answer.location })
|
|
156
|
+
: back(answer.location as string, { id, state: { ok: true } })
|
|
157
|
+
const state: ActionState = {
|
|
158
|
+
ok: false,
|
|
159
|
+
status: answer.status,
|
|
160
|
+
message: answer.message,
|
|
161
|
+
errors: answer.errors,
|
|
162
|
+
values: submitted(form),
|
|
163
|
+
}
|
|
164
|
+
return json
|
|
165
|
+
? Response.json(
|
|
166
|
+
{ ok: false, status: answer.status, message: answer.message, errors: answer.errors },
|
|
167
|
+
{ status: answer.status },
|
|
168
|
+
)
|
|
169
|
+
: back(to, { id, state })
|
|
170
|
+
}
|
|
171
|
+
const value = answer instanceof Ok ? answer.value : answer
|
|
172
|
+
return json
|
|
173
|
+
? Response.json({ ok: true, value })
|
|
174
|
+
: back(to, { id, state: { ok: true, value } })
|
|
175
|
+
}
|
|
176
|
+
entries.set(id, {
|
|
177
|
+
route: route(`${ACTIONS_PATH}/${id}`, { POST: handler as never }),
|
|
178
|
+
owner: `the action ${id}`,
|
|
179
|
+
})
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
return {
|
|
183
|
+
/** The action a path names, or undefined when it names none. */
|
|
184
|
+
match(pathname: string): DeclaredRoute | undefined {
|
|
185
|
+
if (!pathname.startsWith(`${ACTIONS_PATH}/`)) return undefined
|
|
186
|
+
return entries.get(decodeURIComponent(pathname.slice(ACTIONS_PATH.length + 1)))
|
|
187
|
+
},
|
|
188
|
+
/** The flash a page returned to holds, when its signature holds and it is fresh. */
|
|
189
|
+
readFlash(cookie: string | undefined): ActionFlash | undefined {
|
|
190
|
+
return readSignedFlash<ActionFlash>(flashSecret, cookie)
|
|
191
|
+
},
|
|
192
|
+
}
|
|
193
|
+
}
|
|
@@ -582,6 +582,7 @@ export function createPublishedContentSource(
|
|
|
582
582
|
return out
|
|
583
583
|
},
|
|
584
584
|
loadContentTypeAliases: () => new ContentTypeRepository(db).aliasesByKey(),
|
|
585
|
+
loadSiteSettingsTypes: () => new ContentTypeRepository(db).siteSettingsAliases(),
|
|
585
586
|
loadUrlOptions: () => readUrlOptions(db),
|
|
586
587
|
|
|
587
588
|
async loadRedirects() {
|
package/src/adapters/health.ts
CHANGED
|
@@ -41,6 +41,7 @@ const CHECKS = {
|
|
|
41
41
|
nodes: { id: '6f1d4a8e-0047-4c1a-9e7d-000000000005', name: 'Servers' },
|
|
42
42
|
outgoing: { id: '6f1d4a8e-0047-4c1a-9e7d-000000000006', name: 'Outgoing changes' },
|
|
43
43
|
routes: { id: '6f1d4a8e-0047-4c1a-9e7d-000000000007', name: 'Routes and pages' },
|
|
44
|
+
settings: { id: '6f1d4a8e-0047-4c1a-9e7d-000000000008', name: 'Site settings' },
|
|
44
45
|
} as const
|
|
45
46
|
|
|
46
47
|
/** Waiting longer than this means nothing is sending: no server is running its jobs, or one is stuck. */
|
|
@@ -87,6 +88,11 @@ const GROUPS: HealthCheckGroup[] = [
|
|
|
87
88
|
description:
|
|
88
89
|
"Whether a route in the site's code answers at an address a published page also has, which hides the page.",
|
|
89
90
|
},
|
|
91
|
+
{
|
|
92
|
+
...CHECKS.settings,
|
|
93
|
+
description:
|
|
94
|
+
"Whether each site has at most one settings page, kept directly below the site's top page.",
|
|
95
|
+
},
|
|
90
96
|
],
|
|
91
97
|
},
|
|
92
98
|
]
|
|
@@ -166,6 +172,10 @@ export interface HealthCheckOptions {
|
|
|
166
172
|
now?: () => Date
|
|
167
173
|
/** Published pages a route answers in place of (story 211). */
|
|
168
174
|
hiddenByRoutes?: () => Promise<Array<{ route: string; owner: string; page: string; url: string }>>
|
|
175
|
+
/** Settings pages that are not, or not alone, their site's settings (story 058). */
|
|
176
|
+
siteSettingsFindings?: () => Promise<
|
|
177
|
+
Array<{ kind: 'second' | 'deep'; name: string; counted?: string }>
|
|
178
|
+
>
|
|
169
179
|
}
|
|
170
180
|
|
|
171
181
|
const result = (
|
|
@@ -351,6 +361,19 @@ export function createDiagnosticsPort(options: HealthCheckOptions): DiagnosticsP
|
|
|
351
361
|
),
|
|
352
362
|
)
|
|
353
363
|
},
|
|
364
|
+
[CHECKS.settings.id]: async () => {
|
|
365
|
+
const findings = (await options.siteSettingsFindings?.()) ?? []
|
|
366
|
+
if (findings.length === 0)
|
|
367
|
+
return [result('Success', 'Every settings page is where its site reads it.')]
|
|
368
|
+
return findings.map((f) =>
|
|
369
|
+
result(
|
|
370
|
+
'Warning',
|
|
371
|
+
f.kind === 'second'
|
|
372
|
+
? `"${f.name}" is a second settings page for its site, so it is not used: "${f.counted}" is.`
|
|
373
|
+
: `"${f.name}" is a settings page below another page, so no site reads it. Move it directly below its site's top page.`,
|
|
374
|
+
),
|
|
375
|
+
)
|
|
376
|
+
},
|
|
354
377
|
[CHECKS.outgoing.id]: async () =>
|
|
355
378
|
outgoingResults(
|
|
356
379
|
{
|
package/src/config.ts
CHANGED
|
@@ -216,6 +216,12 @@ export interface CromboloConfig {
|
|
|
216
216
|
* finding. docs/rendering.md, "Route handlers".
|
|
217
217
|
*/
|
|
218
218
|
routes?: SiteRoute<SiteServices, RequestMember>[]
|
|
219
|
+
/**
|
|
220
|
+
* The site's server actions (story 219), a module at a time:
|
|
221
|
+
* `actions: { profile }` after `import * as profile from '#actions/profile.ts'`.
|
|
222
|
+
* Each export is an action, `profile.save`. docs/rendering.md, "Server actions".
|
|
223
|
+
*/
|
|
224
|
+
actions?: Record<string, Record<string, unknown>>
|
|
219
225
|
/** How long a route handler may take before it answers 504; 0 for no limit. */
|
|
220
226
|
routeTimeoutMs: number
|
|
221
227
|
/** Requests a minute each caller may make to the site's routes, on each server; 0 for no limit. */
|
|
@@ -976,7 +982,7 @@ export function describeDatabase(
|
|
|
976
982
|
}
|
|
977
983
|
}
|
|
978
984
|
|
|
979
|
-
export const VERSION = '0.
|
|
985
|
+
export const VERSION = '0.40.0'
|
|
980
986
|
|
|
981
987
|
/** A whole number of seconds from the environment; undefined when unset or not one. */
|
|
982
988
|
/** A positive number from a setting, else the default. */
|
package/src/form-submit.ts
CHANGED
|
@@ -166,39 +166,62 @@ interface Flash extends FormSubmissionState {
|
|
|
166
166
|
}
|
|
167
167
|
|
|
168
168
|
export function writeFlash(secret: string, state: FormSubmissionState): string {
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
169
|
+
// The messages matter more than redisplaying what was typed, and a cookie
|
|
170
|
+
// the browser silently drops would lose both.
|
|
171
|
+
return writeSignedFlash(secret, state, [{ values: {} }])
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* A signed, timestamped flash cookie's value, trimmed by each of `fallbacks`
|
|
176
|
+
* in turn while it is over the size a cookie can safely hold. Core forms' and
|
|
177
|
+
* server actions' (story 219).
|
|
178
|
+
*/
|
|
179
|
+
export function writeSignedFlash(
|
|
180
|
+
secret: string,
|
|
181
|
+
payload: object,
|
|
182
|
+
fallbacks: readonly object[] = [],
|
|
183
|
+
): string {
|
|
184
|
+
let current = { ...payload, at: Date.now() }
|
|
185
|
+
let json = JSON.stringify(current)
|
|
186
|
+
for (const trim of fallbacks) {
|
|
187
|
+
if (json.length <= MAX_FLASH_BYTES) break
|
|
188
|
+
current = { ...current, ...trim }
|
|
189
|
+
json = JSON.stringify(current)
|
|
190
|
+
}
|
|
175
191
|
const body = Buffer.from(json).toString('base64url')
|
|
176
192
|
return `${body}.${hmac(secret, body)}`
|
|
177
193
|
}
|
|
178
194
|
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
cookie: string | undefined,
|
|
182
|
-
): FormSubmissionState | undefined {
|
|
195
|
+
/** A flash cookie's payload when its signature holds and it is fresh. */
|
|
196
|
+
export function readSignedFlash<T>(secret: string, cookie: string | undefined): T | undefined {
|
|
183
197
|
if (!cookie) return undefined
|
|
184
198
|
const [body, signature] = cookie.split('.')
|
|
185
199
|
if (!body || !signature) return undefined
|
|
186
200
|
if (!sameSignature(hmac(secret, body), signature)) return undefined
|
|
187
201
|
try {
|
|
188
|
-
const parsed = JSON.parse(Buffer.from(body, 'base64url').toString('utf8')) as
|
|
202
|
+
const parsed = JSON.parse(Buffer.from(body, 'base64url').toString('utf8')) as T & { at: number }
|
|
189
203
|
if (Date.now() - parsed.at > FLASH_SECONDS * 1000) return undefined
|
|
190
|
-
return
|
|
191
|
-
formKey: parsed.formKey,
|
|
192
|
-
formAlias: parsed.formAlias,
|
|
193
|
-
values: parsed.values ?? {},
|
|
194
|
-
errors: parsed.errors ?? [],
|
|
195
|
-
message: parsed.message,
|
|
196
|
-
}
|
|
204
|
+
return parsed
|
|
197
205
|
} catch {
|
|
198
206
|
return undefined
|
|
199
207
|
}
|
|
200
208
|
}
|
|
201
209
|
|
|
210
|
+
export function readFlash(
|
|
211
|
+
secret: string,
|
|
212
|
+
cookie: string | undefined,
|
|
213
|
+
): FormSubmissionState | undefined {
|
|
214
|
+
const parsed = readSignedFlash<Flash>(secret, cookie)
|
|
215
|
+
if (!parsed) return undefined
|
|
216
|
+
return {
|
|
217
|
+
formKey: parsed.formKey,
|
|
218
|
+
formAlias: parsed.formAlias,
|
|
219
|
+
values: parsed.values ?? {},
|
|
220
|
+
errors: parsed.errors ?? [],
|
|
221
|
+
message: parsed.message,
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
202
225
|
// ------------------------------------------------------------------ the submission
|
|
203
226
|
|
|
204
227
|
export interface FormSubmitDeps {
|
package/src/index.ts
CHANGED
package/src/islands.ts
CHANGED
|
@@ -10,7 +10,7 @@ import { ISLANDS_DIR, ISLANDS_PATH, type IslandManifest } from '@crombolo/render
|
|
|
10
10
|
|
|
11
11
|
/** What a client module may not import: code that only runs on the server. */
|
|
12
12
|
const SERVER_ONLY =
|
|
13
|
-
/^(@crombolo\/(crombolo|render|server|core|data|content|auth|schema|transfer|api-delivery|api-management)(\/.*)
|
|
13
|
+
/^(@crombolo\/(crombolo|render|server|core|data|content|auth|schema|transfer|api-delivery|api-management)(\/.*)?|#actions\/.*|node:.*|bun(:.*)?)$/
|
|
14
14
|
/** Whether a client module importing this would pull server code into the browser. */
|
|
15
15
|
export const isServerOnly = (specifier: string): boolean =>
|
|
16
16
|
SERVER_ONLY.test(specifier) && specifier !== BROWSER_ENTRY
|
package/src/ports.ts
CHANGED
|
@@ -353,6 +353,9 @@ export function resolveUserLinkSender(
|
|
|
353
353
|
export interface DepsOptions {
|
|
354
354
|
/** Published pages a site route answers in place of, for the health check (story 211). */
|
|
355
355
|
hiddenByRoutes?: () => Promise<Array<{ route: string; owner: string; page: string; url: string }>>
|
|
356
|
+
siteSettingsFindings?: () => Promise<
|
|
357
|
+
Array<{ kind: 'second' | 'deep'; name: string; counted?: string }>
|
|
358
|
+
>
|
|
356
359
|
config: CromboloConfig
|
|
357
360
|
paths: BackOfficePaths
|
|
358
361
|
/** The site's installed npm extensions, which contribute their manifests. */
|
|
@@ -481,6 +484,7 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
|
|
|
481
484
|
nodeState: options.schema?.nodeState,
|
|
482
485
|
fetch: options.fetch,
|
|
483
486
|
hiddenByRoutes: options.hiddenByRoutes,
|
|
487
|
+
siteSettingsFindings: options.siteSettingsFindings,
|
|
484
488
|
})
|
|
485
489
|
const tags = new TagRepository(options.db)
|
|
486
490
|
deps.tags = { list: (filter) => tags.all(filter) }
|
package/src/routes.ts
CHANGED
|
@@ -117,10 +117,10 @@ const prefersHtml = (request: Request) => {
|
|
|
117
117
|
return html >= 0 && (json < 0 || html < json)
|
|
118
118
|
}
|
|
119
119
|
|
|
120
|
-
/** Builds the site's route pipeline over its routes and its bundles'. */
|
|
121
120
|
/** Why a route's signal is aborted once its answer has been sent. */
|
|
122
121
|
const ANSWERED = new Error('The answer has been sent.')
|
|
123
122
|
|
|
123
|
+
/** Builds the site's route pipeline over its routes and its bundles'. */
|
|
124
124
|
export function createRoutes<Member extends RouteMember>(
|
|
125
125
|
declared: readonly DeclaredRoute[],
|
|
126
126
|
deps: RouteDeps<Member>,
|
package/src/server.ts
CHANGED
|
@@ -128,6 +128,7 @@ import type { SyncReport } from '@crombolo/schema'
|
|
|
128
128
|
import { choicesFor } from '@crombolo/transfer'
|
|
129
129
|
import type { Server } from 'bun'
|
|
130
130
|
import { createNodeLookup, loadAccess } from './access.ts'
|
|
131
|
+
import { ACTION_FLASH_COOKIE, actionRegistry, actionRoutes } from './actions.ts'
|
|
131
132
|
import { createAuditHost, createAuditSink, pluginAuditPlan, recordAudit } from './adapters/audit.ts'
|
|
132
133
|
import { readCreatedBundlePackage, writeCreatedBundlePackage } from './adapters/bundles.ts'
|
|
133
134
|
import { createPublishedContentSource, loadDraftNode } from './adapters/documents.ts'
|
|
@@ -199,7 +200,7 @@ import type { JobsStatus } from './worker-watch.ts'
|
|
|
199
200
|
|
|
200
201
|
export { PREVIEW_COOKIE }
|
|
201
202
|
|
|
202
|
-
import type
|
|
203
|
+
import { ACTIONS_PATH, type SiteRoute } from '@crombolo/common'
|
|
203
204
|
import { backofficeAudience } from './backoffice-external.ts'
|
|
204
205
|
import { createExternalSignIn } from './external-sign-in.ts'
|
|
205
206
|
import { IdentityProviderOverrides } from './identity-provider-overrides.ts'
|
|
@@ -970,6 +971,12 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
|
|
|
970
971
|
cors: formCors,
|
|
971
972
|
})
|
|
972
973
|
|
|
974
|
+
// Story 219: the site's server actions, a module at a time.
|
|
975
|
+
const { registry: actionList, problems: actionProblems } = actionRegistry(config.actions)
|
|
976
|
+
if (actionProblems.length > 0)
|
|
977
|
+
throw new Error(`The site's actions cannot be mounted:\n- ${actionProblems.join('\n- ')}`)
|
|
978
|
+
const siteActions = actionRoutes(actionList, formSecret, config.secureCookies)
|
|
979
|
+
|
|
973
980
|
const notImplementedLog = logger('not-implemented')
|
|
974
981
|
const notImplemented = new NotImplementedLog((line, entry) => {
|
|
975
982
|
// The console line is the development aid; the file keeps it for the log viewer
|
|
@@ -1006,6 +1013,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
|
|
|
1006
1013
|
const managementDeps = createDeps({
|
|
1007
1014
|
config,
|
|
1008
1015
|
paths,
|
|
1016
|
+
siteSettingsFindings: () => cache.settingsFindings(),
|
|
1009
1017
|
hiddenByRoutes: async () => {
|
|
1010
1018
|
const snapshot = await cache.snapshot()
|
|
1011
1019
|
const hidden: Array<{ route: string; owner: string; page: string; url: string }> = []
|
|
@@ -1266,6 +1274,14 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
|
|
|
1266
1274
|
if (response) return response
|
|
1267
1275
|
}
|
|
1268
1276
|
|
|
1277
|
+
// Story 219: a server action, answered where the site is, through the routes' pipeline.
|
|
1278
|
+
if (pathname.startsWith(`${ACTIONS_PATH}/`)) {
|
|
1279
|
+
const action = config.role === 'api' ? undefined : siteActions.match(pathname)
|
|
1280
|
+
return action
|
|
1281
|
+
? siteRoutes.invoke(action, request, url, {})
|
|
1282
|
+
: new Response('Not Found', { status: 404, headers: { 'cache-control': 'no-store' } })
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1269
1285
|
// Islands (story 209): the loader, and each generation's browser code.
|
|
1270
1286
|
if (pathname === ISLAND_LOADER_PATH)
|
|
1271
1287
|
return new Response(ISLAND_LOADER_SCRIPT, {
|
|
@@ -2863,7 +2879,25 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
|
|
|
2863
2879
|
})
|
|
2864
2880
|
}
|
|
2865
2881
|
|
|
2882
|
+
/** A page, and an action's flash cleared once it has been read (story 219). */
|
|
2866
2883
|
async function renderPage(request: Request, pathname: string, host: string): Promise<Response> {
|
|
2884
|
+
const response = await renderPageOnce(request, pathname, host)
|
|
2885
|
+
if (!readCookie(request, ACTION_FLASH_COOKIE)) return response
|
|
2886
|
+
// Rebuilt rather than changed: a redirect's headers cannot be.
|
|
2887
|
+
const headers = new Headers(response.headers)
|
|
2888
|
+
headers.append('set-cookie', expireCookie(ACTION_FLASH_COOKIE, config.secureCookies))
|
|
2889
|
+
return new Response(response.body, {
|
|
2890
|
+
status: response.status,
|
|
2891
|
+
statusText: response.statusText,
|
|
2892
|
+
headers,
|
|
2893
|
+
})
|
|
2894
|
+
}
|
|
2895
|
+
|
|
2896
|
+
async function renderPageOnce(
|
|
2897
|
+
request: Request,
|
|
2898
|
+
pathname: string,
|
|
2899
|
+
host: string,
|
|
2900
|
+
): Promise<Response> {
|
|
2867
2901
|
const preview = await renderPreview(request, pathname, host)
|
|
2868
2902
|
// An `api` node renders for preview and nothing else. The backoffice opens a
|
|
2869
2903
|
// site URL to preview a draft, so the renderer has to be here; serving the
|
|
@@ -2880,18 +2914,22 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
|
|
|
2880
2914
|
// cleared, so a reload shows the page rather than the thank-you again.
|
|
2881
2915
|
const cookie = readCookie(request, FORM_FLASH_COOKIE)
|
|
2882
2916
|
const submission = cookie ? readFlash(formSecret, cookie) : undefined
|
|
2917
|
+
// What a server action answered the visitor with (story 219), read once as well.
|
|
2918
|
+
const actionCookie = readCookie(request, ACTION_FLASH_COOKIE)
|
|
2919
|
+
const actionFlash = siteActions.readFlash(actionCookie)
|
|
2883
2920
|
// A page that is not the same for everyone is never kept: a member's, a
|
|
2884
2921
|
// preview, a form's answer, or anything in a members-only branch — which a
|
|
2885
2922
|
// visitor sees as the login page, at the same address.
|
|
2886
2923
|
// Whether the page itself read anything personal, the member included, it
|
|
2887
2924
|
// says in its result (story 206).
|
|
2888
|
-
let personal = Boolean(preview || submission || cookie)
|
|
2925
|
+
let personal = Boolean(preview || submission || cookie || actionCookie)
|
|
2889
2926
|
const result =
|
|
2890
2927
|
preview ??
|
|
2891
2928
|
(await renderer.render(pathname, host, {
|
|
2892
2929
|
member,
|
|
2893
2930
|
antiforgery: session?.antiforgery,
|
|
2894
2931
|
submission,
|
|
2932
|
+
actions: { idOf: actionList.idOf, flash: actionFlash },
|
|
2895
2933
|
access: async (content) => {
|
|
2896
2934
|
if ((await members.decide(content, undefined)).status !== 'allowed') personal = true
|
|
2897
2935
|
return members.decide(content, member)
|