@crombolo/server 0.54.1 → 0.56.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 +6 -1
- package/src/bundle-install.ts +13 -3
- package/src/bundle-sections.ts +30 -4
- package/src/config.ts +21 -1
- package/src/content-events.ts +17 -1
- package/src/core.ts +32 -0
- package/src/index.ts +4 -0
- package/src/outbound-address.ts +182 -0
- package/src/owner-jobs.ts +7 -1
- package/src/remote.ts +8 -2
- package/src/routes.ts +13 -1
- package/src/schema.ts +6 -2
- package/src/server.ts +2 -2
- package/src/site-content-values.ts +97 -0
- package/src/site-content.ts +282 -0
- package/src/site-events.ts +65 -0
- package/src/site-services.ts +4 -0
- package/src/webhooks.ts +167 -17
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crombolo/server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.56.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.56.0",
|
|
35
|
+
"@crombolo/api-management": "0.56.0",
|
|
36
|
+
"@crombolo/auth": "0.56.0",
|
|
37
|
+
"@crombolo/backoffice-host": "0.56.0",
|
|
38
|
+
"@crombolo/common": "0.56.0",
|
|
39
|
+
"@crombolo/content": "0.56.0",
|
|
40
|
+
"@crombolo/contracts": "0.56.0",
|
|
41
|
+
"@crombolo/core": "0.56.0",
|
|
42
|
+
"@crombolo/data": "0.56.0",
|
|
43
|
+
"@crombolo/render": "0.56.0",
|
|
44
|
+
"@crombolo/schema": "0.56.0",
|
|
45
|
+
"@crombolo/transfer": "0.56.0",
|
|
46
46
|
"@logtape/logtape": "^2.3.8",
|
|
47
47
|
"@opentelemetry/api": "1.10.0",
|
|
48
48
|
"@opentelemetry/context-async-hooks": "3.0.0",
|
package/src/actions.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* flash cookie; a call asking for JSON with the result itself.
|
|
6
6
|
* docs/rendering.md, "Server actions".
|
|
7
7
|
*/
|
|
8
|
+
|
|
8
9
|
import {
|
|
9
10
|
ACTIONS_PATH,
|
|
10
11
|
type ActionState,
|
|
@@ -17,6 +18,7 @@ import {
|
|
|
17
18
|
} from '@crombolo/common'
|
|
18
19
|
import { readSignedFlash, writeSignedFlash } from './form-submit.ts'
|
|
19
20
|
import type { DeclaredRoute } from './routes.ts'
|
|
21
|
+
import { withSiteWrites } from './site-content.ts'
|
|
20
22
|
|
|
21
23
|
/** The cookie an action's result returns to the page in. */
|
|
22
24
|
export const ACTION_FLASH_COOKIE = 'crombolo-action'
|
|
@@ -142,7 +144,10 @@ export function actionRoutes(
|
|
|
142
144
|
const { params: _, ...actionContext } = context
|
|
143
145
|
let answer: Response | Ok<unknown> | Outcome | unknown
|
|
144
146
|
try {
|
|
145
|
-
|
|
147
|
+
// An action may change content (story 298), named for the audit.
|
|
148
|
+
answer = await withSiteWrites({ via: `action ${id}`, source: 'request' }, () =>
|
|
149
|
+
action(form, actionContext),
|
|
150
|
+
)
|
|
146
151
|
} catch (error) {
|
|
147
152
|
// `redirect()` and `notFound()` throw their outcome, as in a page.
|
|
148
153
|
if (!isOutcome(error)) throw error
|
package/src/bundle-install.ts
CHANGED
|
@@ -73,6 +73,7 @@ import {
|
|
|
73
73
|
changedFileSections,
|
|
74
74
|
keepDictionary,
|
|
75
75
|
keptDictionary,
|
|
76
|
+
migrationChanges,
|
|
76
77
|
planSections,
|
|
77
78
|
promoteStaged,
|
|
78
79
|
type RestoredFiles,
|
|
@@ -655,11 +656,20 @@ export async function installBundleContent(
|
|
|
655
656
|
)
|
|
656
657
|
// The code half (story 241): only when asked, only where installs happen here.
|
|
657
658
|
const code = effective.installCode ? codeChanges(planCode(config, carried)) : []
|
|
658
|
-
|
|
659
|
+
const installsElsewhere =
|
|
660
|
+
config.installsElsewhere?.message ??
|
|
661
|
+
"this site does not install code while it runs: add the bundle's code to the site and deploy it"
|
|
662
|
+
if (code.length > 0 && !config.runtimeInstalls) return refuse([installsElsewhere], backup)
|
|
663
|
+
// A bundle's value migrations are code too (story 300), unless they are the site's own.
|
|
664
|
+
const migrations =
|
|
665
|
+
input.provenance === 'local' || effective.withoutSchema ? [] : migrationChanges(config, carried)
|
|
666
|
+
if (migrations.length > 0 && (!effective.installCode || !config.runtimeInstalls))
|
|
659
667
|
return refuse(
|
|
660
668
|
[
|
|
661
|
-
|
|
662
|
-
|
|
669
|
+
effective.installCode
|
|
670
|
+
? installsElsewhere
|
|
671
|
+
: 'this bundle brings schema migrations, which are code: install its code to bring them',
|
|
672
|
+
...migrations.map((file) => file.path),
|
|
663
673
|
],
|
|
664
674
|
backup,
|
|
665
675
|
)
|
package/src/bundle-sections.ts
CHANGED
|
@@ -58,6 +58,11 @@ export interface SectionPlan {
|
|
|
58
58
|
* site: `none` when the bundle carries no schema.
|
|
59
59
|
*/
|
|
60
60
|
schema: { classification: string; findings: string[] } | undefined
|
|
61
|
+
/**
|
|
62
|
+
* The value migrations the bundle carries, `schema/migrations/<name>`: code,
|
|
63
|
+
* listed and never run by a check; they run only at install (story 300).
|
|
64
|
+
*/
|
|
65
|
+
migrations: string[]
|
|
61
66
|
/** Sections present in the bundle, for a caller that only wants to say so. */
|
|
62
67
|
sections: BundleSection[]
|
|
63
68
|
}
|
|
@@ -120,6 +125,21 @@ const FILE_SECTIONS: readonly BundleSection[] = ['components', 'styles', 'script
|
|
|
120
125
|
const withinSection = (path: string, section: BundleSection): string =>
|
|
121
126
|
path.slice(`${BUNDLE_SECTIONS[section]}/`.length)
|
|
122
127
|
|
|
128
|
+
/** A value migration a bundle carries: code, run when the schema syncs. */
|
|
129
|
+
export const isMigration = (path: string): boolean =>
|
|
130
|
+
/^migrations\/[^/]+\.(ts|js)$/.test(withinSection(path, 'schema'))
|
|
131
|
+
|
|
132
|
+
/** The value migrations a bundle would add or change here: code, as its `code/` is. */
|
|
133
|
+
export function migrationChanges(config: CromboloConfig, carried: CarriedSections): SectionFile[] {
|
|
134
|
+
return (carried.carries.schema ?? [])
|
|
135
|
+
.filter(isMigration)
|
|
136
|
+
.map((path) => {
|
|
137
|
+
const target = join(config.schemaDir, withinSection(path, 'schema'))
|
|
138
|
+
return { path, target, action: actionFor(target, sourceOf(carried, path)) }
|
|
139
|
+
})
|
|
140
|
+
.filter((file) => file.action !== 'unchanged')
|
|
141
|
+
}
|
|
142
|
+
|
|
123
143
|
/** Compared as bytes: a public file is an image as often as it is text. */
|
|
124
144
|
function actionFor(target: string, source: string): FileAction {
|
|
125
145
|
if (!existsSync(target)) return 'create'
|
|
@@ -185,6 +205,7 @@ export async function planSections(
|
|
|
185
205
|
return {
|
|
186
206
|
files,
|
|
187
207
|
dictionaryItems: (carried.carries.dictionary ?? []).length,
|
|
208
|
+
migrations: schemaPaths.filter(isMigration),
|
|
188
209
|
schema:
|
|
189
210
|
schemaPaths.length > 0
|
|
190
211
|
? await checkSchemaOverlay(db, config, carried, schemaPaths)
|
|
@@ -215,15 +236,20 @@ async function checkSchemaOverlay(
|
|
|
215
236
|
mkdirSync(dirname(target), { recursive: true })
|
|
216
237
|
writeFileSync(target, read(carried, path))
|
|
217
238
|
}
|
|
239
|
+
// The site's own migrations only: a check never imports a module the bundle brings.
|
|
218
240
|
const report = await checkSchemaDirectory(
|
|
219
241
|
db,
|
|
220
242
|
{ ...config, schemaDir: overlay },
|
|
221
243
|
{ nodeId: config.nodeId, revision: config.schemaRevision },
|
|
244
|
+
{ migrationsDir: config.schemaDir },
|
|
222
245
|
)
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
246
|
+
const carriedMigrations = paths.filter(isMigration).map((path) => withinSection(path, 'schema'))
|
|
247
|
+
const findings = report.outstanding.map((finding) => finding.message)
|
|
248
|
+
if (carriedMigrations.length > 0 && report.outstanding.length > 0)
|
|
249
|
+
findings.push(
|
|
250
|
+
`The bundle brings ${carriedMigrations.map((m) => `schema/${m}`).join(', ')}, which runs only at install, so this check could not count on it.`,
|
|
251
|
+
)
|
|
252
|
+
return { classification: report.classification, findings }
|
|
227
253
|
} finally {
|
|
228
254
|
rmSync(overlay, { recursive: true, force: true })
|
|
229
255
|
}
|
package/src/config.ts
CHANGED
|
@@ -30,6 +30,7 @@ import type { JobSchedule } from './owner-jobs.ts'
|
|
|
30
30
|
import type { ProvenancePolicy, SignaturePolicy } from './provenance.ts'
|
|
31
31
|
import type { SchemaStore } from './schema-store.ts'
|
|
32
32
|
import { setting } from './settings.ts'
|
|
33
|
+
import type { SiteEventHandler } from './site-events.ts'
|
|
33
34
|
import type { SiteDatabaseConfig, SiteQueryModules } from './site-queries.ts'
|
|
34
35
|
import type { TelemetryOptions } from './telemetry.ts'
|
|
35
36
|
|
|
@@ -523,6 +524,25 @@ export interface CromboloConfig {
|
|
|
523
524
|
jobs?: SiteQueryModules
|
|
524
525
|
/** When the site's jobs run by themselves: cron expressions in a timezone. */
|
|
525
526
|
schedules?: JobSchedule[]
|
|
527
|
+
/**
|
|
528
|
+
* `site().content` (story 298): the client id of the API user the site's code
|
|
529
|
+
* acts as when it writes pages. Its permissions bound what the code may do, and
|
|
530
|
+
* every change is audited as it. Without it, each write answers `forbidden`.
|
|
531
|
+
*/
|
|
532
|
+
content?: { actAs?: string }
|
|
533
|
+
/**
|
|
534
|
+
* Handlers for content events, by the names webhooks use (story 298), each run
|
|
535
|
+
* as a site job on a node that owns writes: `(event, { db, site, job })`.
|
|
536
|
+
* docs/rendering.md, "Content events".
|
|
537
|
+
*/
|
|
538
|
+
events?: Readonly<Record<string, SiteEventHandler>>
|
|
539
|
+
/**
|
|
540
|
+
* What a webhook may reach (story 301): the server variables a header's
|
|
541
|
+
* `env:NAME` may name besides `CROMBOLO_WEBHOOK_*`, and whether deliveries may
|
|
542
|
+
* go to loopback, private and link-local addresses: by default only on a
|
|
543
|
+
* development site. docs/webhooks.md.
|
|
544
|
+
*/
|
|
545
|
+
webhooks?: { headerVariables?: readonly string[]; allowPrivateAddresses?: boolean }
|
|
526
546
|
/**
|
|
527
547
|
* Package names this installation provides to every site it runs, rather
|
|
528
548
|
* than the site choosing them (story 177): a whole-site file leaves them out
|
|
@@ -1091,7 +1111,7 @@ export function describeDatabase(
|
|
|
1091
1111
|
}
|
|
1092
1112
|
}
|
|
1093
1113
|
|
|
1094
|
-
export const VERSION = '0.
|
|
1114
|
+
export const VERSION = '0.56.0'
|
|
1095
1115
|
|
|
1096
1116
|
/** A whole number of seconds from the environment; undefined when unset or not one. */
|
|
1097
1117
|
/** A positive number from a setting, else the default. */
|
package/src/content-events.ts
CHANGED
|
@@ -38,6 +38,14 @@ export interface ContentEventSinkOptions {
|
|
|
38
38
|
const subjectOf = (event: DocumentEvent): string | null =>
|
|
39
39
|
'key' in event ? event.key : 'parentKey' in event ? event.parentKey : null
|
|
40
40
|
|
|
41
|
+
/** The cultures an event was about, when it was about some. */
|
|
42
|
+
const culturesOf = (event: DocumentEvent): string[] | null =>
|
|
43
|
+
'cultures' in event && event.cultures ? [...event.cultures] : null
|
|
44
|
+
|
|
45
|
+
/** The site code a change came through (story 298), when it did. */
|
|
46
|
+
const viaOf = (actor: MediaActor): { via?: string } =>
|
|
47
|
+
actor.kind !== 'member' && actor.origin.via ? { via: actor.origin.via } : {}
|
|
48
|
+
|
|
41
49
|
/** Who made a change, as the outbox keeps it: enough to name them and leave them out. */
|
|
42
50
|
export const outboxActor = (actor: MediaActor) => {
|
|
43
51
|
const memberKey = actorMemberKey(actor)
|
|
@@ -70,7 +78,15 @@ export function createContentEventSink(options: ContentEventSinkOptions): EventS
|
|
|
70
78
|
const hook = webhookFor(event)
|
|
71
79
|
const change = notificationFor(event)
|
|
72
80
|
const webhook =
|
|
73
|
-
hook && options.webhooks
|
|
81
|
+
hook && options.webhooks
|
|
82
|
+
? {
|
|
83
|
+
...(await options.webhooks.factsFor(tx, hook)),
|
|
84
|
+
// For the site's own handlers (story 298): what it was about, and who did it.
|
|
85
|
+
cultures: culturesOf(event),
|
|
86
|
+
actor: { kind: actor.kind, name: actorName(actor), ...viaOf(actor) },
|
|
87
|
+
...viaOf(actor),
|
|
88
|
+
}
|
|
89
|
+
: undefined
|
|
74
90
|
const notification =
|
|
75
91
|
change && options.notifier
|
|
76
92
|
? await options.notifier.factsFor(
|
package/src/core.ts
CHANGED
|
@@ -78,6 +78,8 @@ import { createRedirectTracker } from './redirects.ts'
|
|
|
78
78
|
import { withRemoteMedia } from './remote-media.ts'
|
|
79
79
|
import { bootSchema, CacheInstructionPoller } from './schema.ts'
|
|
80
80
|
import { publishSchema, type SchemaStore, useSchemaStore } from './schema-store.ts'
|
|
81
|
+
import { apiUserPrincipal, createSiteContent } from './site-content.ts'
|
|
82
|
+
import { SITE_EVENT_JOB, siteEventJob, siteEventProblems } from './site-events.ts'
|
|
81
83
|
import { createSiteQueries, queryProblems } from './site-queries.ts'
|
|
82
84
|
import { createSiteServices } from './site-services.ts'
|
|
83
85
|
import { recordCacheLookup, startTelemetry, tracedDb, tracedEmail } from './telemetry.ts'
|
|
@@ -155,6 +157,7 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
|
|
|
155
157
|
...siteTablesProblems(config),
|
|
156
158
|
...queryProblems(config),
|
|
157
159
|
...siteJobProblems(config),
|
|
160
|
+
...siteEventProblems(config.events),
|
|
158
161
|
]
|
|
159
162
|
if (site.length > 0)
|
|
160
163
|
throw new Error(`The site's own tables cannot be used:\n- ${site.join('\n- ')}`)
|
|
@@ -361,7 +364,21 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
|
|
|
361
364
|
filesWritable: config.schemaWritable,
|
|
362
365
|
secretKey: config.secretKey,
|
|
363
366
|
bundles: config.bundles,
|
|
367
|
+
// A development site's receivers are on this machine, as the Next.js template's is.
|
|
368
|
+
outbound: {
|
|
369
|
+
...config.webhooks,
|
|
370
|
+
allowPrivateAddresses: config.webhooks?.allowPrivateAddresses ?? config.development,
|
|
371
|
+
},
|
|
364
372
|
isBundleOn: (bundleId) => bundleGrants.isOn(bundleId),
|
|
373
|
+
// The site's own handlers (story 298): each event queues the job that runs one.
|
|
374
|
+
siteEvents: {
|
|
375
|
+
handles: (alias) => typeof config.events?.[alias] === 'function',
|
|
376
|
+
deliver: async (event) => {
|
|
377
|
+
await jobRunner
|
|
378
|
+
.jobsFor(SITE_OWNER, `${event.alias} for ${event.key}`)
|
|
379
|
+
.enqueue(SITE_EVENT_JOB, event)
|
|
380
|
+
},
|
|
381
|
+
},
|
|
365
382
|
onFilesChanged: config.schemaStore
|
|
366
383
|
? async () => {
|
|
367
384
|
await publishSchema(config.schemaStore as SchemaStore, config.schemaDir)
|
|
@@ -550,9 +567,21 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
|
|
|
550
567
|
})
|
|
551
568
|
await poller.start(config.development ? 2_000 : 5_000)
|
|
552
569
|
|
|
570
|
+
// The API user `content.actAs` names must be there to act as (story 298).
|
|
571
|
+
if (config.content?.actAs && !(await apiUserPrincipal(db, config.content.actAs)))
|
|
572
|
+
throw new Error(
|
|
573
|
+
`The config's content.actAs names "${config.content.actAs}", which is no API user's client id.`,
|
|
574
|
+
)
|
|
553
575
|
const siteServicesFor = createSiteServices({
|
|
554
576
|
db,
|
|
555
577
|
cache,
|
|
578
|
+
content: createSiteContent({
|
|
579
|
+
db,
|
|
580
|
+
documents: operations.documents,
|
|
581
|
+
actAs: config.content?.actAs,
|
|
582
|
+
nodeState: schema.nodeState,
|
|
583
|
+
nodeId: schema.nodeId,
|
|
584
|
+
}),
|
|
556
585
|
queries: createSiteQueries({ queries: config.queries, chain: siteChains[0] }),
|
|
557
586
|
jobs: (queuedBy) => ({
|
|
558
587
|
enqueue: async (name, payload) =>
|
|
@@ -561,6 +590,9 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
|
|
|
561
590
|
}),
|
|
562
591
|
})
|
|
563
592
|
const siteJobs = siteJobHandlers(config.jobs)
|
|
593
|
+
// Each content event the site handles runs as a site job (story 298).
|
|
594
|
+
if (config.events && Object.keys(config.events).length > 0)
|
|
595
|
+
siteJobs.set(SITE_EVENT_JOB, siteEventJob(config.events))
|
|
564
596
|
/** Every owner with jobs: the site's given its tables and `site()` as a visitor; a bundle's, its capabilities for no caller. */
|
|
565
597
|
const jobOwners = (): JobOwner[] => [
|
|
566
598
|
// Core's own queued work: a large media branch's trash, move or delete (story 246).
|
package/src/index.ts
CHANGED
|
@@ -90,6 +90,7 @@ export * from './middleware.ts'
|
|
|
90
90
|
export * from './models-builder.ts'
|
|
91
91
|
export * from './no-nodes.ts'
|
|
92
92
|
export * from './oembed.ts'
|
|
93
|
+
export * from './outbound-address.ts'
|
|
93
94
|
export * from './owner-jobs.ts'
|
|
94
95
|
export * from './ports.ts'
|
|
95
96
|
export * from './provenance.ts'
|
|
@@ -112,7 +113,10 @@ export * from './server-events.ts'
|
|
|
112
113
|
export * from './settings.ts'
|
|
113
114
|
export * from './setup.ts'
|
|
114
115
|
export * from './site-assets.ts'
|
|
116
|
+
export { apiUserPrincipal, withSiteWrites } from './site-content.ts'
|
|
117
|
+
export * from './site-content-values.ts'
|
|
115
118
|
export * from './site-data.ts'
|
|
119
|
+
export * from './site-events.ts'
|
|
116
120
|
export * from './site-file.ts'
|
|
117
121
|
export * from './site-public.ts'
|
|
118
122
|
export * from './site-queries.ts'
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where a request a user set up may go (story 301): never this server's own
|
|
3
|
+
* network unless the site allows it, connected to the very address that was
|
|
4
|
+
* checked, so DNS cannot swap it between the check and the connection. And
|
|
5
|
+
* which server variables a header may name. Webhooks use it now; story 304
|
|
6
|
+
* brings the forms workflow and the identity provider test. docs/webhooks.md,
|
|
7
|
+
* "What a webhook may reach".
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** A request refused before anything was sent; trying again would be refused the same way. */
|
|
11
|
+
export class OutboundRefused extends Error {
|
|
12
|
+
override readonly name = 'OutboundRefused'
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface OutboundOptions {
|
|
16
|
+
/** Loopback, private and link-local addresses too: for development and an intranet. */
|
|
17
|
+
allowPrivateAddresses?: boolean
|
|
18
|
+
/** A hostname's addresses; `Bun.dns.lookup` unless a test says otherwise. */
|
|
19
|
+
lookup?: (hostname: string) => Promise<string[]>
|
|
20
|
+
fetch?: typeof fetch
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/
|
|
24
|
+
|
|
25
|
+
function ipv4Bytes(address: string): number[] | undefined {
|
|
26
|
+
const match = IPV4.exec(address)
|
|
27
|
+
if (!match) return undefined
|
|
28
|
+
const bytes = match.slice(1).map(Number)
|
|
29
|
+
return bytes.every((b) => b <= 255) ? bytes : undefined
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function ipv6Bytes(address: string): number[] | undefined {
|
|
33
|
+
if (!address.includes(':')) return undefined
|
|
34
|
+
let text = address.replace(/%.*$/, '')
|
|
35
|
+
const tail: number[] = []
|
|
36
|
+
const lastColon = text.lastIndexOf(':')
|
|
37
|
+
const embedded = ipv4Bytes(text.slice(lastColon + 1))
|
|
38
|
+
if (embedded) {
|
|
39
|
+
tail.push(...embedded)
|
|
40
|
+
text = `${text.slice(0, lastColon + 1)}0:0`
|
|
41
|
+
}
|
|
42
|
+
const halves = text.split('::')
|
|
43
|
+
if (halves.length > 2) return undefined
|
|
44
|
+
const groups = (part: string) => (part === '' ? [] : part.split(':'))
|
|
45
|
+
const head = groups(halves[0] ?? '')
|
|
46
|
+
const rest = halves.length === 2 ? groups(halves[1] ?? '') : []
|
|
47
|
+
const missing = 8 - head.length - rest.length
|
|
48
|
+
if (halves.length === 1 ? missing !== 0 : missing < 0) return undefined
|
|
49
|
+
const all = [...head, ...Array<string>(halves.length === 2 ? missing : 0).fill('0'), ...rest]
|
|
50
|
+
const bytes: number[] = []
|
|
51
|
+
for (const group of all) {
|
|
52
|
+
if (!/^[0-9a-f]{1,4}$/i.test(group)) return undefined
|
|
53
|
+
const value = Number.parseInt(group, 16)
|
|
54
|
+
bytes.push(value >> 8, value & 0xff)
|
|
55
|
+
}
|
|
56
|
+
if (tail.length > 0) bytes.splice(12, 4, ...tail)
|
|
57
|
+
return bytes
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Whether `bytes` starts with the first `bits` of `prefix`. */
|
|
61
|
+
function within(bytes: readonly number[], prefix: readonly number[], bits: number): boolean {
|
|
62
|
+
for (let i = 0; i < bits; i++) {
|
|
63
|
+
const mask = 0x80 >> (i % 8)
|
|
64
|
+
if (((bytes[i >> 3] ?? 0) & mask) !== ((prefix[i >> 3] ?? 0) & mask)) return false
|
|
65
|
+
}
|
|
66
|
+
return true
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const V4_REFUSED: Array<[number[], number, string]> = [
|
|
70
|
+
[[0, 0, 0, 0], 8, 'an unspecified address'],
|
|
71
|
+
[[10, 0, 0, 0], 8, 'a private address'],
|
|
72
|
+
[[100, 64, 0, 0], 10, 'a carrier-grade NAT address'],
|
|
73
|
+
[[127, 0, 0, 0], 8, 'a loopback address'],
|
|
74
|
+
[[169, 254, 0, 0], 16, 'a link-local address'],
|
|
75
|
+
[[172, 16, 0, 0], 12, 'a private address'],
|
|
76
|
+
[[192, 168, 0, 0], 16, 'a private address'],
|
|
77
|
+
[[224, 0, 0, 0], 4, 'a multicast address'],
|
|
78
|
+
[[240, 0, 0, 0], 4, 'a reserved or broadcast address'],
|
|
79
|
+
]
|
|
80
|
+
|
|
81
|
+
const V6_REFUSED: Array<[number[], number, string]> = [
|
|
82
|
+
[[0xfc], 7, 'a private address'],
|
|
83
|
+
[[0xfe, 0x80], 10, 'a link-local address'],
|
|
84
|
+
[[0xff], 8, 'a multicast address'],
|
|
85
|
+
]
|
|
86
|
+
|
|
87
|
+
/** Why an IP address is not one a request may go to, or undefined when it may. Pure. */
|
|
88
|
+
export function refusedAddress(address: string): string | undefined {
|
|
89
|
+
const v4 = ipv4Bytes(address)
|
|
90
|
+
if (v4) return V4_REFUSED.find(([prefix, bits]) => within(v4, prefix, bits))?.[2]
|
|
91
|
+
const v6 = ipv6Bytes(address)
|
|
92
|
+
if (!v6) return 'not an address'
|
|
93
|
+
if (v6.every((b) => b === 0)) return 'an unspecified address'
|
|
94
|
+
if (v6.slice(0, 15).every((b) => b === 0) && v6[15] === 1) return 'a loopback address'
|
|
95
|
+
// ::ffff:a.b.c.d, and the older ::a.b.c.d: an IPv4 address carried in IPv6.
|
|
96
|
+
const carried = (v6[10] === 0xff && v6[11] === 0xff) || (v6[10] === 0 && v6[11] === 0)
|
|
97
|
+
if (v6.slice(0, 10).every((b) => b === 0) && carried) return 'an IPv4 address mapped into IPv6'
|
|
98
|
+
return V6_REFUSED.find(([prefix, bits]) => within(v6, prefix, bits))?.[2]
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const isIp = (host: string) => Boolean(ipv4Bytes(host) || ipv6Bytes(host))
|
|
102
|
+
|
|
103
|
+
const defaultLookup = async (hostname: string) =>
|
|
104
|
+
(await Bun.dns.lookup(hostname)).map((entry) => entry.address)
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* The address a request to `url` connects to, once every address its host has
|
|
108
|
+
* is allowed; refused with the reason otherwise. Undefined when private
|
|
109
|
+
* addresses are allowed, so the request goes as it is.
|
|
110
|
+
*/
|
|
111
|
+
export async function checkedAddress(
|
|
112
|
+
url: URL,
|
|
113
|
+
options: OutboundOptions = {},
|
|
114
|
+
): Promise<string | undefined> {
|
|
115
|
+
if (url.protocol !== 'https:' && url.protocol !== 'http:')
|
|
116
|
+
throw new OutboundRefused(`${url.protocol} is not a web address; use http:// or https://.`)
|
|
117
|
+
if (options.allowPrivateAddresses) return undefined
|
|
118
|
+
const host = url.hostname.replace(/^\[|\]$/g, '')
|
|
119
|
+
const addresses = isIp(host) ? [host] : await (options.lookup ?? defaultLookup)(host)
|
|
120
|
+
if (addresses.length === 0) throw new OutboundRefused(`${host} has no address.`)
|
|
121
|
+
for (const address of addresses) {
|
|
122
|
+
const reason = refusedAddress(address)
|
|
123
|
+
if (reason)
|
|
124
|
+
throw new OutboundRefused(
|
|
125
|
+
`${host === address ? host : `${host} (${address})`} is ${reason}, which this site does not send to. The config's webhooks.allowPrivateAddresses allows it.`,
|
|
126
|
+
)
|
|
127
|
+
}
|
|
128
|
+
return addresses[0]
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* `fetch`, to the address that was checked: the hostname stays in the `Host`
|
|
133
|
+
* header and in TLS, so the certificate is still verified against it.
|
|
134
|
+
* Redirects are never followed; a 3xx is the receiver's answer.
|
|
135
|
+
*/
|
|
136
|
+
export async function pinnedFetch(
|
|
137
|
+
input: string | URL | Request,
|
|
138
|
+
init: RequestInit = {},
|
|
139
|
+
options: OutboundOptions = {},
|
|
140
|
+
): Promise<Response> {
|
|
141
|
+
const request = new Request(input, init)
|
|
142
|
+
const url = new URL(request.url)
|
|
143
|
+
const send = options.fetch ?? fetch
|
|
144
|
+
const address = await checkedAddress(url, options)
|
|
145
|
+
const base = {
|
|
146
|
+
method: request.method,
|
|
147
|
+
headers: new Headers(request.headers),
|
|
148
|
+
body: request.body,
|
|
149
|
+
signal: request.signal,
|
|
150
|
+
redirect: 'manual' as const,
|
|
151
|
+
}
|
|
152
|
+
if (!address) return send(url, base)
|
|
153
|
+
const target = new URL(url)
|
|
154
|
+
const host = url.hostname.replace(/^\[|\]$/g, '')
|
|
155
|
+
target.hostname = address.includes(':') ? `[${address}]` : address
|
|
156
|
+
base.headers.set('host', url.host)
|
|
157
|
+
return send(target, {
|
|
158
|
+
...base,
|
|
159
|
+
...(url.protocol === 'https:' && !isIp(host) ? { tls: { serverName: host } } : {}),
|
|
160
|
+
} as RequestInit)
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** The variables a header may name, besides those the config lists. */
|
|
164
|
+
export const HEADER_VARIABLE_PREFIX = 'CROMBOLO_WEBHOOK_'
|
|
165
|
+
|
|
166
|
+
/** Settings made to be sent: the Next.js front end's shared secret (docs/delivery-api.md). */
|
|
167
|
+
const MADE_TO_SEND = new Set(['CROMBOLO_REVALIDATE_SECRET'])
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Why a header may not send the server variable `variable`, or undefined when
|
|
171
|
+
* it may: one the config lists, one starting `CROMBOLO_WEBHOOK_`, or a setting
|
|
172
|
+
* made to be sent. Never any other `CROMBOLO_` setting, listed or not. Pure.
|
|
173
|
+
*/
|
|
174
|
+
export function headerVariableProblem(
|
|
175
|
+
header: string,
|
|
176
|
+
variable: string,
|
|
177
|
+
allowed: readonly string[] = [],
|
|
178
|
+
): string | undefined {
|
|
179
|
+
if (variable.startsWith(HEADER_VARIABLE_PREFIX) || MADE_TO_SEND.has(variable)) return undefined
|
|
180
|
+
if (allowed.includes(variable) && !variable.startsWith('CROMBOLO_')) return undefined
|
|
181
|
+
return `The header "${header}" names ${variable}, which a webhook may not send. List it in the config's webhooks.headerVariables, or name a variable starting ${HEADER_VARIABLE_PREFIX}.`
|
|
182
|
+
}
|
package/src/owner-jobs.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* its owner's public route sees, and nothing acts as the site.
|
|
6
6
|
* docs/rendering.md, "Background jobs"; docs/bundles.md, "Jobs".
|
|
7
7
|
*/
|
|
8
|
+
|
|
8
9
|
import {
|
|
9
10
|
type Db,
|
|
10
11
|
type JobProgress,
|
|
@@ -14,6 +15,7 @@ import {
|
|
|
14
15
|
} from '@crombolo/data'
|
|
15
16
|
import { type Cron, isTimezone, nextOccurrence, parseCron } from './cron.ts'
|
|
16
17
|
import { logger } from './logging.ts'
|
|
18
|
+
import { withSiteWrites } from './site-content.ts'
|
|
17
19
|
import { inSpan, recordJob } from './telemetry.ts'
|
|
18
20
|
|
|
19
21
|
/**
|
|
@@ -283,7 +285,11 @@ export function createJobRunner(options: {
|
|
|
283
285
|
`job ${job.owner}/${job.name}`,
|
|
284
286
|
{ ...attributes, 'crombolo.job.attempt': job.attempts },
|
|
285
287
|
async () => {
|
|
286
|
-
|
|
288
|
+
const run = () => handler(job.payload, { ...owner.context(), job: info })
|
|
289
|
+
// The site's jobs may change content (story 298), named for the audit.
|
|
290
|
+
await (owner.id === 'site'
|
|
291
|
+
? withSiteWrites({ via: `job ${job.name}`, source: 'job' }, run)
|
|
292
|
+
: run())
|
|
287
293
|
},
|
|
288
294
|
)
|
|
289
295
|
await jobs.succeed(job.id)
|
package/src/remote.ts
CHANGED
|
@@ -49,7 +49,12 @@ import {
|
|
|
49
49
|
readBundle,
|
|
50
50
|
revertSections,
|
|
51
51
|
} from './bundle-install.ts'
|
|
52
|
-
import {
|
|
52
|
+
import {
|
|
53
|
+
carriesSections,
|
|
54
|
+
migrationChanges,
|
|
55
|
+
type SectionFile,
|
|
56
|
+
swappedSections,
|
|
57
|
+
} from './bundle-sections.ts'
|
|
53
58
|
import { type CromboloConfig, REMOTE_ACCESS_LEVELS, type RemoteAccess } from './config.ts'
|
|
54
59
|
import { answerContentQuery, contentQueryScope } from './content-query.ts'
|
|
55
60
|
import { mediaStoreFor } from './media-files.ts'
|
|
@@ -699,7 +704,8 @@ export function createRemote(options: RemoteOptions): Remote {
|
|
|
699
704
|
try {
|
|
700
705
|
const carried = readBundle(dir, config.siteDir).carried
|
|
701
706
|
structural = carriesSections(carried)
|
|
702
|
-
code
|
|
707
|
+
// A bundle's value migrations are code too (story 300).
|
|
708
|
+
code = [...codeChanges(planCode(config, carried)), ...migrationChanges(config, carried)]
|
|
703
709
|
} catch (error) {
|
|
704
710
|
return problem(400, {
|
|
705
711
|
code: 'not-a-bundle',
|
package/src/routes.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* response — a `Result`'s value as JSON, an outcome as its status, an error as
|
|
6
6
|
* problem+json or the status page. docs/rendering.md, "Route handlers".
|
|
7
7
|
*/
|
|
8
|
+
|
|
8
9
|
import { type CorsPolicy, isPreflight, preflightResponse, withCors } from '@crombolo/api-delivery'
|
|
9
10
|
import {
|
|
10
11
|
type CookieOptions,
|
|
@@ -19,6 +20,7 @@ import {
|
|
|
19
20
|
import { ANTIFORGERY_HEADER, type PageOutcome, requestScope } from '@crombolo/render'
|
|
20
21
|
import { isSitePath, requestCookies } from './middleware.ts'
|
|
21
22
|
import { RateLimiter } from './rate-limit.ts'
|
|
23
|
+
import { withSiteWrites } from './site-content.ts'
|
|
22
24
|
|
|
23
25
|
/** A member as a route sees them: their key, for limits, and their group names. */
|
|
24
26
|
export interface RouteMember {
|
|
@@ -51,6 +53,9 @@ export interface RouteDeps<Member extends RouteMember> {
|
|
|
51
53
|
}
|
|
52
54
|
|
|
53
55
|
/** A route with what it needs added to its context, such as a bundle's capabilities. */
|
|
56
|
+
/** Who the site's own routes are declared by; a bundle's say its id. */
|
|
57
|
+
export const SITE_ROUTE_OWNER = 'the site'
|
|
58
|
+
|
|
54
59
|
export interface DeclaredRoute {
|
|
55
60
|
route: SiteRoute
|
|
56
61
|
/** Who declared it, for errors and logs: the site, or a bundle by id. */
|
|
@@ -342,7 +347,14 @@ export function createRoutes<Member extends RouteMember>(
|
|
|
342
347
|
let response: Response
|
|
343
348
|
try {
|
|
344
349
|
const work = Promise.resolve().then(() =>
|
|
345
|
-
requestScope({ headers: request.headers }, site, () =>
|
|
350
|
+
requestScope({ headers: request.headers }, site, () =>
|
|
351
|
+
// The site's own routes may change content (story 298), named for the audit.
|
|
352
|
+
entry.owner === SITE_ROUTE_OWNER
|
|
353
|
+
? withSiteWrites({ via: `route ${method} ${route.path}`, source: 'request' }, () =>
|
|
354
|
+
handler(request, context as never),
|
|
355
|
+
)
|
|
356
|
+
: handler(request, context as never),
|
|
357
|
+
),
|
|
346
358
|
)
|
|
347
359
|
work.catch(() => {})
|
|
348
360
|
const answer = await Promise.race([work, overran])
|
package/src/schema.ts
CHANGED
|
@@ -76,7 +76,11 @@ export async function checkSchemaDirectory(
|
|
|
76
76
|
db: Db,
|
|
77
77
|
config: CromboloConfig,
|
|
78
78
|
node: { nodeId: string; revision: string },
|
|
79
|
-
options: {
|
|
79
|
+
options: {
|
|
80
|
+
set?: Record<string, unknown>
|
|
81
|
+
/** Where the value migrations are loaded from: the schema's own, unless a check says otherwise. */
|
|
82
|
+
migrationsDir?: string
|
|
83
|
+
} = {},
|
|
80
84
|
): Promise<CheckReport> {
|
|
81
85
|
const loaded = loadSchemaDirectory(config.schemaDir, { formTypes: formTypesFor(config) })
|
|
82
86
|
return runCheck(
|
|
@@ -86,7 +90,7 @@ export async function checkSchemaDirectory(
|
|
|
86
90
|
{
|
|
87
91
|
...syncOptionsFor(config),
|
|
88
92
|
set: options.set,
|
|
89
|
-
migrations: await loadValueMigrations(config.schemaDir),
|
|
93
|
+
migrations: await loadValueMigrations(options.migrationsDir ?? config.schemaDir),
|
|
90
94
|
backOfficePath: config.backOfficePath,
|
|
91
95
|
},
|
|
92
96
|
)
|
package/src/server.ts
CHANGED
|
@@ -274,7 +274,7 @@ import {
|
|
|
274
274
|
import { CORE_JOB_OWNER, type JobRunner } from './owner-jobs.ts'
|
|
275
275
|
import { callerAddress } from './rate-limit.ts'
|
|
276
276
|
import { syncConfiguredRedirects } from './redirects.ts'
|
|
277
|
-
import { createRoutes, type DeclaredRoute, siteRouteProblems } from './routes.ts'
|
|
277
|
+
import { createRoutes, type DeclaredRoute, SITE_ROUTE_OWNER, siteRouteProblems } from './routes.ts'
|
|
278
278
|
import { componentAliasesIn, importSchema, type SchemaBoot, watchSchema } from './schema.ts'
|
|
279
279
|
import { publishSchema, type SchemaStore } from './schema-store.ts'
|
|
280
280
|
import { createSeoHost, originOf, publicOrigin } from './seo.ts'
|
|
@@ -1198,7 +1198,7 @@ export async function createServer(
|
|
|
1198
1198
|
// routes too.
|
|
1199
1199
|
const declaredRoutes: DeclaredRoute[] = [
|
|
1200
1200
|
...(config.routes ?? []).map(
|
|
1201
|
-
(route): DeclaredRoute => ({ route: route as SiteRoute, owner:
|
|
1201
|
+
(route): DeclaredRoute => ({ route: route as SiteRoute, owner: SITE_ROUTE_OWNER }),
|
|
1202
1202
|
),
|
|
1203
1203
|
...(bundles?.siteRoutes() ?? []),
|
|
1204
1204
|
]
|