@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/src/server.ts CHANGED
@@ -8,13 +8,28 @@
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,
32
+ type ServerEvent,
18
33
  } from '@crombolo/api-management'
19
34
  import {
20
35
  AuthService,
@@ -63,6 +78,7 @@ import {
63
78
  ensureKeyValue,
64
79
  FormEntryRepository,
65
80
  FormWorkflowRepository,
81
+ latestContentVersionId,
66
82
  PublicAccessRepository,
67
83
  RedirectRepository,
68
84
  readLedger,
@@ -74,14 +90,20 @@ import {
74
90
  type WritesPaused,
75
91
  } from '@crombolo/data'
76
92
  import {
93
+ cacheable,
94
+ cacheControl,
77
95
  contentForNode,
78
96
  DEVELOPMENT_LIMITS,
79
97
  FORM_SCRIPT,
80
98
  FORM_SCRIPT_PATH,
81
99
  FORM_SUBMIT_PATH,
100
+ formAction,
101
+ lifetimeFor,
82
102
  MEMBER_EXTERNAL_SIGN_IN_PATH,
103
+ PRIVATE_NO_STORE,
83
104
  PublishedCache,
84
105
  Renderer,
106
+ resolveCacheSettings,
85
107
  type SnapshotStatus,
86
108
  setFormFieldTypes,
87
109
  setFormTokenSigner,
@@ -109,6 +131,7 @@ import {
109
131
  type ServerRole,
110
132
  VERSION,
111
133
  } from './config.ts'
134
+ import { createContentEventSink } from './content-events.ts'
112
135
  import { createContentNotificationRunner, createContentNotifier } from './content-notifications.ts'
113
136
  import { attachDatabase, bootstrapDatabase } from './database.ts'
114
137
  import { createDeliveryMemberSecurity } from './delivery-members.ts'
@@ -149,6 +172,12 @@ import { createMemberAuth, MEMBER_ROUTE_PREFIX } from './member-auth.ts'
149
172
  import { noNodesPage } from './no-nodes.ts'
150
173
  import { NotImplementedLog } from './not-implemented.ts'
151
174
  import { createDeps, documentEditUrl, PREVIEW_COOKIE, resolveUserLinkSender } from './ports.ts'
175
+ import {
176
+ previewSigningSecret,
177
+ previewUser,
178
+ readPreviewToken,
179
+ signPreviewToken,
180
+ } from './preview-tokens.ts'
152
181
  import { createRedirectTracker } from './redirects.ts'
153
182
  import { createRemote } from './remote.ts'
154
183
  import { withRemoteMedia } from './remote-media.ts'
@@ -178,7 +207,7 @@ import {
178
207
  watchSchema,
179
208
  } from './schema.ts'
180
209
  import { publishSchema, type SchemaStore, useSchemaStore } from './schema-store.ts'
181
- import { createSeoHost, originOf } from './seo.ts'
210
+ import { createSeoHost, originOf, publicOrigin } from './seo.ts'
182
211
  import {
183
212
  combineHubs,
184
213
  createServerEventHub,
@@ -471,7 +500,13 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
471
500
  }
472
501
 
473
502
  const identity = await auth.resolveAccessToken(token)
474
- if (!identity) return undefined
503
+ return identity && principalFrom(identity)
504
+ }
505
+
506
+ /** What a resolved user may do, as every check in the Management API reads it. */
507
+ async function principalFrom(
508
+ identity: NonNullable<Awaited<ReturnType<typeof auth.identityOf>>>,
509
+ ): Promise<Principal> {
475
510
  return {
476
511
  id: identity.user.key,
477
512
  userName: identity.user.login,
@@ -500,7 +535,28 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
500
535
  nodeId: schema.nodeId,
501
536
  })
502
537
  const cacheOptions = { form: (key: string) => forms.byKey(key) }
503
- const cache = new PublishedCache(publishedSource, cacheOptions)
538
+ // Every page as last saved, for previewing in an app (story 053). Built on the
539
+ // first preview after a change and dropped with the published cache, so a site
540
+ // nobody previews never holds it. A save on another node announces nothing,
541
+ // but always adds a version, so the newest version id says when it is stale.
542
+ const draftSource = createPublishedContentSource(db, {
543
+ nodeState: schema.nodeState,
544
+ nodeId: schema.nodeId,
545
+ drafts: true,
546
+ })
547
+ let drafts: { cache: PublishedCache; version: number } | undefined
548
+ const draftCache = async (): Promise<PublishedCache> => {
549
+ const version = await latestContentVersionId(db)
550
+ if (drafts?.version !== version)
551
+ drafts = { cache: new PublishedCache(draftSource, cacheOptions), version }
552
+ return drafts.cache
553
+ }
554
+ const cache = new PublishedCache(publishedSource, {
555
+ ...cacheOptions,
556
+ onInvalidate: () => {
557
+ drafts = undefined
558
+ },
559
+ })
504
560
  // A sync or a Settings change that alters how URLs are built moves every URL:
505
561
  // the old ones redirect, as a rename's do.
506
562
  const urlChange: UrlChangeContext = {
@@ -687,12 +743,14 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
687
743
  },
688
744
  )
689
745
  : undefined
690
- const remote = createRemote({ db, config, authenticate })
746
+ const remote = createRemote({ db, config, authenticate, onApplied: () => cache.invalidate() })
691
747
  const members = createMemberAuth(db, config, {
692
748
  nodeState: schema.nodeState,
693
749
  nodeId: schema.nodeId,
694
750
  })
695
751
  const deliverySettings = resolveDeliveryApiSettings(config.deliveryApi)
752
+ const caching = resolveCacheSettings(config.cache)
753
+ const formCors = corsPolicy(deliverySettings)
696
754
  const deliveryPrefix = DELIVERY_API_PREFIX
697
755
  const deliveryMembers = createDeliveryMemberSecurity({
698
756
  db,
@@ -701,18 +759,98 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
701
759
  })
702
760
  for (const problem of deliveryMembers.problems)
703
761
  log.warning('Delivery API: {problem}', { problem })
762
+ for (const problem of previewProblems(deliverySettings))
763
+ log.warning('Delivery API: {problem}', { problem })
764
+
765
+ // Preview tokens (story 053): an app in the browser reads drafts for the
766
+ // editor who pressed Preview, checked again on every request.
767
+ const previewSecret = await previewSigningSecret(db)
768
+ const previewEditor = async (token: string): Promise<Principal | undefined> => {
769
+ const claims = readPreviewToken(previewSecret, token)
770
+ if (!claims) return undefined
771
+ const standing = await previewUser(db, { id: claims.user })
772
+ if (standing?.stamp !== claims.stamp) return undefined
773
+ const identity = await auth.identityOf(claims.user)
774
+ return identity && principalFrom(identity)
775
+ }
776
+
777
+ /** Where a page previews in the app, with a token for this editor in the address. */
778
+ async function previewInApp(
779
+ key: string,
780
+ culture: string | null,
781
+ principal: Principal,
782
+ ): Promise<{ url: string } | { message: string }> {
783
+ const page = await (await draftCache()).byKey(key, culture)
784
+ if (!page) return { message: 'Save the page, then preview it in the app.' }
785
+ const template = previewUrlFor(deliverySettings, page.contentType.alias)
786
+ if (!template)
787
+ return {
788
+ message:
789
+ 'Pages of this type have no preview address in the app. Ask an administrator to add one.',
790
+ }
791
+ const standing = await previewUser(db, { key: principal.id })
792
+ if (!standing) return { message: 'Sign in again, then preview the page.' }
793
+ const token = signPreviewToken(previewSecret, {
794
+ user: standing.id,
795
+ stamp: standing.stamp,
796
+ expires: Date.now() + deliverySettings.preview.tokenMinutes * 60_000,
797
+ })
798
+ const path = /^https?:\/\//i.test(page.url) ? new URL(page.url).pathname : page.url
799
+ return { url: fillPreviewUrl(template, { path, id: key, culture, token }) }
800
+ }
801
+ const appPreview =
802
+ deliverySettings.enabled && previewsInApp(deliverySettings) ? previewInApp : undefined
803
+
704
804
  const deliveryApi =
705
805
  config.role === 'api'
706
806
  ? undefined
707
807
  : createDeliveryApi({
708
808
  settings: deliverySettings,
709
809
  cache,
810
+ caching,
710
811
  prefix: deliveryPrefix,
812
+ // Asked only at request time, by which point the SEO host below exists.
813
+ seo: async (content, request) => ({ ...(await seo.details(content, request)) }),
814
+ forms: {
815
+ // By key, or by alias, which is what an app is likelier to know.
816
+ byKey: (key) => forms.byKey(key) ?? forms.all().find((form) => form.alias === key),
817
+ shaper: async (culture, request) => {
818
+ const tools = await cache.formTools(culture)
819
+ const now = Date.now()
820
+ // Submissions go to the CMS, wherever the app that draws the form is.
821
+ const origin = originOf(request, config)
822
+ return (form) =>
823
+ apiForm(tools.resolve(form), {
824
+ types: formTypes.types,
825
+ action: `${origin}${formAction(form)}`,
826
+ token: signFormToken(formSecret, form.key ?? form.alias, now),
827
+ renderedAt: now,
828
+ redirectUrl: form.redirectTo ? tools.urlOf(form.redirectTo) : undefined,
829
+ })
830
+ },
831
+ },
832
+ sitemap: (request, host) => seo.sitemapItems(request, host),
833
+ notFound: async (host, path) => {
834
+ const found = await seo.notFound(host, path)
835
+ return found && { key: found.content.key, culture: found.culture }
836
+ },
837
+ preview: async (request, keyed) => {
838
+ if (keyed) return { cache: await draftCache() }
839
+ const token = request.headers.get('preview-token')
840
+ const editor = token ? await previewEditor(token) : undefined
841
+ if (!editor) return undefined
842
+ return {
843
+ cache: await draftCache(),
844
+ mayRead: (chain) => canReadDocumentAt(editor, chain),
845
+ }
846
+ },
711
847
  protection: () => new PublicAccessRepository(db).allRules(),
712
848
  member: (token) => deliveryMembers.member(token),
713
849
  security: (request, action) => deliveryMembers.handle(request, action),
714
850
  search: (term, options) => new SiteSearch(db).query(term, options),
715
851
  })
852
+ for (const problem of deliveryApi?.problems ?? [])
853
+ log.warning('Delivery API: {problem}', { problem })
716
854
 
717
855
  const nodeLookup = createNodeLookup(db)
718
856
 
@@ -796,13 +934,29 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
796
934
  }
