@crombolo/server 0.20.0 → 0.22.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/server",
3
- "version": "0.20.0",
3
+ "version": "0.22.0",
4
4
  "description": "The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -30,17 +30,17 @@
30
30
  "access": "public"
31
31
  },
32
32
  "dependencies": {
33
- "@crombolo/api-delivery": "0.20.0",
34
- "@crombolo/api-management": "0.20.0",
35
- "@crombolo/assistant": "0.20.0",
36
- "@crombolo/auth": "0.20.0",
37
- "@crombolo/backoffice-host": "0.20.0",
38
- "@crombolo/contracts": "0.20.0",
39
- "@crombolo/core": "0.20.0",
40
- "@crombolo/data": "0.20.0",
41
- "@crombolo/render": "0.20.0",
42
- "@crombolo/schema": "0.20.0",
43
- "@crombolo/transfer": "0.20.0",
33
+ "@crombolo/api-delivery": "0.22.0",
34
+ "@crombolo/api-management": "0.22.0",
35
+ "@crombolo/assistant": "0.22.0",
36
+ "@crombolo/auth": "0.22.0",
37
+ "@crombolo/backoffice-host": "0.22.0",
38
+ "@crombolo/contracts": "0.22.0",
39
+ "@crombolo/core": "0.22.0",
40
+ "@crombolo/data": "0.22.0",
41
+ "@crombolo/render": "0.22.0",
42
+ "@crombolo/schema": "0.22.0",
43
+ "@crombolo/transfer": "0.22.0",
44
44
  "@logtape/logtape": "^2.3.8"
45
45
  }
46
46
  }
