@crombolo/server 0.21.0 → 0.23.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 -12
- package/src/adapters/documents.ts +7 -2
- package/src/adapters/elements.ts +87 -5
- package/src/approvals.ts +36 -26
- package/src/config.ts +59 -3
- package/src/content-events.ts +76 -0
- package/src/content-operations.ts +80 -0
- package/src/domains.ts +51 -0
- package/src/form-workflows.ts +36 -0
- package/src/index.ts +2 -0
- package/src/jobs.ts +26 -1
- package/src/ports.ts +78 -22
- package/src/preview-tokens.ts +95 -0
- package/src/remote.ts +6 -0
- package/src/seo.ts +101 -7
- package/src/server.ts +209 -20
- package/src/settings.ts +48 -0
package/src/domains.ts
CHANGED
|
@@ -16,9 +16,11 @@ import { existsSync, readFileSync } from 'node:fs'
|
|
|
16
16
|
import { join } from 'node:path'
|
|
17
17
|
import { ObjectTypes } from '@crombolo/core'
|
|
18
18
|
import {
|
|
19
|
+
appendCacheInstruction,
|
|
19
20
|
type Db,
|
|
20
21
|
DocumentRepository,
|
|
21
22
|
DomainRepository,
|
|
23
|
+
type DomainRow,
|
|
22
24
|
describeRefFailure,
|
|
23
25
|
LanguageRepository,
|
|
24
26
|
NodeRepository,
|
|
@@ -307,6 +309,7 @@ export async function syncDomainsFile(
|
|
|
307
309
|
else byNode.set(declaration.node, [declaration])
|
|
308
310
|
}
|
|
309
311
|
|
|
312
|
+
const boundBefore = bindingsOf(await domains.all())
|
|
310
313
|
const kept = new Set<number>()
|
|
311
314
|
const namedBy = new Map<number, string>()
|
|
312
315
|
for (const [node, declarations] of byNode) {
|
|
@@ -368,9 +371,24 @@ export async function syncDomainsFile(
|
|
|
368
371
|
removed += before.domains.length + (before.defaultIsoCode ? 1 : 0)
|
|
369
372
|
}
|
|
370
373
|
|
|
374
|
+
// Hostnames are part of every node's published cache, and this runs from the
|
|
375
|
+
// CLI as often as from a server. Unsigned, so every node rebuilds its routing,
|
|
376
|
+
// the one this ran in included; only when something changed, so a boot that
|
|
377
|
+
// re-applies the same file tells nobody anything.
|
|
378
|
+
if (bindingsOf(await domains.all()) !== boundBefore)
|
|
379
|
+
await appendCacheInstruction(db, { kind: 'content', payload: { domains: true } })
|
|
380
|
+
|
|
371
381
|
return { action: 'applied', applied, removed, problems }
|
|
372
382
|
}
|
|
373
383
|
|
|
384
|
+
/** The bindings as a comparable string: page, hostname and culture, in a stable order. */
|
|
385
|
+
function bindingsOf(rows: readonly DomainRow[]): string {
|
|
386
|
+
return rows
|
|
387
|
+
.map((row) => `${row.nodeId}|${row.domainName}|${row.isoCode ?? ''}|${row.isWildcard}`)
|
|
388
|
+
.sort()
|
|
389
|
+
.join('\n')
|
|
390
|
+
}
|
|
391
|
+
|
|
374
392
|
function describeSetFailure(result: { status: string; domainName?: string; isoCode?: string }) {
|
|
375
393
|
switch (result.status) {
|
|
376
394
|
case 'invalidLanguage':
|
|
@@ -383,3 +401,36 @@ function describeSetFailure(result: { status: string; domainName?: string; isoCo
|
|
|
383
401
|
return result.status
|
|
384
402
|
}
|
|
385
403
|
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* After a page's hostnames were saved in the backoffice: a site that keeps
|
|
407
|
+
* `domains.toml` keeps them in the file, since the next boot converges onto it
|
|
408
|
+
* and a change saved only in the database would be undone. Only this page's
|
|
409
|
+
* entries are rewritten, so `${VAR}` in the others survives. Answers the file it
|
|
410
|
+
* wrote, or undefined for a site without one.
|
|
411
|
+
*/
|
|
412
|
+
export async function writeDomainsFor(
|
|
413
|
+
db: Db,
|
|
414
|
+
siteDir: string | undefined,
|
|
415
|
+
node: NodeRow,
|
|
416
|
+
assignment: {
|
|
417
|
+
defaultIsoCode: string | null
|
|
418
|
+
domains: Array<{ domainName: string; isoCode: string }>
|
|
419
|
+
},
|
|
420
|
+
): Promise<string | undefined> {
|
|
421
|
+
const declarations = siteDir ? readDomainsFile(siteDir) : undefined
|
|
422
|
+
if (!siteDir || !declarations) return undefined
|
|
423
|
+
await writeDomains(
|
|
424
|
+
siteDir,
|
|
425
|
+
replaceNodeDeclarations(
|
|
426
|
+
declarations.declarations,
|
|
427
|
+
await nodeReferenceFor(db, declarations.declarations, node),
|
|
428
|
+
assignment.domains.map((domain) => ({
|
|
429
|
+
host: domain.domainName,
|
|
430
|
+
culture: domain.isoCode || undefined,
|
|
431
|
+
})),
|
|
432
|
+
assignment.defaultIsoCode ?? undefined,
|
|
433
|
+
),
|
|
434
|
+
)
|
|
435
|
+
return DOMAINS_FILE
|
|
436
|
+
}
|
package/src/form-workflows.ts
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
* why), and Slack is `sendToUrl` with a webhook URL rather than a type of its
|
|
12
12
|
* own.
|
|
13
13
|
*/
|
|
14
|
+
import { type DocumentOperations, systemActor } from '@crombolo/content'
|
|
14
15
|
import {
|
|
15
16
|
allFormFields,
|
|
16
17
|
type FormValueToStore,
|
|
@@ -66,6 +67,11 @@ export interface WorkflowDeps {
|
|
|
66
67
|
nodeId?: string
|
|
67
68
|
/** Told when a workflow published something, so the cache is dropped. */
|
|
68
69
|
onContentChanged?: () => void
|
|
70
|
+
/**
|
|
71
|
+
* Saves a submission as a page as the site (story 170), recorded and announced
|
|
72
|
+
* as any page made in the backoffice is. Without them it writes directly.
|
|
73
|
+
*/
|
|
74
|
+
operations?: DocumentOperations
|
|
69
75
|
/** The workflow types wired bundles add, by type. */
|
|
70
76
|
bundleWorkflows?: ReadonlyMap<string, FormWorkflowTypeDefinition>
|
|
71
77
|
/** Renders a `template` component to HTML; absent, a workflow naming one cannot send. */
|
|
@@ -358,6 +364,36 @@ async function saveAsContent(
|
|
|
358
364
|
(nameField ? firstValue(context.values, nameField) : '') ||
|
|
359
365
|
`${context.form.name} ${new Date().toISOString().slice(0, 16).replace('T', ' ')}`
|
|
360
366
|
|
|
367
|
+
const input = {
|
|
368
|
+
key: crypto.randomUUID(),
|
|
369
|
+
contentTypeKey: type.key,
|
|
370
|
+
componentKey: null,
|
|
371
|
+
// `root` or nothing both mean the top of the tree.
|
|
372
|
+
parentKey: parent && parent !== 'root' ? parent : null,
|
|
373
|
+
values: Object.entries(map).map(([fieldAlias, propertyAlias]) => ({
|
|
374
|
+
alias: propertyAlias,
|
|
375
|
+
culture: null,
|
|
376
|
+
segment: null,
|
|
377
|
+
value: firstValue(context.values, fieldAlias),
|
|
378
|
+
})),
|
|
379
|
+
variants: [{ culture: null, segment: null, name }],
|
|
380
|
+
}
|
|
381
|
+
if (deps.operations) {
|
|
382
|
+
const actor = systemActor(`The form "${context.form.name}"`, {
|
|
383
|
+
note: `from a submission to "${context.form.name}"`,
|
|
384
|
+
})
|
|
385
|
+
const result =
|
|
386
|
+
settings.publish === true
|
|
387
|
+
? await deps.operations.createAndPublish(actor, input, null)
|
|
388
|
+
: await deps.operations.create(actor, input)
|
|
389
|
+
if (result.ok) return { ok: true, detail: result.key }
|
|
390
|
+
// A node behind the schema, or a parent not yet published, resolves on its own: worth retrying.
|
|
391
|
+
return {
|
|
392
|
+
ok: false,
|
|
393
|
+
retry: result.kind === 'conflict' || result.kind === 'blocked',
|
|
394
|
+
error: result.reason,
|
|
395
|
+
}
|
|
396
|
+
}
|
|
361
397
|
const documents = new DocumentRepository(deps.db, {
|
|
362
398
|
nodeState: deps.nodeState,
|
|
363
399
|
nodeId: deps.nodeId,
|
package/src/index.ts
CHANGED
|
@@ -25,7 +25,9 @@ export * from './bundles.ts'
|
|
|
25
25
|
export * from './busy.ts'
|
|
26
26
|
export * from './components.ts'
|
|
27
27
|
export * from './config.ts'
|
|
28
|
+
export * from './content-events.ts'
|
|
28
29
|
export * from './content-notifications.ts'
|
|
30
|
+
export * from './content-operations.ts'
|
|
29
31
|
export * from './content-type-udt.ts'
|
|
30
32
|
export * from './database.ts'
|
|
31
33
|
export * from './diagnostics.ts'
|
package/src/jobs.ts
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* it runs once.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
+
import { type DocumentOperations, systemActor } from '@crombolo/content'
|
|
11
12
|
import type { NodeSchemaState } from '@crombolo/data'
|
|
12
13
|
import {
|
|
13
14
|
AuditLog,
|
|
@@ -64,6 +65,11 @@ export interface JobsOptions {
|
|
|
64
65
|
notifier?: ContentNotifier
|
|
65
66
|
/** Told what scheduled publishing did, for the approval requests waiting on it (story 029). */
|
|
66
67
|
approvals?: Pick<Approvals, 'scheduleFired' | 'sweepScheduled'>
|
|
68
|
+
/**
|
|
69
|
+
* Publishes what a schedule says, as the site (story 170): recorded, tracked and
|
|
70
|
+
* announced as an editor's publish is. Without them the job writes directly.
|
|
71
|
+
*/
|
|
72
|
+
operations?: DocumentOperations
|
|
67
73
|
}
|
|
68
74
|
|
|
69
75
|
export interface ScheduledRun {
|
|
@@ -110,8 +116,25 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
|
|
|
110
116
|
for (const due of await documents.dueSchedules(now)) {
|
|
111
117
|
if (!(await documents.claimSchedule(due.id))) continue
|
|
112
118
|
const cultures = due.culture ? [due.culture] : null
|
|
119
|
+
const release = due.action === 'Release'
|
|
120
|
+
if (options.operations) {
|
|
121
|
+
const actor = systemActor('The schedule', {
|
|
122
|
+
note: `scheduled${due.culture ? ` (${due.culture})` : ''}`,
|
|
123
|
+
})
|
|
124
|
+
const result = release
|
|
125
|
+
? await options.operations.publish(actor, due.key, { cultures })
|
|
126
|
+
: await options.operations.unpublish(actor, due.key, cultures)
|
|
127
|
+
if (result.ok) (release ? run.published : run.unpublished).push(due.key)
|
|
128
|
+
else run.failed.push({ key: due.key, reason: result.reason })
|
|
129
|
+
await options.approvals?.scheduleFired(
|
|
130
|
+
due.key,
|
|
131
|
+
due.culture,
|
|
132
|
+
due.action,
|
|
133
|
+
result.ok ? { ok: true } : { ok: false, reason: result.reason },
|
|
134
|
+
)
|
|
135
|
+
continue
|
|
136
|
+
}
|
|
113
137
|
try {
|
|
114
|
-
const release = due.action === 'Release'
|
|
115
138
|
const changed = release
|
|
116
139
|
? await documents.publish(due.key, cultures)
|
|
117
140
|
: await documents.unpublish(due.key, cultures)
|
|
@@ -137,6 +160,8 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
|
|
|
137
160
|
}
|
|
138
161
|
}
|
|
139
162
|
await options.approvals?.sweepScheduled(now.getTime())
|
|
163
|
+
// The operations announced and refreshed what they did themselves.
|
|
164
|
+
if (options.operations) return run
|
|
140
165
|
if (run.published.length + run.unpublished.length > 0) options.cache.invalidate()
|
|
141
166
|
for (const key of run.published) {
|
|
142
167
|
await options.webhooks?.raise({ alias: 'Umbraco.ContentPublish', key })
|
package/src/ports.ts
CHANGED
|
@@ -16,12 +16,21 @@ import type {
|
|
|
16
16
|
} from '@crombolo/api-management'
|
|
17
17
|
import { AuthStore, expireCookie, serializeCookie } from '@crombolo/auth'
|
|
18
18
|
import {
|
|
19
|
+
APP_PREVIEW_MANIFEST_ID,
|
|
19
20
|
ASSISTANT_MANIFEST_ID,
|
|
20
21
|
type BackOfficePaths,
|
|
21
22
|
collectManifests,
|
|
22
23
|
type ExtensionRegistry,
|
|
23
24
|
toResponseModels,
|
|
24
25
|
} from '@crombolo/backoffice-host'
|
|
26
|
+
import {
|
|
27
|
+
type ApprovalsGate,
|
|
28
|
+
type ContentPrincipal,
|
|
29
|
+
createDocumentOperations,
|
|
30
|
+
type DocumentOperations,
|
|
31
|
+
type EventSink,
|
|
32
|
+
SILENT,
|
|
33
|
+
} from '@crombolo/content'
|
|
25
34
|
import {
|
|
26
35
|
CORE_SECTION_ALIASES,
|
|
27
36
|
DEFAULT_UPLOAD_SETTINGS,
|
|
@@ -71,12 +80,13 @@ import { createTemplateFileStore } from './adapters/template-files.ts'
|
|
|
71
80
|
import { createTemplateQueryPort } from './adapters/template-query.ts'
|
|
72
81
|
import { avatarUrls, createUserPorts } from './adapters/users.ts'
|
|
73
82
|
import { createWebhookPort } from './adapters/webhooks.ts'
|
|
74
|
-
import { createApprovals } from './approvals.ts'
|
|
83
|
+
import { type Approvals, createApprovals } from './approvals.ts'
|
|
75
84
|
import { COMPONENT_SNIPPETS } from './component-snippets.ts'
|
|
76
85
|
import { type CromboloConfig, type UserLinkSender, VERSION } from './config.ts'
|
|
77
86
|
import type { ContentNotifier } from './content-notifications.ts'
|
|
87
|
+
import { writeDomainsFor } from './domains.ts'
|
|
78
88
|
import { type EmailPort, resolveEmailPort } from './email.ts'
|
|
79
|
-
import { createFileIntake } from './file-intake.ts'
|
|
89
|
+
import { createFileIntake, TemporaryFileMissingError } from './file-intake.ts'
|
|
80
90
|
import { formTypesFor } from './form-types.ts'
|
|
81
91
|
import { createLogViewerPort } from './log-viewer.ts'
|
|
82
92
|
import { logger } from './logging.ts'
|
|
@@ -127,12 +137,13 @@ function createServerPort(config: CromboloConfig, canSendUserLinks: boolean): Se
|
|
|
127
137
|
/** Umbraco's preview cookie; with a signed-in editor it turns on draft rendering. */
|
|
128
138
|
export const PREVIEW_COOKIE = 'UMB_PREVIEW'
|
|
129
139
|
|
|
130
|
-
function createPreviewPort(config: CromboloConfig): PreviewPort {
|
|
140
|
+
function createPreviewPort(config: CromboloConfig, inApp?: PreviewPort['inApp']): PreviewPort {
|
|
131
141
|
return {
|
|
132
142
|
enter: () => [
|
|
133
143
|
serializeCookie({ name: PREVIEW_COOKIE, value: 'preview', secure: config.secureCookies }),
|
|
134
144
|
],
|
|
135
145
|
exit: () => [expireCookie(PREVIEW_COOKIE, config.secureCookies)],
|
|
146
|
+
inApp,
|
|
136
147
|
}
|
|
137
148
|
}
|
|
138
149
|
|
|
@@ -385,10 +396,14 @@ export interface DepsOptions {
|
|
|
385
396
|
extensions: ExtensionRegistry
|
|
386
397
|
/** Omitted only by tests that exercise the contract without a database. */
|
|
387
398
|
db?: Db
|
|
399
|
+
/** Where document operations announce what they did; nothing hears them when absent. */
|
|
400
|
+
contentEvents?: EventSink
|
|
388
401
|
/** The site's webhooks, shared with the delivery job and the event source. */
|
|
389
402
|
webhooks?: WebhookService
|
|
390
403
|
/** Required alongside `db` to serve documents, which invalidate the cache. */
|
|
391
404
|
cache?: PublishedCache
|
|
405
|
+
/** Where a page previews in the site's app (story 053); unset, Preview is Umbraco's own. */
|
|
406
|
+
previewInApp?: PreviewPort['inApp']
|
|
392
407
|
schema?: SchemaBoot
|
|
393
408
|
/** Uploaded files; one is made on `config.mediaDir` when omitted. */
|
|
394
409
|
mediaFiles?: MediaFileStore
|
|
@@ -454,14 +469,13 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
|
|
|
454
469
|
const sendUserLink = resolveUserLinkSender(options.config, email)
|
|
455
470
|
const deps: ManagementApiDeps = {
|
|
456
471
|
server: createServerPort(options.config, Boolean(sendUserLink)),
|
|
457
|
-
preview: createPreviewPort(options.config),
|
|
472
|
+
preview: createPreviewPort(options.config, options.previewInApp),
|
|
458
473
|
// An unconfigured assistant contributes no extension, so the backoffice has
|
|
459
|
-
// no drawer, no button and nothing to load.
|
|
460
|
-
manifests: createManifestPort(
|
|
461
|
-
options.
|
|
462
|
-
options.
|
|
463
|
-
|
|
464
|
-
),
|
|
474
|
+
// no drawer, no button and nothing to load; Preview in app likewise.
|
|
475
|
+
manifests: createManifestPort(options.paths, options.extensions, [
|
|
476
|
+
...(options.config.assistant ? [] : [ASSISTANT_MANIFEST_ID]),
|
|
477
|
+
...(options.previewInApp ? [] : [APP_PREVIEW_MANIFEST_ID]),
|
|
478
|
+
]),
|
|
465
479
|
localization: createLocalizationPort(
|
|
466
480
|
options.db,
|
|
467
481
|
options.db ? createSchemaFileWriter(options.db, schemaFiles(options.config)) : undefined,
|
|
@@ -635,6 +649,13 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
|
|
|
635
649
|
deps.dictionary = createDictionaryPort(options.db, mediaFiles, {
|
|
636
650
|
onChange: () => options.cache?.invalidate(),
|
|
637
651
|
})
|
|
652
|
+
const tracker = options.cache
|
|
653
|
+
? createRedirectTracker({
|
|
654
|
+
cache: options.cache,
|
|
655
|
+
redirects: new RedirectRepository(options.db),
|
|
656
|
+
enabled: options.config.trackRedirects,
|
|
657
|
+
})
|
|
658
|
+
: undefined
|
|
638
659
|
if (options.cache)
|
|
639
660
|
deps.documents = createDocumentPort(
|
|
640
661
|
options.db,
|
|
@@ -644,29 +665,47 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
|
|
|
644
665
|
nodeId: options.schema?.nodeId,
|
|
645
666
|
valueIntake,
|
|
646
667
|
},
|
|
647
|
-
|
|
648
|
-
cache: options.cache,
|
|
649
|
-
redirects: new RedirectRepository(options.db),
|
|
650
|
-
enabled: options.config.trackRedirects,
|
|
651
|
-
}),
|
|
668
|
+
tracker,
|
|
652
669
|
options.config.siteDir,
|
|
653
670
|
Boolean(email),
|
|
654
671
|
)
|
|
655
672
|
if (deps.documents) {
|
|
656
|
-
const
|
|
657
|
-
|
|
658
|
-
|
|
673
|
+
const db = options.db
|
|
674
|
+
// Every document write, whoever starts it (story 170). Approvals publish
|
|
675
|
+
// through it too, so what an approval publishes is cached, tracked and
|
|
676
|
+
// announced as any publish is.
|
|
677
|
+
let operations: DocumentOperations | undefined
|
|
678
|
+
const approvals = createApprovals({
|
|
679
|
+
db,
|
|
659
680
|
nodeState: options.schema?.nodeState,
|
|
660
681
|
email,
|
|
661
682
|
backOfficeUrl: backOfficeUrl(options.config),
|
|
662
683
|
notifier: options.notifier,
|
|
663
|
-
// Through the same port an editor's publish takes, so what approval
|
|
664
|
-
// publishes is cached, tracked and announced as any publish is.
|
|
665
684
|
publisher: {
|
|
666
|
-
publish: (key, cultures) =>
|
|
667
|
-
|
|
685
|
+
publish: (key, cultures, actor) =>
|
|
686
|
+
(operations as DocumentOperations).publish(actor, key, { cultures }),
|
|
687
|
+
unpublish: (key, cultures, actor) =>
|
|
688
|
+
(operations as DocumentOperations).unpublish(actor, key, cultures),
|
|
689
|
+
},
|
|
690
|
+
})
|
|
691
|
+
deps.approvals = approvals
|
|
692
|
+
operations = createDocumentOperations({
|
|
693
|
+
db,
|
|
694
|
+
repository: {
|
|
695
|
+
nodeState: options.schema?.nodeState,
|
|
696
|
+
nodeId: options.schema?.nodeId,
|
|
697
|
+
valueIntake,
|
|
668
698
|
},
|
|
699
|
+
events: options.contentEvents ?? SILENT,
|
|
700
|
+
approvals: approvalsGate(approvals),
|
|
701
|
+
redirects: tracker,
|
|
702
|
+
onChange: () => options.cache?.invalidate(),
|
|
703
|
+
afterDomains: (node, assignment) =>
|
|
704
|
+
writeDomainsFor(db, options.config.siteDir, node, assignment),
|
|
705
|
+
refusalReason: (error) =>
|
|
706
|
+
error instanceof TemporaryFileMissingError ? error.message : undefined,
|
|
669
707
|
})
|
|
708
|
+
deps.documentOperations = operations
|
|
670
709
|
}
|
|
671
710
|
}
|
|
672
711
|
return deps
|
|
@@ -712,3 +751,20 @@ function userTwoFactorPort(service: TwoFactorService): UserTwoFactorPort {
|
|
|
712
751
|
reset: (userKey) => service.reset(userKey, provider),
|
|
713
752
|
}
|
|
714
753
|
}
|
|
754
|
+
|
|
755
|
+
/**
|
|
756
|
+
* The approval workflows as the document operations meet them. A user's principal
|
|
757
|
+
* is the backoffice's own, passed straight through; a local operator has none.
|
|
758
|
+
*/
|
|
759
|
+
export function approvalsGate(approvals: Approvals): ApprovalsGate {
|
|
760
|
+
const as = (who: ContentPrincipal | undefined) => who as Principal | undefined
|
|
761
|
+
return {
|
|
762
|
+
publishRefusal: (who, key, action) => approvals.publishRefusal(as(who), key, action),
|
|
763
|
+
branchRefusal: (who, key) => approvals.branchRefusal(as(who), key),
|
|
764
|
+
newPageRefusal: (who, parentKey, typeKey) =>
|
|
765
|
+
approvals.newPageRefusal(as(who), parentKey, typeKey),
|
|
766
|
+
beforeSave: (who, key) => approvals.beforeSave(as(who), key),
|
|
767
|
+
afterSave: (who, key) => approvals.afterSave(as(who), key),
|
|
768
|
+
afterDirectPublish: (who, key, what) => approvals.afterDirectPublish(as(who), key, what),
|
|
769
|
+
}
|
|
770
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Preview tokens (story 053): what lets an app in the browser read drafts
|
|
3
|
+
* without the API key, on behalf of the editor who pressed Preview. A token is
|
|
4
|
+
* signed, names its editor and an expiry, and carries a digest of their security
|
|
5
|
+
* stamp, so changing the password ends every token they hold. Who it is and what
|
|
6
|
+
* they may read are checked again on every request. docs/delivery-api.md,
|
|
7
|
+
* "Preview".
|
|
8
|
+
*/
|
|
9
|
+
import type { Db } from '@crombolo/data'
|
|
10
|
+
import { ensureKeyValue, fromDbBool } from '@crombolo/data'
|
|
11
|
+
|
|
12
|
+
const SIGNING_KEY = 'crombolo/previewTokenKey'
|
|
13
|
+
|
|
14
|
+
export interface PreviewTokenClaims {
|
|
15
|
+
/** The editor's user id. */
|
|
16
|
+
user: number
|
|
17
|
+
/** A digest of their security stamp when it was issued. */
|
|
18
|
+
stamp: string
|
|
19
|
+
/** Milliseconds since the epoch. */
|
|
20
|
+
expires: number
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** The per-site signing key, created once and shared by every node through the database. */
|
|
24
|
+
export function previewSigningSecret(db: Db): Promise<string> {
|
|
25
|
+
return ensureKeyValue(db, SIGNING_KEY, () => crypto.randomUUID())
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function hmac(secret: string, payload: string): string {
|
|
29
|
+
const hasher = new Bun.CryptoHasher('sha256', secret)
|
|
30
|
+
hasher.update(payload)
|
|
31
|
+
return hasher.digest('base64url')
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function sameSignature(a: string, b: string): boolean {
|
|
35
|
+
if (a.length !== b.length) return false
|
|
36
|
+
let difference = 0
|
|
37
|
+
for (let i = 0; i < a.length; i++) difference |= a.charCodeAt(i) ^ b.charCodeAt(i)
|
|
38
|
+
return difference === 0
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** A short digest of a security stamp: enough to notice it changed, nothing of the stamp itself. */
|
|
42
|
+
export function stampDigest(stamp: string | null): string {
|
|
43
|
+
const hasher = new Bun.CryptoHasher('sha256')
|
|
44
|
+
hasher.update(stamp ?? '')
|
|
45
|
+
return hasher.digest('base64url').slice(0, 16)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function signPreviewToken(secret: string, claims: PreviewTokenClaims): string {
|
|
49
|
+
const payload = Buffer.from(JSON.stringify(claims)).toString('base64url')
|
|
50
|
+
return `${payload}.${hmac(secret, payload)}`
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The claims of a token signed here and not yet expired; undefined for anything else. */
|
|
54
|
+
export function readPreviewToken(
|
|
55
|
+
secret: string,
|
|
56
|
+
token: string,
|
|
57
|
+
now = Date.now(),
|
|
58
|
+
): PreviewTokenClaims | undefined {
|
|
59
|
+
const [payload, signature, ...rest] = token.split('.')
|
|
60
|
+
if (!payload || !signature || rest.length > 0) return undefined
|
|
61
|
+
if (!sameSignature(hmac(secret, payload), signature)) return undefined
|
|
62
|
+
try {
|
|
63
|
+
const claims = JSON.parse(Buffer.from(payload, 'base64url').toString()) as PreviewTokenClaims
|
|
64
|
+
if (
|
|
65
|
+
typeof claims.user !== 'number' ||
|
|
66
|
+
typeof claims.stamp !== 'string' ||
|
|
67
|
+
typeof claims.expires !== 'number'
|
|
68
|
+
)
|
|
69
|
+
return undefined
|
|
70
|
+
return claims.expires > now ? claims : undefined
|
|
71
|
+
} catch {
|
|
72
|
+
return undefined
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The editor's standing now: undefined once they are gone, locked out or not approved. */
|
|
77
|
+
export async function previewUser(
|
|
78
|
+
db: Db,
|
|
79
|
+
where: { id: number } | { key: string },
|
|
80
|
+
): Promise<{ id: number; stamp: string } | undefined> {
|
|
81
|
+
const rows = await db.query<{
|
|
82
|
+
id: number
|
|
83
|
+
security_stamp: string | null
|
|
84
|
+
is_locked_out: unknown
|
|
85
|
+
is_approved: unknown
|
|
86
|
+
}>(
|
|
87
|
+
`SELECT id, security_stamp, is_locked_out, is_approved FROM user_account WHERE ${
|
|
88
|
+
'id' in where ? 'id' : 'key'
|
|
89
|
+
} = ?`,
|
|
90
|
+
['id' in where ? where.id : where.key],
|
|
91
|
+
)
|
|
92
|
+
const row = rows[0]
|
|
93
|
+
if (!row || fromDbBool(row.is_locked_out) || !fromDbBool(row.is_approved)) return undefined
|
|
94
|
+
return { id: Number(row.id), stamp: stampDigest(row.security_stamp) }
|
|
95
|
+
}
|
package/src/remote.ts
CHANGED
|
@@ -48,6 +48,11 @@ export interface RemoteOptions {
|
|
|
48
48
|
db: Db
|
|
49
49
|
config: CromboloConfig
|
|
50
50
|
authenticate(request: Request): Promise<Principal | undefined>
|
|
51
|
+
/**
|
|
52
|
+
* Told once a push has landed, so this node's published cache is rebuilt: the
|
|
53
|
+
* import's cache instruction carries this node's id, and a node skips its own.
|
|
54
|
+
*/
|
|
55
|
+
onApplied?(): void
|
|
51
56
|
}
|
|
52
57
|
|
|
53
58
|
export interface Remote {
|
|
@@ -307,6 +312,7 @@ export function createRemote(options: RemoteOptions): Remote {
|
|
|
307
312
|
})
|
|
308
313
|
return
|
|
309
314
|
}
|
|
315
|
+
options.onApplied?.()
|
|
310
316
|
await jobs.update(job.id, {
|
|
311
317
|
state: 'done',
|
|
312
318
|
stage:
|
package/src/seo.ts
CHANGED
|
@@ -16,6 +16,7 @@ import {
|
|
|
16
16
|
type PublishedContent,
|
|
17
17
|
renderSitemap,
|
|
18
18
|
robotsTxt,
|
|
19
|
+
SEO_ALIASES,
|
|
19
20
|
type SeoSiteDefaults,
|
|
20
21
|
sitemapEntries,
|
|
21
22
|
urlsIn,
|
|
@@ -73,6 +74,34 @@ export function originOf(request: Request, config: Pick<CromboloConfig, 'applica
|
|
|
73
74
|
return config.applicationUrl.replace(/\/$/, '')
|
|
74
75
|
}
|
|
75
76
|
|
|
77
|
+
/**
|
|
78
|
+
* The origin visitors' addresses are written against: the site's public address
|
|
79
|
+
* when it is served by an app elsewhere (`seo.publicUrl`), else the request's.
|
|
80
|
+
* Never for anything the CMS itself answers, such as sign-in callbacks.
|
|
81
|
+
*/
|
|
82
|
+
export function publicOrigin(
|
|
83
|
+
request: Request,
|
|
84
|
+
config: Pick<CromboloConfig, 'applicationUrl' | 'seo'>,
|
|
85
|
+
): string {
|
|
86
|
+
const configured = config.seo.publicUrl?.trim()
|
|
87
|
+
if (configured && /^https?:\/\/[^/]+/i.test(configured)) return configured.replace(/\/+$/, '')
|
|
88
|
+
return originOf(request, config)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** A page's search and sharing details as an app writes its head tags (story 055). */
|
|
92
|
+
export interface SeoDetails {
|
|
93
|
+
/** The `<title>`, suffix included. */
|
|
94
|
+
title: string
|
|
95
|
+
description: string | null
|
|
96
|
+
image: { url: string; width: number | null; height: number | null } | null
|
|
97
|
+
canonical: string | null
|
|
98
|
+
/** `noindex` when search engines are asked to leave the page out; otherwise null. */
|
|
99
|
+
robots: string | null
|
|
100
|
+
alternates: Array<{ culture: string; url: string }>
|
|
101
|
+
xDefault: string | null
|
|
102
|
+
siteName: string
|
|
103
|
+
}
|
|
104
|
+
|
|
76
105
|
/** Refusal text for a settings body, or the overrides it sets. */
|
|
77
106
|
export function parseSettingsBody(
|
|
78
107
|
body: unknown,
|
|
@@ -172,6 +201,21 @@ export interface SeoHost {
|
|
|
172
201
|
host: string,
|
|
173
202
|
pathname: string,
|
|
174
203
|
): Promise<{ content: PublishedContent; culture: string | null } | undefined>
|
|
204
|
+
/** What `<SeoHead>` would write for a page with no template's fallbacks, as data. */
|
|
205
|
+
details(content: PublishedContent, request: Request): Promise<SeoDetails>
|
|
206
|
+
/** The sitemap's pages for a hostname, as data; undefined when the sitemap is off. */
|
|
207
|
+
sitemapItems(
|
|
208
|
+
request: Request,
|
|
209
|
+
host: string,
|
|
210
|
+
): Promise<
|
|
211
|
+
| Array<{
|
|
212
|
+
id: string
|
|
213
|
+
url: string
|
|
214
|
+
lastmod: string
|
|
215
|
+
alternates: Array<{ culture: string; url: string }>
|
|
216
|
+
}>
|
|
217
|
+
| undefined
|
|
218
|
+
>
|
|
175
219
|
/** Backoffice routes below `<backoffice>/crombolo/api/seo`. */
|
|
176
220
|
handle(request: Request, subpath: string, principal: Principal): Promise<Response | undefined>
|
|
177
221
|
}
|
|
@@ -253,6 +297,59 @@ export function createSeoHost(options: SeoHostOptions): SeoHost {
|
|
|
253
297
|
|
|
254
298
|
const cacheControl = config.development ? 'no-cache' : 'public, max-age=3600'
|
|
255
299
|
|
|
300
|
+
/** The pages a hostname offers search engines, members-only ones left out. */
|
|
301
|
+
const openEntries = async (request: Request, host: string) => {
|
|
302
|
+
const snapshot = await cache.snapshot()
|
|
303
|
+
const entries = sitemapEntries(snapshot, { host, origin: publicOrigin(request, config) })
|
|
304
|
+
const open: typeof entries = []
|
|
305
|
+
for (const entry of entries) if (!(await options.isProtected(entry.content))) open.push(entry)
|
|
306
|
+
return open
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
const sitemapItems: SeoHost['sitemapItems'] = async (request, host) => {
|
|
310
|
+
const { effective } = await settings()
|
|
311
|
+
if (!effective.sitemap || !effective.indexable) return undefined
|
|
312
|
+
return (await openEntries(request, host)).map((entry) => ({
|
|
313
|
+
id: entry.content.key,
|
|
314
|
+
url: entry.url,
|
|
315
|
+
lastmod: entry.lastmod.toISOString(),
|
|
316
|
+
alternates: entry.alternates,
|
|
317
|
+
}))
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
const details: SeoHost['details'] = async (content, request) => {
|
|
321
|
+
const snapshot = await cache.snapshot()
|
|
322
|
+
const { effective } = await settings()
|
|
323
|
+
const meta = effectiveMeta(content, {
|
|
324
|
+
origin: publicOrigin(request, config),
|
|
325
|
+
alternates: urlsIn(snapshot, content.key),
|
|
326
|
+
site: await siteDefaults(),
|
|
327
|
+
})
|
|
328
|
+
// A size only when the image is a media item: the page's own, or a site default given by key.
|
|
329
|
+
const media =
|
|
330
|
+
meta.image.source === 'page'
|
|
331
|
+
? content.media(SEO_ALIASES.image)[0]?.media
|
|
332
|
+
: meta.image.source === 'site' && UUID.test(effective.defaultImage.trim())
|
|
333
|
+
? snapshot.media.get(effective.defaultImage.trim().toLowerCase())
|
|
334
|
+
: undefined
|
|
335
|
+
const size = (alias: string) => {
|
|
336
|
+
const value = Number(media?.value(alias))
|
|
337
|
+
return media && Number.isFinite(value) && value > 0 ? value : null
|
|
338
|
+
}
|
|
339
|
+
return {
|
|
340
|
+
title: meta.fullTitle,
|
|
341
|
+
description: meta.description.value ?? null,
|
|
342
|
+
image: meta.image.value
|
|
343
|
+
? { url: meta.image.value, width: size('umbracoWidth'), height: size('umbracoHeight') }
|
|
344
|
+
: null,
|
|
345
|
+
canonical: meta.canonical.value ?? null,
|
|
346
|
+
robots: meta.noindex.value ? 'noindex' : null,
|
|
347
|
+
alternates: meta.alternates,
|
|
348
|
+
xDefault: meta.xDefault ?? null,
|
|
349
|
+
siteName: meta.siteName,
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
256
353
|
const sitemap: SeoHost['sitemap'] = async (request, host) => {
|
|
257
354
|
const { effective } = await settings()
|
|
258
355
|
if (!effective.sitemap || !effective.indexable)
|
|
@@ -260,10 +357,7 @@ export function createSeoHost(options: SeoHostOptions): SeoHost {
|
|
|
260
357
|
status: 404,
|
|
261
358
|
headers: { 'content-type': 'text/plain; charset=utf-8' },
|
|
262
359
|
})
|
|
263
|
-
const
|
|
264
|
-
const entries = sitemapEntries(snapshot, { host, origin: originOf(request, config) })
|
|
265
|
-
const open: typeof entries = []
|
|
266
|
-
for (const entry of entries) if (!(await options.isProtected(entry.content))) open.push(entry)
|
|
360
|
+
const open = await openEntries(request, host)
|
|
267
361
|
return new Response(renderSitemap(open), {
|
|
268
362
|
headers: { 'content-type': 'application/xml; charset=utf-8', 'cache-control': cacheControl },
|
|
269
363
|
})
|
|
@@ -272,7 +366,7 @@ export function createSeoHost(options: SeoHostOptions): SeoHost {
|
|
|
272
366
|
const robots: SeoHost['robots'] = async (request) => {
|
|
273
367
|
const { effective } = await settings()
|
|
274
368
|
const text = robotsTxt(effective.robotsTxt, {
|
|
275
|
-
origin:
|
|
369
|
+
origin: publicOrigin(request, config),
|
|
276
370
|
indexable: effective.indexable,
|
|
277
371
|
sitemap: effective.sitemap,
|
|
278
372
|
})
|
|
@@ -317,7 +411,7 @@ export function createSeoHost(options: SeoHostOptions): SeoHost {
|
|
|
317
411
|
if (!UUID.test(key)) return Response.json({ message: 'Choose a page.' }, { status: 400 })
|
|
318
412
|
const draft = await options.draft(key, url.searchParams.get('culture') || null, principal)
|
|
319
413
|
if (!draft) return Response.json({ message: 'That page could not be found.' }, { status: 404 })
|
|
320
|
-
const origin =
|
|
414
|
+
const origin = publicOrigin(request, config)
|
|
321
415
|
const snapshot = await cache.snapshot()
|
|
322
416
|
const meta = effectiveMeta(draft.content, {
|
|
323
417
|
origin,
|
|
@@ -359,7 +453,7 @@ export function createSeoHost(options: SeoHostOptions): SeoHost {
|
|
|
359
453
|
return Response.json(await settings())
|
|
360
454
|
}
|
|
361
455
|
|
|
362
|
-
return { settings, siteDefaults, sitemap, robots, notFound, handle }
|
|
456
|
+
return { settings, siteDefaults, sitemap, robots, notFound, details, sitemapItems, handle }
|
|
363
457
|
}
|
|
364
458
|
|
|
365
459
|
function safeJson(text: string): unknown {
|