@crombolo/server 0.55.0 → 0.57.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 +16 -13
- package/src/actions.ts +6 -1
- package/src/adapters/bundles.ts +72 -6
- package/src/adapters/health.ts +30 -1
- package/src/bundle-admin.ts +246 -23
- package/src/bundle-api.ts +299 -0
- package/src/bundle-build.ts +4 -3
- package/src/bundle-grants.ts +133 -18
- package/src/bundle-install.ts +140 -11
- package/src/bundle-sections.ts +49 -4
- package/src/bundles.ts +87 -7
- package/src/component-templates-api.ts +27 -6
- package/src/components.ts +7 -0
- package/src/config.ts +56 -3
- package/src/content-events.ts +17 -1
- package/src/core.ts +219 -15
- package/src/created-extension.ts +101 -0
- package/src/extension-components.ts +157 -0
- package/src/extension-discovery.ts +180 -0
- package/src/extension-process.ts +854 -0
- package/src/extension-sql.ts +85 -0
- package/src/index.ts +21 -0
- package/src/marketplace.ts +182 -54
- package/src/outbound-address.ts +182 -0
- package/src/owner-jobs.ts +7 -1
- package/src/ports.ts +8 -0
- package/src/provenance.ts +181 -15
- package/src/remote.ts +62 -10
- package/src/routes.ts +13 -1
- package/src/schema.ts +37 -6
- package/src/seed/compile.ts +4 -2
- package/src/seed/export.ts +1 -1
- package/src/seed/values.ts +3 -3
- package/src/seo.ts +13 -5
- package/src/server.ts +192 -45
- package/src/settings.ts +12 -4
- package/src/signing-keys.ts +155 -0
- package/src/site-content-values.ts +97 -0
- package/src/site-content.ts +292 -0
- package/src/site-events.ts +65 -0
- package/src/site-file.ts +20 -6
- package/src/site-public.ts +1 -1
- package/src/site-sections.ts +1 -1
- package/src/site-services.ts +4 -0
- package/src/site-trust.ts +238 -0
- package/src/transfer-dashboard.ts +6 -0
- package/src/trusted-signers-admin.ts +132 -0
- package/src/webhooks.ts +182 -17
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `site().content`'s values (story 298): by alias, `{ title: 'Hello' }`, and by
|
|
3
|
+
* culture for a property that varies, `{ title: { 'en-GB': 'Hello' } }`, to and
|
|
4
|
+
* from the stored shape the document operations take. Pure.
|
|
5
|
+
*/
|
|
6
|
+
import type { DocumentAggregate, DocumentValue, FieldError } from '@crombolo/core'
|
|
7
|
+
|
|
8
|
+
/** What the conversion needs of a property: its alias, and whether it varies by culture. */
|
|
9
|
+
export interface ValueProperty {
|
|
10
|
+
alias: string
|
|
11
|
+
variesByCulture: boolean
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
15
|
+
typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Site code's values as the operations store them, laid over what the page
|
|
19
|
+
* already holds; or, when a value cannot be placed, the fields that say why.
|
|
20
|
+
*
|
|
21
|
+
* - A property that does not vary takes its value as it is.
|
|
22
|
+
* - One that varies takes a culture-keyed object, or a plain value with `culture`.
|
|
23
|
+
*/
|
|
24
|
+
export function toDocumentValues(
|
|
25
|
+
given: Readonly<Record<string, unknown>>,
|
|
26
|
+
properties: readonly ValueProperty[],
|
|
27
|
+
options: { culture?: string; existing?: readonly DocumentValue[] } = {},
|
|
28
|
+
): { values: DocumentValue[] } | { errors: FieldError[] } {
|
|
29
|
+
const byAlias = new Map(properties.map((p) => [p.alias, p]))
|
|
30
|
+
const errors: FieldError[] = []
|
|
31
|
+
const set = new Map<string, DocumentValue>()
|
|
32
|
+
const keyOf = (alias: string, culture: string | null) => `${alias}|${culture ?? ''}`
|
|
33
|
+
for (const value of options.existing ?? []) {
|
|
34
|
+
if (value.segment) continue
|
|
35
|
+
set.set(keyOf(value.alias, value.culture), value)
|
|
36
|
+
}
|
|
37
|
+
for (const [alias, value] of Object.entries(given)) {
|
|
38
|
+
const property = byAlias.get(alias)
|
|
39
|
+
if (!property) {
|
|
40
|
+
errors.push({ field: alias, message: `The content type has no property "${alias}".` })
|
|
41
|
+
continue
|
|
42
|
+
}
|
|
43
|
+
if (!property.variesByCulture) {
|
|
44
|
+
set.set(keyOf(alias, null), { alias, culture: null, segment: null, value })
|
|
45
|
+
continue
|
|
46
|
+
}
|
|
47
|
+
if (
|
|
48
|
+
isRecord(value) &&
|
|
49
|
+
Object.keys(value).every((key) => /^[a-z]{2,3}(-[A-Za-z0-9]+)*$/.test(key))
|
|
50
|
+
) {
|
|
51
|
+
for (const [culture, inCulture] of Object.entries(value))
|
|
52
|
+
set.set(keyOf(alias, culture), { alias, culture, segment: null, value: inCulture })
|
|
53
|
+
continue
|
|
54
|
+
}
|
|
55
|
+
if (!options.culture) {
|
|
56
|
+
errors.push({
|
|
57
|
+
field: alias,
|
|
58
|
+
message: `"${alias}" varies by culture: give it by culture, { "en-GB": … }, or say which culture.`,
|
|
59
|
+
})
|
|
60
|
+
continue
|
|
61
|
+
}
|
|
62
|
+
set.set(keyOf(alias, options.culture), {
|
|
63
|
+
alias,
|
|
64
|
+
culture: options.culture,
|
|
65
|
+
segment: null,
|
|
66
|
+
value,
|
|
67
|
+
})
|
|
68
|
+
}
|
|
69
|
+
return errors.length > 0 ? { errors } : { values: [...set.values()] }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** A page's stored values by alias, by culture where its property varies. */
|
|
73
|
+
export function fromDocumentValues(
|
|
74
|
+
values: readonly DocumentValue[],
|
|
75
|
+
properties: readonly ValueProperty[],
|
|
76
|
+
): Record<string, unknown> {
|
|
77
|
+
const varies = new Map(properties.map((p) => [p.alias, p.variesByCulture]))
|
|
78
|
+
const out: Record<string, unknown> = {}
|
|
79
|
+
for (const value of values) {
|
|
80
|
+
if (value.segment) continue
|
|
81
|
+
if (varies.get(value.alias) && value.culture) {
|
|
82
|
+
const byCulture = (out[value.alias] ?? {}) as Record<string, unknown>
|
|
83
|
+
byCulture[value.culture] = value.value
|
|
84
|
+
out[value.alias] = byCulture
|
|
85
|
+
} else if (!value.culture) out[value.alias] = value.value
|
|
86
|
+
}
|
|
87
|
+
return out
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** A page's name: one, or one per culture where its type varies. */
|
|
91
|
+
export function documentName(
|
|
92
|
+
document: Pick<DocumentAggregate, 'variants'>,
|
|
93
|
+
): string | Record<string, string> {
|
|
94
|
+
const named = document.variants.filter((v) => !v.segment)
|
|
95
|
+
if (named.length === 1 && !named[0]?.culture) return named[0]?.name ?? ''
|
|
96
|
+
return Object.fromEntries(named.map((v) => [v.culture ?? '', v.name]))
|
|
97
|
+
}
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `site().content` (story 298): the site's own code reading and writing pages,
|
|
3
|
+
* through the document operations the Management API uses, as the API user the
|
|
4
|
+
* config's `content.actAs` names. Its permissions, start nodes, languages and the
|
|
5
|
+
* approval workflows bound what this may do, and the audit names the route,
|
|
6
|
+
* action, job or event that made each change. docs/rendering.md, "Writing content".
|
|
7
|
+
*/
|
|
8
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
9
|
+
import type { Principal } from '@crombolo/api-management'
|
|
10
|
+
import { canReadDocument } from '@crombolo/api-management'
|
|
11
|
+
import { AuthStore } from '@crombolo/auth'
|
|
12
|
+
import type { DocumentOperations, Refusal } from '@crombolo/content'
|
|
13
|
+
import { userActor } from '@crombolo/content'
|
|
14
|
+
import { normaliseUuid, Outcome, ok, toSectionAliases } from '@crombolo/core'
|
|
15
|
+
import {
|
|
16
|
+
ContentTypeRepository,
|
|
17
|
+
type Db,
|
|
18
|
+
DocumentRepository,
|
|
19
|
+
type DocumentRepositoryOptions,
|
|
20
|
+
UserRepository,
|
|
21
|
+
} from '@crombolo/data'
|
|
22
|
+
import type { SiteContent, SiteDocument } from '@crombolo/render'
|
|
23
|
+
import { createNodeLookup, loadAccess } from './access.ts'
|
|
24
|
+
import {
|
|
25
|
+
documentName,
|
|
26
|
+
fromDocumentValues,
|
|
27
|
+
toDocumentValues,
|
|
28
|
+
type ValueProperty,
|
|
29
|
+
} from './site-content-values.ts'
|
|
30
|
+
|
|
31
|
+
/** Where site code may write from, and what it is: `route POST /api/listings`, `job imports.nightly`. */
|
|
32
|
+
interface WriteScope {
|
|
33
|
+
via: string
|
|
34
|
+
source: 'request' | 'job'
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const writes = new AsyncLocalStorage<WriteScope>()
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Runs site code that may write content: a route, an action, a job or an event
|
|
41
|
+
* handler, named for the audit. A page render runs outside any, and only reads.
|
|
42
|
+
*/
|
|
43
|
+
export function withSiteWrites<T>(scope: WriteScope, run: () => T): T {
|
|
44
|
+
return writes.run(scope, run)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
|
48
|
+
|
|
49
|
+
export interface SiteContentDeps {
|
|
50
|
+
db: Db
|
|
51
|
+
documents: DocumentOperations
|
|
52
|
+
/** The node's schema state, as every document read on it is given. */
|
|
53
|
+
nodeState?: DocumentRepositoryOptions['nodeState']
|
|
54
|
+
nodeId?: string
|
|
55
|
+
/** The API user's client id, from `content.actAs`. */
|
|
56
|
+
actAs?: string
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The API user a client id names, as the Management API would see it signed in; undefined when none. */
|
|
60
|
+
export async function apiUserPrincipal(db: Db, clientId: string): Promise<Principal | undefined> {
|
|
61
|
+
const owner = await new UserRepository(db).clientCredentialOwner(clientId)
|
|
62
|
+
if (!owner) return undefined
|
|
63
|
+
return userPrincipal(db, owner.userId)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** A back-office user, by key, as the Management API would see them signed in; undefined when none (story 308). */
|
|
67
|
+
export async function userPrincipalByKey(db: Db, key: string): Promise<Principal | undefined> {
|
|
68
|
+
const user = await new UserRepository(db).byKey(key)
|
|
69
|
+
return user ? userPrincipal(db, user.id) : undefined
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function userPrincipal(db: Db, userId: number): Promise<Principal | undefined> {
|
|
73
|
+
const store = new AuthStore(db)
|
|
74
|
+
const user = await store.findUserById(userId)
|
|
75
|
+
if (!user || user.isLockedOut || !user.isApproved) return undefined
|
|
76
|
+
const authorization = await store.loadAuthorization(user.id)
|
|
77
|
+
return {
|
|
78
|
+
id: user.key,
|
|
79
|
+
userName: user.login,
|
|
80
|
+
name: user.userName,
|
|
81
|
+
email: user.email,
|
|
82
|
+
isAdmin: authorization.isAdmin,
|
|
83
|
+
languageIsoCode: user.language ?? undefined,
|
|
84
|
+
avatarUrls: [],
|
|
85
|
+
allowedSections: toSectionAliases(authorization.appAliases),
|
|
86
|
+
permissions: authorization.permissions,
|
|
87
|
+
groupKeys: authorization.groupKeys,
|
|
88
|
+
hasAccessToAllLanguages: authorization.hasAccessToAllLanguages,
|
|
89
|
+
...(await loadAccess(db, user.id)),
|
|
90
|
+
} as unknown as Principal
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** An operation's refusal as an `Outcome` site code matches on. */
|
|
94
|
+
function outcomeOf(refusal: Refusal) {
|
|
95
|
+
switch (refusal.kind) {
|
|
96
|
+
case 'notFound':
|
|
97
|
+
return Outcome.notFound(refusal.reason)
|
|
98
|
+
case 'forbidden':
|
|
99
|
+
return Outcome.forbidden(refusal.reason)
|
|
100
|
+
case 'needsApproval':
|
|
101
|
+
return Outcome.badRequest(`This needs approval before it is published: ${refusal.reason}`)
|
|
102
|
+
case 'validation':
|
|
103
|
+
case 'blocked':
|
|
104
|
+
if (refusal.kind === 'blocked' && !refusal.errors?.length)
|
|
105
|
+
return Outcome.badRequest(refusal.reason)
|
|
106
|
+
return Outcome.unprocessableContent(
|
|
107
|
+
(refusal.errors ?? []).flatMap((error) =>
|
|
108
|
+
error.messages.map((message) => ({
|
|
109
|
+
field: error.culture ? `${error.alias}.${error.culture}` : error.alias,
|
|
110
|
+
message,
|
|
111
|
+
})),
|
|
112
|
+
),
|
|
113
|
+
refusal.reason,
|
|
114
|
+
)
|
|
115
|
+
default:
|
|
116
|
+
return Outcome.badRequest(refusal.reason)
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function createSiteContent(deps: SiteContentDeps): SiteContent {
|
|
121
|
+
const { db, documents } = deps
|
|
122
|
+
const repo = new DocumentRepository(db, { nodeState: deps.nodeState, nodeId: deps.nodeId })
|
|
123
|
+
const types = new ContentTypeRepository(db)
|
|
124
|
+
const nodes = createNodeLookup(db)
|
|
125
|
+
|
|
126
|
+
const notActing = () =>
|
|
127
|
+
Outcome.forbidden(
|
|
128
|
+
"This site's code cannot change content: name an API user in the config's content.actAs.",
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
const principal = async () => (deps.actAs ? apiUserPrincipal(db, deps.actAs) : undefined)
|
|
132
|
+
|
|
133
|
+
/** Who a write is, inside a route, an action, a job or an event; a refusal elsewhere. */
|
|
134
|
+
const writer = async () => {
|
|
135
|
+
const scope = writes.getStore()
|
|
136
|
+
if (!scope)
|
|
137
|
+
return Outcome.forbidden(
|
|
138
|
+
'A page render reads content and never changes it: write from an action, a route, a job or an event.',
|
|
139
|
+
)
|
|
140
|
+
const who = await principal()
|
|
141
|
+
if (!who) return notActing()
|
|
142
|
+
return userActor(who, { via: scope.via, source: scope.source } as never)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const properties = async (typeKey: string): Promise<ValueProperty[]> =>
|
|
146
|
+
(await types.resolveProperties(typeKey)).map((p) => ({
|
|
147
|
+
alias: p.alias,
|
|
148
|
+
variesByCulture: p.variesByCulture,
|
|
149
|
+
}))
|
|
150
|
+
|
|
151
|
+
const read = async (key: string): Promise<SiteDocument | undefined> => {
|
|
152
|
+
const document = await repo.byKey(key)
|
|
153
|
+
if (!document || document.isTrashed) return undefined
|
|
154
|
+
return {
|
|
155
|
+
key: document.key,
|
|
156
|
+
contentType: document.contentTypeAlias,
|
|
157
|
+
parent: document.parentKey,
|
|
158
|
+
name: documentName(document),
|
|
159
|
+
values: fromDocumentValues(document.values, await properties(document.contentTypeKey)),
|
|
160
|
+
published: document.published,
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const done = (key: string) => ok({ key })
|
|
165
|
+
|
|
166
|
+
return {
|
|
167
|
+
async get(key) {
|
|
168
|
+
const who = await principal()
|
|
169
|
+
if (!who) return notActing()
|
|
170
|
+
if (!UUID.test(key) || !(await canReadDocument(who, key, nodes))) return Outcome.notFound()
|
|
171
|
+
const found = await read(key)
|
|
172
|
+
return found ? ok(found) : Outcome.notFound()
|
|
173
|
+
},
|
|
174
|
+
|
|
175
|
+
async children(key) {
|
|
176
|
+
const who = await principal()
|
|
177
|
+
if (!who) return notActing()
|
|
178
|
+
if (key !== null && (!UUID.test(key) || !(await canReadDocument(who, key, nodes))))
|
|
179
|
+
return Outcome.notFound()
|
|
180
|
+
const page = await repo.children(key, 0, 10_000)
|
|
181
|
+
const out: SiteDocument[] = []
|
|
182
|
+
for (const row of page.items) {
|
|
183
|
+
const childKey = normaliseUuid(row.key)
|
|
184
|
+
if (!(await canReadDocument(who, childKey, nodes))) continue
|
|
185
|
+
const found = await read(childKey)
|
|
186
|
+
if (found) out.push(found)
|
|
187
|
+
}
|
|
188
|
+
return ok(out)
|
|
189
|
+
},
|
|
190
|
+
|
|
191
|
+
async create(input) {
|
|
192
|
+
const actor = await writer()
|
|
193
|
+
if (actor instanceof Outcome) return actor
|
|
194
|
+
const type = await types.byAlias(input.contentType)
|
|
195
|
+
if (!type)
|
|
196
|
+
return Outcome.unprocessableContent(
|
|
197
|
+
[{ field: 'contentType', message: `There is no content type "${input.contentType}".` }],
|
|
198
|
+
`There is no content type "${input.contentType}".`,
|
|
199
|
+
)
|
|
200
|
+
const converted = toDocumentValues(input.values ?? {}, await properties(type.key), {
|
|
201
|
+
culture: input.culture,
|
|
202
|
+
})
|
|
203
|
+
if ('errors' in converted)
|
|
204
|
+
return Outcome.unprocessableContent(converted.errors, 'Some values could not be placed.')
|
|
205
|
+
const key = crypto.randomUUID()
|
|
206
|
+
const result = await documents.create(actor, {
|
|
207
|
+
key,
|
|
208
|
+
contentTypeKey: type.key,
|
|
209
|
+
componentKey: type.defaultComponentKey,
|
|
210
|
+
parentKey: input.parent,
|
|
211
|
+
values: converted.values,
|
|
212
|
+
variants: [
|
|
213
|
+
{
|
|
214
|
+
culture: type.variesByCulture ? (input.culture ?? null) : null,
|
|
215
|
+
segment: null,
|
|
216
|
+
name: input.name,
|
|
217
|
+
},
|
|
218
|
+
],
|
|
219
|
+
})
|
|
220
|
+
return result.ok ? done(result.key) : outcomeOf(result)
|
|
221
|
+
},
|
|
222
|
+
|
|
223
|
+
async update(key, change) {
|
|
224
|
+
const actor = await writer()
|
|
225
|
+
if (actor instanceof Outcome) return actor
|
|
226
|
+
const existing = UUID.test(key) ? await repo.byKey(key) : undefined
|
|
227
|
+
if (!existing) return Outcome.notFound()
|
|
228
|
+
const converted = toDocumentValues(
|
|
229
|
+
change.values ?? {},
|
|
230
|
+
await properties(existing.contentTypeKey),
|
|
231
|
+
{ culture: change.culture, existing: existing.values },
|
|
232
|
+
)
|
|
233
|
+
if ('errors' in converted)
|
|
234
|
+
return Outcome.unprocessableContent(converted.errors, 'Some values could not be placed.')
|
|
235
|
+
const variants = existing.variants
|
|
236
|
+
.filter((v) => !v.segment)
|
|
237
|
+
.map((v) => ({
|
|
238
|
+
culture: v.culture,
|
|
239
|
+
segment: null,
|
|
240
|
+
name:
|
|
241
|
+
change.name !== undefined && (change.culture ?? null) === (v.culture ?? null)
|
|
242
|
+
? change.name
|
|
243
|
+
: v.name,
|
|
244
|
+
}))
|
|
245
|
+
if (
|
|
246
|
+
change.name !== undefined &&
|
|
247
|
+
change.culture &&
|
|
248
|
+
!variants.some((v) => v.culture === change.culture)
|
|
249
|
+
)
|
|
250
|
+
variants.push({ culture: change.culture, segment: null, name: change.name })
|
|
251
|
+
const result = await documents.save(
|
|
252
|
+
actor,
|
|
253
|
+
existing.key,
|
|
254
|
+
{
|
|
255
|
+
key: existing.key,
|
|
256
|
+
contentTypeKey: existing.contentTypeKey,
|
|
257
|
+
componentKey: existing.componentKey,
|
|
258
|
+
parentKey: existing.parentKey,
|
|
259
|
+
values: converted.values,
|
|
260
|
+
variants,
|
|
261
|
+
},
|
|
262
|
+
{ expectedRevision: existing.revision },
|
|
263
|
+
)
|
|
264
|
+
return result.ok ? done(existing.key) : outcomeOf(result)
|
|
265
|
+
},
|
|
266
|
+
|
|
267
|
+
async publish(key, options = {}) {
|
|
268
|
+
const actor = await writer()
|
|
269
|
+
if (actor instanceof Outcome) return actor
|
|
270
|
+
if (!UUID.test(key)) return Outcome.notFound()
|
|
271
|
+
const cultures = options.cultures ?? null
|
|
272
|
+
const result = await documents.publish(actor, key, { cultures })
|
|
273
|
+
return result.ok ? done(key) : outcomeOf(result)
|
|
274
|
+
},
|
|
275
|
+
|
|
276
|
+
async unpublish(key, options = {}) {
|
|
277
|
+
const actor = await writer()
|
|
278
|
+
if (actor instanceof Outcome) return actor
|
|
279
|
+
if (!UUID.test(key)) return Outcome.notFound()
|
|
280
|
+
const result = await documents.unpublish(actor, key, options.cultures ?? null)
|
|
281
|
+
return result.ok ? done(key) : outcomeOf(result)
|
|
282
|
+
},
|
|
283
|
+
|
|
284
|
+
async delete(key) {
|
|
285
|
+
const actor = await writer()
|
|
286
|
+
if (actor instanceof Outcome) return actor
|
|
287
|
+
if (!UUID.test(key)) return Outcome.notFound()
|
|
288
|
+
const result = await documents.trash(actor, key)
|
|
289
|
+
return result.ok ? done(key) : outcomeOf(result)
|
|
290
|
+
},
|
|
291
|
+
}
|
|
292
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The site's own content event handlers (story 298): the config's `events`, by
|
|
3
|
+
* the names webhooks use. The outbox dispatcher queues a site job per event
|
|
4
|
+
* (`SITE_EVENT_JOB`), so a handler runs on a node that owns writes, retried as
|
|
5
|
+
* jobs are, with the site's tables and `site()`. docs/rendering.md, "Content events".
|
|
6
|
+
*/
|
|
7
|
+
import { WEBHOOK_EVENT_ALIASES } from '@crombolo/api-management/domain'
|
|
8
|
+
import type { SiteContentEvent, SiteServices } from '@crombolo/render'
|
|
9
|
+
import type { JobHandler, JobInfo } from './owner-jobs.ts'
|
|
10
|
+
import { withSiteWrites } from './site-content.ts'
|
|
11
|
+
|
|
12
|
+
/** What a site's event handler is given besides the event. */
|
|
13
|
+
export interface SiteEventContext {
|
|
14
|
+
/** The site's own tables, when it has any. */
|
|
15
|
+
db?: unknown
|
|
16
|
+
site: SiteServices
|
|
17
|
+
/** The job the event runs as: its id, its attempt, and how to report progress. */
|
|
18
|
+
job: JobInfo
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export type SiteEventHandler = (event: SiteContentEvent, context: SiteEventContext) => unknown
|
|
22
|
+
|
|
23
|
+
/** The site job each content event runs as. Not a `module.export`, so no site job can take it. */
|
|
24
|
+
export const SITE_EVENT_JOB = 'crombolo:event'
|
|
25
|
+
|
|
26
|
+
/** Why the config's `events` cannot be used. Pure. */
|
|
27
|
+
export function siteEventProblems(events: Readonly<Record<string, unknown>> | undefined): string[] {
|
|
28
|
+
const problems: string[] = []
|
|
29
|
+
for (const [alias, handler] of Object.entries(events ?? {})) {
|
|
30
|
+
if (!WEBHOOK_EVENT_ALIASES.has(alias))
|
|
31
|
+
problems.push(`The site handles "${alias}", which is not an event this site raises.`)
|
|
32
|
+
if (typeof handler !== 'function')
|
|
33
|
+
problems.push(`The site's handler for "${alias}" is not a function.`)
|
|
34
|
+
}
|
|
35
|
+
return problems
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** What a handler's own write is said to come from, so its event does not call it again. */
|
|
39
|
+
export const eventVia = (alias: string, key: string): string => `event ${alias} ${key}`
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Whether an event comes from a site event handler's write to the very page the
|
|
43
|
+
* handler was called for: the site does not hear of that, so a handler that
|
|
44
|
+
* updates its page is not called again for its own change. Pure.
|
|
45
|
+
*/
|
|
46
|
+
export function isOwnChange(event: { key: string; via?: string }): boolean {
|
|
47
|
+
const own = /^event \S+ (\S+)$/.exec(event.via ?? '')
|
|
48
|
+
return own !== null && (own[1] ?? '').toLowerCase() === event.key.toLowerCase()
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The job that calls the site's handler for an event, as the event names the write. */
|
|
52
|
+
export function siteEventJob(events: Readonly<Record<string, SiteEventHandler>>): JobHandler {
|
|
53
|
+
return async (payload: SiteContentEvent, context: SiteEventContext) => {
|
|
54
|
+
const handler = events[payload.alias]
|
|
55
|
+
// A handler taken out of the config since: nothing to call, and nothing to retry.
|
|
56
|
+
if (!handler) return
|
|
57
|
+
await withSiteWrites({ via: eventVia(payload.alias, payload.key), source: 'job' }, () =>
|
|
58
|
+
handler(payload, {
|
|
59
|
+
...(context.db !== undefined ? { db: context.db } : {}),
|
|
60
|
+
site: context.site,
|
|
61
|
+
job: context.job,
|
|
62
|
+
}),
|
|
63
|
+
)
|
|
64
|
+
}
|
|
65
|
+
}
|
package/src/site-file.ts
CHANGED
|
@@ -23,10 +23,12 @@ import {
|
|
|
23
23
|
MANIFEST_FILE,
|
|
24
24
|
mediaPath,
|
|
25
25
|
newSeal,
|
|
26
|
+
packageIdentity,
|
|
26
27
|
packageNameFor,
|
|
27
28
|
planStreamedBundle,
|
|
28
29
|
sanitise,
|
|
29
30
|
sealBytes,
|
|
31
|
+
updateTrailer,
|
|
30
32
|
writeManifest,
|
|
31
33
|
} from '@crombolo/transfer'
|
|
32
34
|
import { createComponentsPort, createFileSystemPort } from './adapters/file-system.ts'
|
|
@@ -34,9 +36,11 @@ import { createTemplateFileStore } from './adapters/template-files.ts'
|
|
|
34
36
|
import { type CromboloConfig, VERSION } from './config.ts'
|
|
35
37
|
import { mediaStoreFor } from './media-files.ts'
|
|
36
38
|
import { type StoredFile, streamOf } from './media-store.ts'
|
|
39
|
+
import { signPathWithKey } from './provenance.ts'
|
|
37
40
|
import { readSiteData } from './site-data.ts'
|
|
38
41
|
import { publicSources } from './site-public.ts'
|
|
39
42
|
import { siteSections } from './site-sections.ts'
|
|
43
|
+
import { siteSigningKey } from './site-trust.ts'
|
|
40
44
|
import { TarballWriter } from './tar.ts'
|
|
41
45
|
|
|
42
46
|
export interface SiteExportOptions {
|
|
@@ -245,6 +249,7 @@ export async function exportSite(
|
|
|
245
249
|
seal,
|
|
246
250
|
content: options.sealContent ? 'sealed' : 'open',
|
|
247
251
|
public: publicFiles,
|
|
252
|
+
bundleType: 'site',
|
|
248
253
|
},
|
|
249
254
|
)
|
|
250
255
|
|
|
@@ -256,7 +261,13 @@ export async function exportSite(
|
|
|
256
261
|
label: site.manifest.label,
|
|
257
262
|
private: true,
|
|
258
263
|
peerRange: `>=${VERSION}`,
|
|
264
|
+
bundleType: 'site',
|
|
259
265
|
}
|
|
266
|
+
const pkg = bundlePackageJson(info, [
|
|
267
|
+
...planned.files.map((file) => file.path),
|
|
268
|
+
...planned.blobs.map(mediaPath),
|
|
269
|
+
...publicFiles.map((file) => file.path),
|
|
270
|
+
])
|
|
260
271
|
|
|
261
272
|
const partial = `${options.out}.partial`
|
|
262
273
|
const writer = TarballWriter.create(partial)
|
|
@@ -299,16 +310,19 @@ export async function exportSite(
|
|
|
299
310
|
// Outside the bundle's hash: `public.json`, inside it, holds each file's own.
|
|
300
311
|
for (const file of publicFiles)
|
|
301
312
|
await writer.addStream(file.path, file.size, Bun.file(file.source).stream())
|
|
313
|
+
// The manifest and the package's identity close the hash, as `bundleIntegrity` has it.
|
|
314
|
+
updateTrailer(hasher, {
|
|
315
|
+
manifest: writeManifest({ ...planned.manifest, integrity: '' }),
|
|
316
|
+
packageIdentity: packageIdentity(pkg),
|
|
317
|
+
})
|
|
302
318
|
const manifest = { ...planned.manifest, integrity: `sha256-${hasher.digest('hex')}` }
|
|
303
319
|
await writer.add(MANIFEST_FILE, encoder.encode(writeManifest(manifest)))
|
|
304
|
-
await writer.add(
|
|
305
|
-
'package.json',
|
|
306
|
-
encoder.encode(
|
|
307
|
-
`${JSON.stringify(bundlePackageJson(info, [...paths, ...publicFiles.map((file) => file.path)]), null, 2)}\n`,
|
|
308
|
-
),
|
|
309
|
-
)
|
|
320
|
+
await writer.add('package.json', encoder.encode(`${JSON.stringify(pkg, null, 2)}\n`))
|
|
310
321
|
await writer.close()
|
|
311
322
|
await rename(partial, options.out)
|
|
323
|
+
// Signed with this site's key, so a site that trusts it knows it came from here (story 316).
|
|
324
|
+
const key = await siteSigningKey(db, config)
|
|
325
|
+
if (key) await signPathWithKey(options.out, key)
|
|
312
326
|
} catch (error) {
|
|
313
327
|
await writer.abort()
|
|
314
328
|
await rm(partial, { force: true })
|
package/src/site-public.ts
CHANGED
|
@@ -14,7 +14,7 @@ import { isSitePath } from './middleware.ts'
|
|
|
14
14
|
/** Where a CLI finds out what a server is: never a site's to answer. */
|
|
15
15
|
export const REMOTE_DISCOVERY_PATH = '/.well-known/crombolo-remote'
|
|
16
16
|
|
|
17
|
-
/** Above this, `
|
|
17
|
+
/** Above this, `site build` says what is making the bundle heavy. */
|
|
18
18
|
export const PUBLIC_WARNING_BYTES = 100 * 1024 ** 2
|
|
19
19
|
|
|
20
20
|
const IMMUTABLE = 'public, max-age=31536000, immutable'
|
package/src/site-sections.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The sections a bundle carries beyond its content — schema, components,
|
|
3
3
|
* styles, scripts and the dictionary — gathered from a site. One place, so the
|
|
4
|
-
* backoffice's Packages builder (picked items) and `crombolo export
|
|
4
|
+
* backoffice's Packages builder (picked items) and `crombolo site export`
|
|
5
5
|
* (everything) compose a bundle the same way. `docs/bundles.md`.
|
|
6
6
|
*/
|
|
7
7
|
import { readdir, readFile } from 'node:fs/promises'
|
package/src/site-services.ts
CHANGED
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
type PublishedCache,
|
|
20
20
|
type PublishedMedia,
|
|
21
21
|
type RequestMember,
|
|
22
|
+
type SiteContent,
|
|
22
23
|
type SiteJobs,
|
|
23
24
|
type SiteMembers,
|
|
24
25
|
type SiteQueries,
|
|
@@ -37,6 +38,8 @@ export interface SiteServicesDeps {
|
|
|
37
38
|
queries?: (
|
|
38
39
|
member: RequestMember | undefined | (() => Promise<RequestMember | undefined>),
|
|
39
40
|
) => SiteQueries
|
|
41
|
+
/** `site().content` (story 298): one for every caller, acting as the configured API user. */
|
|
42
|
+
content?: SiteContent
|
|
40
43
|
}
|
|
41
44
|
|
|
42
45
|
/** Builds `site()`'s services for one request; undefined `member` is a visitor or a previewing editor. */
|
|
@@ -110,6 +113,7 @@ export function createSiteServices(deps: SiteServicesDeps) {
|
|
|
110
113
|
return who ? `member ${who.username}` : 'a visitor'
|
|
111
114
|
}) ?? unavailableServices<SiteJobs>('jobs'),
|
|
112
115
|
members: unavailableServices<SiteMembers>('members'),
|
|
116
|
+
content: deps.content ?? unavailableServices<SiteContent>('content'),
|
|
113
117
|
}
|
|
114
118
|
return () => services
|
|
115
119
|
}
|