797
935
  : undefined,
798
936
  })
937
+ /**
938
+ * What an open backoffice hears of a change: the event hub drops its cached
939
+ * copy, whatever was queued gets indexed now, and an open preview reloads.
940
+ * Called only once requests are served, by which time the hubs below exist.
941
+ */
942
+ function announce(event: ServerEvent): void {
943
+ events.broadcast('notify', [event])
944
+ jobs.kickSearchIndexing()
945
+ if (event.eventSource === 'Umbraco:CMS:Document' && event.eventType !== 'Deleted')
946
+ previewHub.broadcast('refreshed', [event.key])
947
+ }
948
+ // Document writes announce themselves through this, from every entry point (story 170).
949
+ const contentEvents = createContentEventSink({ db, webhooks, notifier, live: announce })
950
+
799
951
  const managementDeps = createDeps({
800
952
  config,
801
953
  paths,
802
954
  extensions,
803
955
  db,
804
956
  webhooks,
957
+ contentEvents,
805
958
  cache,
959
+ previewInApp: appPreview,
806
960
  schema,
807
961
  mediaFiles,
808
962
  email,
@@ -848,14 +1002,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
848
1002
  onContentChange: (change, principal) => {
849
1003
  void notifier.raise(change, principal ? { key: principal.id, name: principal.name } : null)
850
1004
  },
851
- onServerEvent: (event) => {
852
- events.broadcast('notify', [event])
853
- // Saves, deletes and moves all announce themselves; whatever they queued gets indexed now.
854
- jobs.kickSearchIndexing()
855
- // An open preview of the document reloads when it changes.
856
- if (event.eventSource === 'Umbraco:CMS:Document' && event.eventType !== 'Deleted')
857
- previewHub.broadcast('refreshed', [event.key])
858
- },
1005
+ onServerEvent: announce,
859
1006
  })