@@ -116,6 +116,7 @@ export function createDocumentPort(
116
116
  return {
117
117
  byKey: (key) => repo.byKey(key),
118
118
  propertyAliases: (key) => repo.propertyAliases(key),
119
+ propertyTypes: (key) => repo.propertyTypeKeys(key),
119
120
  byKeyPublished: (key) => repo.byKeyPublished(key),
120
121
  validate: (input, cultures) => repo.validate(input, cultures),
121
122
 
@@ -480,14 +481,19 @@ export function createDocumentPort(
480
481
  }
481
482
  }
482
483
 
484
+ /**
485
+ * What the published cache is built from. With `drafts`, every page as last
486
+ * saved instead of as published, for previewing in an app (story 053); the
487
+ * rest — media, languages, domains, elements — is the same either way.
488
+ */
483
489
  export function createPublishedContentSource(
484
490
  db: Db,
485
- options: DocumentRepositoryOptions = {},
491
+ options: DocumentRepositoryOptions & { drafts?: boolean } = {},
486
492
  ): PublishedContentSource {
487
493
  const repo = new DocumentRepository(db, options)
488
494
  return {
489
495
  async loadPublished(): Promise<PublishedNode[]> {
490
- const rows = await repo.loadPublished()
496
+ const rows = options.drafts ? await repo.loadDrafts() : await repo.loadPublished()
491
497
  return rows.map((row) => ({
492
498
  key: row.key,
493
499
  id: row.id,
@@ -12,7 +12,15 @@
12
12
  * themselves did.
13
13
  */
14
14
  import type { ElementPort, Principal } from '@crombolo/api-management'
15
- import { type ElementTreeItem, normaliseUuid, ObjectTypes, SystemNodes } from '@crombolo/core'
15
+ import {
16
+ type ElementTreeItem,
17
+ MENU_ALIAS_PROPERTY,
18
+ normaliseUuid,
19
+ ObjectTypes,
20
+ SYSTEM_CONTENT_TYPE_KEYS,
21
+ SystemNodes,
22
+ safeAlias,
23
+ } from '@crombolo/core'
16
24
  import {
17
25
  appendCacheInstruction,
18
26
  type Db,
@@ -77,6 +85,72 @@ export function createElementPort(
77
85
  /** An element has no template, whatever a save sends. */
78
86
  const saved = <T extends object>(input: T) => ({ ...input, componentKey: null })
79
87
 
88
+ /** Whether another menu, not in the bin, already answers to `alias`. */
89
+ const menuAliasTaken = async (alias: string, key: string | undefined): Promise<boolean> => {
90
+ const rows = await db.query<{ unique_id: string }>(
91
+ `SELECT n.unique_id FROM property_value pv
92
+ JOIN property_type p ON p.id = pv.property_type_id
93
+ JOIN node n ON n.id = pv.node_id
94
+ JOIN content c ON c.node_id = n.id
95
+ JOIN node ct ON ct.id = c.content_type_id
96
+ WHERE p.alias = ? AND pv.is_current = ? AND n.trashed = ? AND ct.unique_id = ?
97
+ AND LOWER(COALESCE(pv.varchar_value, pv.text_value)) = ?`,
98
+ [
99
+ MENU_ALIAS_PROPERTY,
100
+ db.dialect.boolValue(true),
101
+ db.dialect.boolValue(false),
102
+ SYSTEM_CONTENT_TYPE_KEYS.Menu,
103
+ alias.toLowerCase(),
104
+ ],
105
+ )
106
+ return rows.some((row) => normaliseUuid(String(row.unique_id)) !== key?.toLowerCase())
107
+ }
108
+
109
+ /**
110
+ * A menu's alias, filled from its name when left empty, as Umbraco makes a type's
111
+ * (story 141); refused when another menu has it, since a template could then get
112
+ * either. Anything that is not a menu is saved as sent.
113
+ */
114
+ const withMenuAlias = async <
115
+ T extends {
116
+ contentTypeKey?: string
117
+ values: Array<{
118
+ alias: string
119
+ culture: string | null
120
+ segment: string | null
121
+ value: unknown
122
+ }>
123
+ variants: Array<{ name: string }>
124
+ },
125
+ >(
126
+ input: T,
127
+ key?: string,
128
+ ): Promise<T | { ok: false; reason: string; status: number }> => {
129
+ const typeKey =
130
+ input.contentTypeKey ?? (key ? (await repo.byKey(key))?.contentTypeKey : undefined)
131
+ if (typeKey?.toLowerCase() !== SYSTEM_CONTENT_TYPE_KEYS.Menu) return input
132
+ const given = input.values.find((v) => v.alias === MENU_ALIAS_PROPERTY && v.culture === null)
133
+ const alias =
134
+ (typeof given?.value === 'string' ? given.value.trim() : '') ||
135
+ safeAlias(input.variants[0]?.name ?? '')
136
+ if (!alias) return input
137
+ if (await menuAliasTaken(alias, key))
138
+ return {
139
+ ok: false,
140
+ reason: `Another menu already uses the alias "${alias}". Choose another one.`,
141
+ status: 400,
142
+ }
143
+ return {
144
+ ...input,
145
+ values: [
146
+ ...input.values.filter((v) => !(v.alias === MENU_ALIAS_PROPERTY && v.culture === null)),
147
+ { alias: MENU_ALIAS_PROPERTY, culture: null, segment: null, value: alias },
148
+ ],
149
+ }
150
+ }
151
+ const refused = (value: object): value is { ok: false; reason: string; status: number } =>
152
+ 'ok' in value && value.ok === false
153
+
80
154
  return {
81
155
  folders: createFolderPort(folders, tree, changed),
82
156
 
@@ -118,7 +192,9 @@ export function createElementPort(
118
192
  byKeyPublished: (key) => repo.byKeyPublished(key),
119
193
  validate: (input, cultures) => repo.validate(input, cultures),
120
194
 
121
- async create(input, principal) {
195
+ async create(sent, principal) {
196
+ const input = await withMenuAlias(sent)
197
+ if (refused(input)) return input
122
198
  try {
123
199
  const created = await repo.create(saved({ ...input, userId: await userIdOf(principal) }))
124
200
  await changed()
@@ -128,7 +204,9 @@ export function createElementPort(
128
204
  }
129
205
  },
130
206
 
131
- async update(key, input, principal) {
207
+ async update(key, sent, principal) {
208
+ const input = await withMenuAlias(sent, key)
209
+ if (refused(input)) return input
132
210
  try {
133
211
  const updated = await repo.update(
134
212
  saved({ ...input, key, userId: await userIdOf(principal) }),
@@ -141,7 +219,9 @@ export function createElementPort(
141
219
  }
142
220
  },
143
221
 
144
- async createAndPublish(input, cultures, principal) {
222
+ async createAndPublish(sent, cultures, principal) {
223
+ const input = await withMenuAlias(sent)
224
+ if (refused(input)) return input
145
225
  try {
146
226
  const result = await repo.createAndPublish(
147
227
  saved({ ...input, userId: await userIdOf(principal) }),
@@ -161,7 +241,9 @@ export function createElementPort(
161
241
  }
162
242
  },
163
243
 
164
- async updateAndPublish(key, input, cultures, principal) {
244
+ async updateAndPublish(key, sent, cultures, principal) {
245
+ const input = await withMenuAlias(sent, key)
246
+ if (refused(input)) return input
165
247
  try {
166
248
  const result = await repo.updateAndPublish(
167
249
  saved({ ...input, key, userId: await userIdOf(principal) }),
@@ -608,17 +608,15 @@ export function createUserPorts(
608
608
 
609
609
  async permissions(principal, tree, keys) {
610
610
  if (tree !== 'document') {
611
- // Media carries no verbs; element verbs are the groups' own until the Library exists
612
- const verbs =
613
- tree === 'element'
614
- ? [
615
- ...new Set(
616
- principal.groups.flatMap((g) =>
617
- g.defaults.filter((p) => p.startsWith('Umb.Element')),
618
- ),
619
- ),
620
- ]
621
- : []
611
+ // Media and element verbs are the groups' own: neither has per-node permissions
612
+ const prefixes = tree === 'element' ? ['Umb.Element'] : ['Crombolo.Media.']
613
+ const verbs = [
614
+ ...new Set(
615
+ principal.groups.flatMap((g) =>
616
+ g.defaults.filter((p) => prefixes.some((prefix) => p.startsWith(prefix))),
617
+ ),
618
+ ),
619
+ ]
622
620
  return keys.map((nodeKey) => ({ nodeKey: normaliseUuid(nodeKey), permissions: verbs }))
623
621
  }
624
622
  const found = await nodes.documents(keys)
package/src/approvals.ts CHANGED
@@ -14,6 +14,7 @@ import {
14
14
  approvalsNeeded,
15
15
  DocumentPermissions,
16
16
  descendantStages,
17
+ hasPathAccess,
17
18
  normaliseUuid,
18
19
  permissionsForPath,
19
20
  type SchemaWorkflow,
@@ -80,6 +81,7 @@ interface PageFacts {
80
81
  key: string
81
82
  name: string
82
83
  chain: string[]
84
+ trashed: boolean
83
85
  contentTypeAlias: string | undefined
84
86
  variesByCulture: boolean
85
87
  }
@@ -273,6 +275,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
273
275
  key: node.key,
274
276
  name: node.text ?? node.key,
275
277
  chain: ids.flatMap((id) => keyOf.get(id) ?? []),
278
+ trashed: node.trashed,
276
279
  contentTypeAlias: type[0]?.alias,
277
280
  // Umbraco's flags: 1 is culture, 2 is segment.
278
281
  variesByCulture: (Number(type[0]?.variations ?? 0) & 1) === 1,
@@ -295,6 +298,19 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
295
298
  action === 'publish' ? DocumentPermissions.Publish : DocumentPermissions.Unpublish,
296
299
  )
297
300
 
301
+ /**
302
+ * Refuses, with a 403, a caller who cannot reach the page through their start
303
+ * nodes or lacks a verb on it: asking about a page needs what opening it does.
304
+ */
305
+ const assertMayReach = (principal: Principal, facts: PageFacts, verbs: readonly string[]) => {
306
+ const granted = permissionsForPath(principal.groups, facts.chain)
307
+ if (
308
+ !hasPathAccess(principal.startNodes.document, facts.chain, facts.trashed) ||
309
+ !verbs.every((verb) => granted.has(verb))
310
+ )
311
+ throw new ApprovalRefused('You do not have access to this page.', 403)
312
+ }
313
+
298
314
  const covers = (workflow: SchemaWorkflow | undefined, action: ApprovalAction) =>
299
315
  workflow !== undefined && (action === 'publish' || workflow.unpublish)
300
316
 
@@ -749,6 +765,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
749
765
  key: '',
750
766
  name: 'This page',
751
767
  chain: parent?.chain ?? [],
768
+ trashed: false,
752
769
  contentTypeAlias: type[0]?.alias,
753
770
  variesByCulture: false,
754
771
  }
@@ -800,6 +817,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
800
817
  async send(principal, key, action, cultures, comment, schedule) {
801
818
  const facts = await page(key)
802
819
  if (!facts) throw new ApprovalRefused('The page could not be found.', 404)
820
+ assertMayReach(principal, facts, [DocumentPermissions.Read, DocumentPermissions.Update])
803
821
  const workflow = await covering(facts)
804
822
  if (!workflow || !covers(workflow, action))
805
823
  throw new ApprovalRefused(
@@ -1064,6 +1082,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
1064
1082
  async forPage(principal, key) {
1065
1083
  const facts = await page(key)
1066
1084
  if (!facts) throw new ApprovalRefused('The page could not be found.', 404)
1085
+ assertMayReach(principal, facts, [DocumentPermissions.Read])
1067
1086
  const workflow = await covering(facts)
1068
1087
  const all = await requests().forNode(key)
1069
1088
  const waiting = all.find((r) => r.state === 'waiting' || r.state === 'scheduled')
package/src/config.ts CHANGED
@@ -6,7 +6,12 @@ import {
6
6
  DEFAULT_PASSWORD_CONFIGURATION,
7
7
  isValidPassword,
8
8
  } from '@crombolo/core'
9
- import { DEFAULT_RENDER_TIMEOUT_MS, type RedirectRule, type SnapshotLimits } from '@crombolo/render'
9
+ import {
10
+ type CacheOptions,
11
+ DEFAULT_RENDER_TIMEOUT_MS,
12
+ type RedirectRule,
13
+ type SnapshotLimits,
14
+ } from '@crombolo/render'
10
15
  import type { AssistantConfig } from './assistant.ts'
11
16
  import type { ServerBundle } from './bundles.ts'
12
17
  import type { EmailPort } from './email.ts'
@@ -349,10 +354,19 @@ export interface CromboloConfig {
349
354
  /**
350
355
  * Umbraco's Delivery API (`docs/delivery-api.md`): off unless enabled.
351
356
  * `CROMBOLO_DELIVERY_API`, `CROMBOLO_DELIVERY_API_KEY`,
352
- * `CROMBOLO_DELIVERY_API_PUBLIC` and `CROMBOLO_DELIVERY_API_MEDIA`; member
357
+ * `CROMBOLO_DELIVERY_API_PUBLIC`, `CROMBOLO_DELIVERY_API_MEDIA`,
358
+ * `CROMBOLO_DELIVERY_API_CORS_ORIGINS`, `CROMBOLO_DELIVERY_API_PREVIEW_URL` and
359
+ * `CROMBOLO_DELIVERY_API_PREVIEW_TOKEN_MINUTES`; member
353
360
  * sign-in is configured here, since its clients and secrets are a list.
354
361
  */
355
362
  deliveryApi: DeliveryApiOptions
363
+ /**
364
+ * How long pages, Delivery API answers and media may be kept by browsers and a
365
+ * CDN (story 057; `docs/operations.md`, "Behind a CDN"). Nothing is kept unless
366
+ * set. `CROMBOLO_CACHE_MAX_AGE`, `CROMBOLO_CACHE_STALE_WHILE_REVALIDATE` and
367
+ * `CROMBOLO_CACHE_TAG_HEADER`; per type alias in code only.
368
+ */
369
+ cache: CacheOptions
356
370
  /**
357
371
  * Bundles whose server half this site runs, each the result of calling the
358
372
  * factory its package exports. Imported and listed here by hand on purpose:
@@ -485,6 +499,12 @@ export interface SeoConfig {
485
499
  defaultImage?: string
486
500
  /** A page key, or rules choosing one per hostname or language. */
487
501
  notFoundPage?: string | NotFoundRule[]
502
+ /**
503
+ * Where visitors see the site, when that is not here — an app on another host
504
+ * (story 055): used for preferred addresses, the sitemap and `robots.txt`.
505
+ * CROMBOLO_PUBLIC_URL.
506
+ */
507
+ publicUrl?: string
488
508
  }
489
509
 
490
510
  /** A site's config file exports `defineConfig({...})`; unset keys come from the environment. */
@@ -624,6 +644,7 @@ export function loadConfig(
624
644
  seo: stripUndefined({
625
645
  sitemap: envFlag(setting('CROMBOLO_SITEMAP')),
626
646
  indexable: envFlag(setting('CROMBOLO_INDEXABLE')),
647
+ publicUrl: setting('CROMBOLO_PUBLIC_URL') || undefined,
627
648
  }),
628
649
  deliveryApi: stripUndefined({
629
650
  enabled: envFlag(setting('CROMBOLO_DELIVERY_API')),
@@ -633,6 +654,27 @@ export function loadConfig(
633
654
  envFlag(setting('CROMBOLO_DELIVERY_API_MEDIA')) === undefined
634
655
  ? undefined
635
656
  : { enabled: envFlag(setting('CROMBOLO_DELIVERY_API_MEDIA')) },
657
+ cors:
658
+ setting('CROMBOLO_DELIVERY_API_CORS_ORIGINS') === undefined
659
+ ? undefined
660
+ : {
661
+ allowedOrigins: (setting('CROMBOLO_DELIVERY_API_CORS_ORIGINS') ?? '')
662
+ .split(',')
663
+ .map((origin) => origin.trim())
664
+ .filter(Boolean),
665
+ },
666
+ preview: stripUndefined({
667
+ url: setting('CROMBOLO_DELIVERY_API_PREVIEW_URL') || undefined,
668
+ tokenMinutes:
669
+ setting('CROMBOLO_DELIVERY_API_PREVIEW_TOKEN_MINUTES') === undefined
670
+ ? undefined
671
+ : Number(setting('CROMBOLO_DELIVERY_API_PREVIEW_TOKEN_MINUTES')),
672
+ }),
673
+ }),
674
+ cache: stripUndefined({
675
+ maxAge: numberSetting('CROMBOLO_CACHE_MAX_AGE'),
676
+ staleWhileRevalidate: numberSetting('CROMBOLO_CACHE_STALE_WHILE_REVALIDATE'),
677
+ tagHeader: setting('CROMBOLO_CACHE_TAG_HEADER') || undefined,
636
678
  }),
637
679
  // No environment variable: a bundle is an import, which is code.
638
680
  bundles: [],
@@ -653,10 +695,16 @@ export function loadConfig(
653
695
  throw new Error(
654
696
  `remote.environment "${merged.remote.environment}" must be lower case letters, digits and dashes.`,
655
697
  )
698
+ merged.cache = { ...fromEnv.cache, ...stripUndefined(overrides.cache ?? {}) }
656
699
  merged.deliveryApi = {
657
700
  ...fromEnv.deliveryApi,
658
701
  ...stripUndefined(overrides.deliveryApi ?? {}),
659
702
  media: { ...fromEnv.deliveryApi.media, ...(overrides.deliveryApi?.media ?? {}) },
703
+ cors: { ...fromEnv.deliveryApi.cors, ...stripUndefined(overrides.deliveryApi?.cors ?? {}) },
704
+ preview: {
705
+ ...fromEnv.deliveryApi.preview,
706
+ ...stripUndefined(overrides.deliveryApi?.preview ?? {}),
707
+ },
660
708
  }
661
709
  // A schema store makes backoffice writes durable, so it carries writability with
662
710
  // it — that is the point of configuring one. An explicit setting still wins.
@@ -740,4 +788,12 @@ export function describeDatabase(
740
788
  }
741
789
  }
742
790
 
743
- export const VERSION = '0.20.0'
791
+ export const VERSION = '0.22.0'
792
+
793
+ /** A whole number of seconds from the environment; undefined when unset or not one. */
794
+ function numberSetting(name: Parameters<typeof setting>[0]): number | undefined {
795
+ const raw = setting(name)
796
+ if (raw === undefined || raw.trim() === '') return undefined
797
+ const value = Number(raw)
798
+ return Number.isFinite(value) && value >= 0 ? value : undefined
799
+ }
@@ -26,6 +26,7 @@ import {
26
26
  externalLoginProvider,
27
27
  } from '@crombolo/data'
28
28
  import type { IdentityProvider } from './identity-providers.ts'
29
+ import { originOf } from './seo.ts'
29
30
 
30
31
  /** A member or user, as far as signing in is concerned. */
31
32
  export interface ExternalAccount {
@@ -155,10 +156,13 @@ export function createExternalSignIn(
155
156
  return key
156
157
  }
157
158
  const flowCookie = `crombolo-external-${audience.audience}`
158
- const originOf = (request: Request) =>
159
- (options.applicationUrl || new URL(request.url).origin).replace(/\/$/, '')
159
+ // The address the visitor used, as a proxy in front says it, so a site
160
+ // reached by several names signs in on the one it was opened on. The
161
+ // provider still refuses a callback it was not registered with.
162
+ const callbackOrigin = (request: Request) =>
163
+ originOf(request, { applicationUrl: options.applicationUrl })
160
164
  const callbackUrl = (request: Request, id: string) =>
161
- `${originOf(request)}${audience.basePath}/${id}/callback`
165
+ `${callbackOrigin(request)}${audience.basePath}/${id}/callback`
162
166
  const redirect = (location: string, cookies: string[] = []) => {
163
167
  const headers = new Headers({ location })
164
168
  for (const cookie of cookies) headers.append('set-cookie', cookie)
package/src/ports.ts CHANGED
@@ -16,6 +16,7 @@ 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,
@@ -127,12 +128,13 @@ function createServerPort(config: CromboloConfig, canSendUserLinks: boolean): Se
127
128
  /** Umbraco's preview cookie; with a signed-in editor it turns on draft rendering. */
128
129
  export const PREVIEW_COOKIE = 'UMB_PREVIEW'
129
130
 
130
- function createPreviewPort(config: CromboloConfig): PreviewPort {
131
+ function createPreviewPort(config: CromboloConfig, inApp?: PreviewPort['inApp']): PreviewPort {
131
132
  return {
132
133
  enter: () => [
133
134
  serializeCookie({ name: PREVIEW_COOKIE, value: 'preview', secure: config.secureCookies }),
134
135
  ],
135
136
  exit: () => [expireCookie(PREVIEW_COOKIE, config.secureCookies)],
137
+ inApp,
136
138
  }
137
139
  }
138
140
 
@@ -389,6 +391,8 @@ export interface DepsOptions {
389
391
  webhooks?: WebhookService
390
392
  /** Required alongside `db` to serve documents, which invalidate the cache. */
391
393
  cache?: PublishedCache
394
+ /** Where a page previews in the site's app (story 053); unset, Preview is Umbraco's own. */
395
+ previewInApp?: PreviewPort['inApp']
392
396
  schema?: SchemaBoot
393
397
  /** Uploaded files; one is made on `config.mediaDir` when omitted. */
394
398
  mediaFiles?: MediaFileStore
@@ -454,14 +458,13 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
454
458
  const sendUserLink = resolveUserLinkSender(options.config, email)
455
459
  const deps: ManagementApiDeps = {
456
460
  server: createServerPort(options.config, Boolean(sendUserLink)),
457
- preview: createPreviewPort(options.config),
461
+ preview: createPreviewPort(options.config, options.previewInApp),
458
462
  // An unconfigured assistant contributes no extension, so the backoffice has
459
- // no drawer, no button and nothing to load.
460
- manifests: createManifestPort(
461
- options.paths,
462
- options.extensions,
463
- options.config.assistant ? [] : [ASSISTANT_MANIFEST_ID],
464
- ),
463
+ // no drawer, no button and nothing to load; Preview in app likewise.
464
+ manifests: createManifestPort(options.paths, options.extensions, [
465
+ ...(options.config.assistant ? [] : [ASSISTANT_MANIFEST_ID]),
466
+ ...(options.previewInApp ? [] : [APP_PREVIEW_MANIFEST_ID]),
467
+ ]),
465
468
  localization: createLocalizationPort(
466
469
  options.db,
467
470
  options.db ? createSchemaFileWriter(options.db, schemaFiles(options.config)) : undefined,
@@ -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/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 snapshot = await cache.snapshot()
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: originOf(request, config),
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 = originOf(request, config)
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 {
package/src/server.ts CHANGED
@@ -8,10 +8,24 @@
8
8
 
9
9
  import { existsSync } from 'node:fs'
10
10
  import { join } from 'node:path'
11
- import { createDeliveryApi, resolveDeliveryApiSettings } from '@crombolo/api-delivery'
11
+ import {
12
+ apiForm,
13
+ corsPolicy,
14
+ createDeliveryApi,
15
+ fillPreviewUrl,
16
+ isPreflight,
17
+ preflightResponse,
18
+ previewProblems,
19
+ previewsInApp,
20
+ previewUrlFor,
21
+ requestedCulture,
22
+ resolveDeliveryApiSettings,
23
+ withCors,
24
+ } from '@crombolo/api-delivery'
12
25
  import {
13
26
  type ClientAddress,
14
27
  canReadDocument,
28
+ canReadDocumentAt,
15
29
  createManagementApiRouter,
16
30
  hasSection,
17
31
  type Principal,
@@ -63,6 +77,7 @@ import {
63
77
  ensureKeyValue,
64
78
  FormEntryRepository,
65
79
  FormWorkflowRepository,
80
+ latestContentVersionId,
66
81
  PublicAccessRepository,
67
82
  RedirectRepository,
68
83
  readLedger,
@@ -74,14 +89,20 @@ import {
74
89
  type WritesPaused,
75
90
  } from '@crombolo/data'
76
91
  import {
92
+ cacheable,
93
+ cacheControl,
77
94
  contentForNode,
78
95
  DEVELOPMENT_LIMITS,
79
96
  FORM_SCRIPT,
80
97
  FORM_SCRIPT_PATH,
81
98
  FORM_SUBMIT_PATH,
99
+ formAction,
100
+ lifetimeFor,
82
101
  MEMBER_EXTERNAL_SIGN_IN_PATH,
102
+ PRIVATE_NO_STORE,
83
103
  PublishedCache,
84
104
  Renderer,
105
+ resolveCacheSettings,
85
106
  type SnapshotStatus,
86
107
  setFormFieldTypes,
87
108
  setFormTokenSigner,
@@ -149,6 +170,12 @@ import { createMemberAuth, MEMBER_ROUTE_PREFIX } from './member-auth.ts'
149
170
  import { noNodesPage } from './no-nodes.ts'
150
171
  import { NotImplementedLog } from './not-implemented.ts'
151
172
  import { createDeps, documentEditUrl, PREVIEW_COOKIE, resolveUserLinkSender } from './ports.ts'
173
+ import {
174
+ previewSigningSecret,
175
+ previewUser,
176
+ readPreviewToken,
177
+ signPreviewToken,
178
+ } from './preview-tokens.ts'
152
179
  import { createRedirectTracker } from './redirects.ts'
153
180
  import { createRemote } from './remote.ts'
154
181
  import { withRemoteMedia } from './remote-media.ts'
@@ -178,7 +205,7 @@ import {
178
205
  watchSchema,
179
206
  } from './schema.ts'
180
207
  import { publishSchema, type SchemaStore, useSchemaStore } from './schema-store.ts'
181
- import { createSeoHost, originOf } from './seo.ts'
208
+ import { createSeoHost, originOf, publicOrigin } from './seo.ts'
182
209
  import {
183
210
  combineHubs,
184
211
  createServerEventHub,
@@ -471,7 +498,13 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
471
498
  }
472
499
 
473
500
  const identity = await auth.resolveAccessToken(token)
474
- if (!identity) return undefined
501
+ return identity && principalFrom(identity)
502
+ }
503
+
504
+ /** What a resolved user may do, as every check in the Management API reads it. */
505
+ async function principalFrom(
506
+ identity: NonNullable<Awaited<ReturnType<typeof auth.identityOf>>>,
507
+ ): Promise<Principal> {
475
508
  return {
476
509
  id: identity.user.key,
477
510
  userName: identity.user.login,
@@ -500,7 +533,28 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
500
533
  nodeId: schema.nodeId,
501
534
  })
502
535
  const cacheOptions = { form: (key: string) => forms.byKey(key) }
503
- const cache = new PublishedCache(publishedSource, cacheOptions)
536
+ // Every page as last saved, for previewing in an app (story 053). Built on the
537
+ // first preview after a change and dropped with the published cache, so a site
538
+ // nobody previews never holds it. A save on another node announces nothing,
539
+ // but always adds a version, so the newest version id says when it is stale.
540
+ const draftSource = createPublishedContentSource(db, {
541
+ nodeState: schema.nodeState,
542
+ nodeId: schema.nodeId,
543
+ drafts: true,
544
+ })
545
+ let drafts: { cache: PublishedCache; version: number } | undefined
546
+ const draftCache = async (): Promise<PublishedCache> => {
547
+ const version = await latestContentVersionId(db)
548
+ if (drafts?.version !== version)
549
+ drafts = { cache: new PublishedCache(draftSource, cacheOptions), version }
550
+ return drafts.cache
551
+ }
552
+ const cache = new PublishedCache(publishedSource, {
553
+ ...cacheOptions,
554
+ onInvalidate: () => {
555
+ drafts = undefined
556
+ },
557
+ })
504
558
  // A sync or a Settings change that alters how URLs are built moves every URL:
505
559
  // the old ones redirect, as a rename's do.
506
560
  const urlChange: UrlChangeContext = {
@@ -693,6 +747,8 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
693
747
  nodeId: schema.nodeId,
694
748
  })
695
749
  const deliverySettings = resolveDeliveryApiSettings(config.deliveryApi)
750
+ const caching = resolveCacheSettings(config.cache)
751
+ const formCors = corsPolicy(deliverySettings)
696
752
  const deliveryPrefix = DELIVERY_API_PREFIX
697
753
  const deliveryMembers = createDeliveryMemberSecurity({
698
754
  db,
@@ -701,18 +757,98 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
701
757
  })
702
758
  for (const problem of deliveryMembers.problems)
703
759
  log.warning('Delivery API: {problem}', { problem })
760
+ for (const problem of previewProblems(deliverySettings))
761
+ log.warning('Delivery API: {problem}', { problem })
762
+
763
+ // Preview tokens (story 053): an app in the browser reads drafts for the
764
+ // editor who pressed Preview, checked again on every request.
765
+ const previewSecret = await previewSigningSecret(db)
766
+ const previewEditor = async (token: string): Promise<Principal | undefined> => {
767
+ const claims = readPreviewToken(previewSecret, token)
768
+ if (!claims) return undefined
769
+ const standing = await previewUser(db, { id: claims.user })
770
+ if (standing?.stamp !== claims.stamp) return undefined
771
+ const identity = await auth.identityOf(claims.user)
772
+ return identity && principalFrom(identity)
773
+ }
774
+
775
+ /** Where a page previews in the app, with a token for this editor in the address. */
776
+ async function previewInApp(
777
+ key: string,
778
+ culture: string | null,
779
+ principal: Principal,
780
+ ): Promise<{ url: string } | { message: string }> {
781
+ const page = await (await draftCache()).byKey(key, culture)
782
+ if (!page) return { message: 'Save the page, then preview it in the app.' }
783
+ const template = previewUrlFor(deliverySettings, page.contentType.alias)
784
+ if (!template)
785
+ return {
786
+ message:
787
+ 'Pages of this type have no preview address in the app. Ask an administrator to add one.',
788
+ }
789
+ const standing = await previewUser(db, { key: principal.id })
790
+ if (!standing) return { message: 'Sign in again, then preview the page.' }
791
+ const token = signPreviewToken(previewSecret, {
792
+ user: standing.id,
793
+ stamp: standing.stamp,
794
+ expires: Date.now() + deliverySettings.preview.tokenMinutes * 60_000,
795
+ })
796
+ const path = /^https?:\/\//i.test(page.url) ? new URL(page.url).pathname : page.url
797
+ return { url: fillPreviewUrl(template, { path, id: key, culture, token }) }
798
+ }
799
+ const appPreview =
800
+ deliverySettings.enabled && previewsInApp(deliverySettings) ? previewInApp : undefined
801
+
704
802
  const deliveryApi =
705
803
  config.role === 'api'
706
804
  ? undefined
707
805
  : createDeliveryApi({
708
806
  settings: deliverySettings,
709
807
  cache,
808
+ caching,
710
809
  prefix: deliveryPrefix,
810
+ // Asked only at request time, by which point the SEO host below exists.
811
+ seo: async (content, request) => ({ ...(await seo.details(content, request)) }),
812
+ forms: {
813
+ // By key, or by alias, which is what an app is likelier to know.
814
+ byKey: (key) => forms.byKey(key) ?? forms.all().find((form) => form.alias === key),
815
+ shaper: async (culture, request) => {
816
+ const tools = await cache.formTools(culture)
817
+ const now = Date.now()
818
+ // Submissions go to the CMS, wherever the app that draws the form is.
819
+ const origin = originOf(request, config)
820
+ return (form) =>
821
+ apiForm(tools.resolve(form), {
822
+ types: formTypes.types,
823
+ action: `${origin}${formAction(form)}`,
824
+ token: signFormToken(formSecret, form.key ?? form.alias, now),
825
+ renderedAt: now,
826
+ redirectUrl: form.redirectTo ? tools.urlOf(form.redirectTo) : undefined,
827
+ })
828
+ },
829
+ },
830
+ sitemap: (request, host) => seo.sitemapItems(request, host),
831
+ notFound: async (host, path) => {
832
+ const found = await seo.notFound(host, path)
833
+ return found && { key: found.content.key, culture: found.culture }
834
+ },
835
+ preview: async (request, keyed) => {
836
+ if (keyed) return { cache: await draftCache() }
837
+ const token = request.headers.get('preview-token')
838
+ const editor = token ? await previewEditor(token) : undefined
839
+ if (!editor) return undefined
840
+ return {
841
+ cache: await draftCache(),
842
+ mayRead: (chain) => canReadDocumentAt(editor, chain),
843
+ }
844
+ },
711
845
  protection: () => new PublicAccessRepository(db).allRules(),
712
846
  member: (token) => deliveryMembers.member(token),
713
847
  security: (request, action) => deliveryMembers.handle(request, action),
714
848
  search: (term, options) => new SiteSearch(db).query(term, options),
715
849
  })
850
+ for (const problem of deliveryApi?.problems ?? [])
851
+ log.warning('Delivery API: {problem}', { problem })
716
852
 
717
853
  const nodeLookup = createNodeLookup(db)
718
854
 
@@ -803,6 +939,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
803
939
  db,
804
940
  webhooks,
805
941
  cache,
942
+ previewInApp: appPreview,
806
943
  schema,
807
944
  mediaFiles,
808
945
  email,
@@ -1064,10 +1201,14 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1064
1201
 
1065
1202
  // A visitor posting a form. Before the renderer, which would otherwise try
1066
1203
  // to resolve `/crombolo/forms/...` as a page.
1067
- if (pathname.startsWith(`${FORM_SUBMIT_PATH}/`))
1204
+ // An app on another origin posts here too (story 056), on the Delivery API's origins.
1205
+ if (pathname.startsWith(`${FORM_SUBMIT_PATH}/`)) {
1206
+ if (isPreflight(request) && formCors.origins.size + (formCors.any ? 1 : 0) > 0)
1207
+ return preflightResponse(formCors, request, 'POST')
1068
1208
  return request.method === 'POST'
1069
- ? submitFormRoute(request, pathname)
1209
+ ? withCors(formCors, request, await submitFormRoute(request, pathname))
1070
1210
  : new Response('Method Not Allowed', { status: 405, headers: { allow: 'POST' } })
1211
+ }
1071
1212
 
1072
1213
  // Not on an `api` node, which serves no public site to describe.
1073
1214
  if ((pathname === '/sitemap.xml' || pathname === '/robots.txt') && config.role !== 'api')
@@ -1898,9 +2039,21 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1898
2039
  async function serveMedia(pathname: string, search: URLSearchParams): Promise<Response> {
1899
2040
  // Media is what someone else uploaded, served from this origin, so a browser
1900
2041
  // must not guess a type the store did not give.
2042
+ // A file's bytes never change at its address — a replacement is placed in a
2043
+ // new folder — so it is kept for a year unless its media item or type says
2044
+ // otherwise (story 057). Resized images follow their original.
2045
+ const item = await cache.mediaAt(pathname)
2046
+ const chosen = item
2047
+ ? lifetimeFor(
2048
+ caching,
2049
+ { typeAlias: item.mediaType.alias, value: (alias) => item.value(alias) },
2050
+ { site: false },
2051
+ )
2052
+ : undefined
1901
2053
  const cacheable = {
1902
- 'cache-control': 'public, max-age=31536000, immutable',
2054
+ 'cache-control': cacheControl(chosen) ?? 'public, max-age=31536000, immutable',
1903
2055
  'x-content-type-options': 'nosniff',
2056
+ ...(caching.tagHeader && item ? { [caching.tagHeader]: item.key } : {}),
1904
2057
  }
1905
2058
  /**
1906
2059
  * `sandbox` for the types that carry script, which Umbraco's upload rules
@@ -1974,7 +2127,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1974
2127
  /** What every rendered page is told about the request and the site's search defaults. */
1975
2128
  async function pageRequest(request: Request) {
1976
2129
  return {
1977
- origin: originOf(request, config),
2130
+ origin: publicOrigin(request, config),
1978
2131
  url: request.url,
1979
2132
  seo: await seo.siteDefaults(),
1980
2133
  signal: request.signal,
@@ -2022,6 +2175,9 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2022
2175
  // The page it was sent from names the culture; the keys a source offers
2023
2176
  // are the same in every culture, so only the stored labels depend on it.
2024
2177
  resolveForm: async (form) => {
2178
+ // An app says which language it drew the form in; a page's address says it otherwise.
2179
+ const asked = requestedCulture(request.headers.get('accept-language'))
2180
+ if (asked && (await cache.hasCulture(asked))) return cache.resolveForm(form, asked)
2025
2181
  const referer = request.headers.get('referer')
2026
2182
  let culture: string | null = null
2027
2183
  try {
@@ -2111,12 +2267,19 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2111
2267
  // cleared, so a reload shows the page rather than the thank-you again.
2112
2268
  const cookie = readCookie(request, FORM_FLASH_COOKIE)
2113
2269
  const submission = cookie ? readFlash(formSecret, cookie) : undefined
2270
+ // A page that is not the same for everyone is never kept: a member's, a
2271
+ // preview, a form's answer, or anything in a members-only branch — which a
2272
+ // visitor sees as the login page, at the same address.
2273
+ let personal = Boolean(preview || member || submission || cookie)
2114
2274
  const result =
2115
2275
  preview ??
2116
2276
  (await renderer.render(pathname, host, {
2117
2277
  member,
2118
2278
  submission,
2119
- access: (content) => members.decide(content, member),
2279
+ access: async (content) => {
2280
+ if ((await members.decide(content, undefined)).status !== 'allowed') personal = true
2281
+ return members.decide(content, member)
2282
+ },
2120
2283
  search: siteSearchFor(db, cache, member),
2121
2284
  ...(await pageRequest(request)),
2122
2285
  }))
@@ -2124,10 +2287,24 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2124
2287
  ? { 'set-cookie': expireCookie(FORM_FLASH_COOKIE, config.secureCookies) }
2125
2288
  : {}
2126
2289
  switch (result.status) {
2127
- case 'ok':
2128
- return new Response(result.html, {
2290
+ case 'ok': {
2291
+ const response = new Response(result.html, {
2129
2292
  headers: { 'content-type': 'text/html; charset=utf-8', ...cleared },
2130
2293
  })
2294
+ if (personal) {
2295
+ response.headers.set('cache-control', PRIVATE_NO_STORE)
2296
+ return response
2297
+ }
2298
+ const ancestors = (await cache.navigation(result.content.culture)).ancestors(result.content)
2299
+ return cacheable(request, response, result.html, {
2300
+ lifetime: lifetimeFor(caching, {
2301
+ typeAlias: result.content.contentType.alias,
2302
+ value: (alias) => result.content.value(alias),
2303
+ }),
2304
+ tags: [result.content.key, ...ancestors.map((a) => a.key)],
2305
+ tagHeader: caching.tagHeader,
2306
+ })
2307
+ }
2131
2308
  case 'redirect':
2132
2309
  // Umbraco's `umbracoRedirect` answers 302: the page may stop redirecting.
2133
2310
  return new Response(null, {
package/src/settings.ts CHANGED
@@ -666,6 +666,13 @@ const DECLARED = [
666
666
  description:
667
667
  'Off keeps search engines out entirely, for a staging site: robots are refused, there is no sitemap and every page asks not to be indexed.',
668
668
  },
669
+ {
670
+ env: 'CROMBOLO_PUBLIC_URL',
671
+ kind: 'string',
672
+ section: 'Public site',
673
+ description:
674
+ 'Where visitors see the site, when that is an app on another address, such as https://www.example.com. Used for preferred addresses, the sitemap and robots.txt.',
675
+ },
669
676
  {
670
677
  env: 'CROMBOLO_SITEMAP',
671
678
  kind: 'boolean',
@@ -709,6 +716,47 @@ const DECLARED = [
709
716
  section: 'Public site',
710
717
  description: 'The Delivery API serves media as well as content.',
711
718
  },
719
+ {
720
+ env: 'CROMBOLO_DELIVERY_API_CORS_ORIGINS',
721
+ kind: 'list',
722
+ section: 'Public site',
723
+ description:
724
+ 'Other sites whose pages may call the Delivery API from the browser, such as https://app.example.com, separated by commas.',
725
+ },
726
+ {
727
+ env: 'CROMBOLO_CACHE_MAX_AGE',
728
+ kind: 'number',
729
+ section: 'Public site',
730
+ description:
731
+ 'Seconds browsers and a CDN may reuse a page, an API answer or a media item before asking again; 0 keeps nothing. Unset, nothing is kept.',
732
+ },
733
+ {
734
+ env: 'CROMBOLO_CACHE_STALE_WHILE_REVALIDATE',
735
+ kind: 'number',
736
+ section: 'Public site',
737
+ description: 'Seconds an out-of-date copy may still be shown while a fresh one is fetched.',
738
+ },
739
+ {
740
+ env: 'CROMBOLO_CACHE_TAG_HEADER',
741
+ kind: 'string',
742
+ section: 'Public site',
743
+ description:
744
+ 'The header your CDN purges by, such as Surrogate-Key or Cache-Tag. Set, every answer lists the pages and media in it.',
745
+ },
746
+ {
747
+ env: 'CROMBOLO_DELIVERY_API_PREVIEW_URL',
748
+ kind: 'string',
749
+ section: 'Public site',
750
+ description:
751
+ 'Where Preview opens a page in your app, such as https://app.example.com/preview?path={path}&token={token}.',
752
+ },
753
+ {
754
+ env: 'CROMBOLO_DELIVERY_API_PREVIEW_TOKEN_MINUTES',
755
+ kind: 'number',
756
+ default: '60',
757
+ section: 'Public site',
758
+ description: 'How long a preview opened in your app keeps working.',
759
+ },
712
760
 
713
761
  // Remote
714
762
  {