860
1007
 
861
1008
  // Fixed by the contract and the client's SDK, wherever the editor is mounted.
@@ -894,6 +1041,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
894
1041
  db,
895
1042
  cache,
896
1043
  approvals: managementDeps.approvals as Approvals | undefined,
1044
+ operations: managementDeps.documentOperations,
897
1045
  nodeState: schema.nodeState,
898
1046
  nodeId: schema.nodeId,
899
1047
  versionCleanup: config.versionCleanup,
@@ -910,6 +1058,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
910
1058
  nodeState: schema.nodeState,
911
1059
  nodeId: schema.nodeId,
912
1060
  onContentChanged: () => cache.invalidate(),
1061
+ operations: managementDeps.documentOperations,
913
1062
  bundleWorkflows: formTypes.workflows,
914
1063
  renderEmail: (alias, props) => renderer.renderEmail(alias, props),
915
1064
  site: async () => ({
@@ -1064,10 +1213,14 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1064
1213
 
1065
1214
  // A visitor posting a form. Before the renderer, which would otherwise try
1066
1215
  // to resolve `/crombolo/forms/...` as a page.
1067
- if (pathname.startsWith(`${FORM_SUBMIT_PATH}/`))
1216
+ // An app on another origin posts here too (story 056), on the Delivery API's origins.
1217
+ if (pathname.startsWith(`${FORM_SUBMIT_PATH}/`)) {
1218
+ if (isPreflight(request) && formCors.origins.size + (formCors.any ? 1 : 0) > 0)
1219
+ return preflightResponse(formCors, request, 'POST')
1068
1220
  return request.method === 'POST'
1069
- ? submitFormRoute(request, pathname)
1221
+ ? withCors(formCors, request, await submitFormRoute(request, pathname))
1070
1222
  : new Response('Method Not Allowed', { status: 405, headers: { allow: 'POST' } })
1223
+ }
1071
1224
 
1072
1225
  // Not on an `api` node, which serves no public site to describe.
1073
1226
  if ((pathname === '/sitemap.xml' || pathname === '/robots.txt') && config.role !== 'api')
@@ -1898,9 +2051,21 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1898
2051
  async function serveMedia(pathname: string, search: URLSearchParams): Promise<Response> {
1899
2052
  // Media is what someone else uploaded, served from this origin, so a browser
1900
2053
  // must not guess a type the store did not give.
2054
+ // A file's bytes never change at its address — a replacement is placed in a
2055
+ // new folder — so it is kept for a year unless its media item or type says
2056
+ // otherwise (story 057). Resized images follow their original.
2057
+ const item = await cache.mediaAt(pathname)
2058
+ const chosen = item
2059
+ ? lifetimeFor(
2060
+ caching,
2061
+ { typeAlias: item.mediaType.alias, value: (alias) => item.value(alias) },
2062
+ { site: false },
2063
+ )
2064
+ : undefined
1901
2065
  const cacheable = {
1902
- 'cache-control': 'public, max-age=31536000, immutable',
2066
+ 'cache-control': cacheControl(chosen) ?? 'public, max-age=31536000, immutable',
1903
2067
  'x-content-type-options': 'nosniff',
2068
+ ...(caching.tagHeader && item ? { [caching.tagHeader]: item.key } : {}),
1904
2069
  }
1905
2070
  /**
1906
2071
  * `sandbox` for the types that carry script, which Umbraco's upload rules
@@ -1974,7 +2139,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1974
2139
  /** What every rendered page is told about the request and the site's search defaults. */
1975
2140
  async function pageRequest(request: Request) {
1976
2141
  return {
1977
- origin: originOf(request, config),
2142
+ origin: publicOrigin(request, config),
1978
2143
  url: request.url,
1979
2144
  seo: await seo.siteDefaults(),
1980
2145
  signal: request.signal,
@@ -2022,6 +2187,9 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2022
2187
  // The page it was sent from names the culture; the keys a source offers
2023
2188
  // are the same in every culture, so only the stored labels depend on it.
2024
2189
  resolveForm: async (form) => {
2190
+ // An app says which language it drew the form in; a page's address says it otherwise.
2191
+ const asked = requestedCulture(request.headers.get('accept-language'))
2192
+ if (asked && (await cache.hasCulture(asked))) return cache.resolveForm(form, asked)
2025
2193
  const referer = request.headers.get('referer')
2026
2194
  let culture: string | null = null
2027
2195
  try {
@@ -2111,12 +2279,19 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2111
2279
  // cleared, so a reload shows the page rather than the thank-you again.
2112
2280
  const cookie = readCookie(request, FORM_FLASH_COOKIE)
2113
2281
  const submission = cookie ? readFlash(formSecret, cookie) : undefined
2282
+ // A page that is not the same for everyone is never kept: a member's, a
2283
+ // preview, a form's answer, or anything in a members-only branch — which a
2284
+ // visitor sees as the login page, at the same address.
2285
+ let personal = Boolean(preview || member || submission || cookie)
2114
2286
  const result =
2115
2287
  preview ??
2116
2288
  (await renderer.render(pathname, host, {
2117
2289
  member,
2118
2290
  submission,
2119
- access: (content) => members.decide(content, member),
2291
+ access: async (content) => {
2292
+ if ((await members.decide(content, undefined)).status !== 'allowed') personal = true
2293
+ return members.decide(content, member)
2294
+ },
2120
2295
  search: siteSearchFor(db, cache, member),
2121
2296
  ...(await pageRequest(request)),
2122
2297
  }))
@@ -2124,10 +2299,24 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2124
2299
  ? { 'set-cookie': expireCookie(FORM_FLASH_COOKIE, config.secureCookies) }
2125
2300
  : {}
2126
2301
  switch (result.status) {
2127
- case 'ok':
2128
- return new Response(result.html, {
2302
+ case 'ok': {
2303
+ const response = new Response(result.html, {
2129
2304
  headers: { 'content-type': 'text/html; charset=utf-8', ...cleared },
2130
2305
  })
2306
+ if (personal) {
2307
+ response.headers.set('cache-control', PRIVATE_NO_STORE)
2308
+ return response
2309
+ }
2310
+ const ancestors = (await cache.navigation(result.content.culture)).ancestors(result.content)
2311
+ return cacheable(request, response, result.html, {
2312
+ lifetime: lifetimeFor(caching, {
2313
+ typeAlias: result.content.contentType.alias,
2314
+ value: (alias) => result.content.value(alias),
2315
+ }),
2316
+ tags: [result.content.key, ...ancestors.map((a) => a.key)],
2317
+ tagHeader: caching.tagHeader,
2318
+ })
2319
+ }
2131
2320
  case 'redirect':
2132
2321
  // Umbraco's `umbracoRedirect` answers 302: the page may stop redirecting.
2133
2322
  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
  {