@crombolo/server 0.33.1 → 0.35.2

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
@@ -14,6 +14,7 @@ import {
14
14
  createDeliveryApi,
15
15
  fillPreviewUrl,
16
16
  isPreflight,
17
+ memberAuthorizationEnabled,
17
18
  preflightResponse,
18
19
  previewProblems,
19
20
  previewsInApp,
@@ -57,7 +58,7 @@ import {
57
58
  resolveStaticFile,
58
59
  serveStaticFile,
59
60
  } from '@crombolo/backoffice-host'
60
- import type { DocumentOperations } from '@crombolo/content'
61
+ import type { DocumentOperations, MediaOperations } from '@crombolo/content'
61
62
  import { servedContract } from '@crombolo/contracts'
62
63
  import {
63
64
  CHOICE_SOURCE_KINDS,
@@ -82,6 +83,8 @@ import {
82
83
  FormEntryRepository,
83
84
  FormWorkflowRepository,
84
85
  latestContentVersionId,
86
+ MediaAccessRepository,
87
+ MemberRepository,
85
88
  PublicAccessRepository,
86
89
  RedirectRepository,
87
90
  readLedger,
@@ -93,9 +96,13 @@ import {
93
96
  type WritesPaused,
94
97
  } from '@crombolo/data'
95
98
  import {
99
+ BUNDLE_SCRIPT,
100
+ BUNDLE_SCRIPT_PATH,
101
+ BUNDLE_SITE_PATH,
96
102
  cacheable,
97
103
  cacheControl,
98
104
  contentForNode,
105
+ DEFAULT_MEDIA_CACHE_MEGABYTES,
99
106
  DEVELOPMENT_LIMITS,
100
107
  FORM_SCRIPT,
101
108
  FORM_SCRIPT_PATH,
@@ -103,6 +110,7 @@ import {
103
110
  formAction,
104
111
  lifetimeFor,
105
112
  MEMBER_EXTERNAL_SIGN_IN_PATH,
113
+ MediaCache,
106
114
  PRIVATE_NO_STORE,
107
115
  PublishedCache,
108
116
  Renderer,
@@ -118,13 +126,29 @@ import type { Server } from 'bun'
118
126
  import { createNodeLookup, loadAccess } from './access.ts'
119
127
  import { createAuditHost, createAuditSink, pluginAuditPlan, recordAudit } from './adapters/audit.ts'
120
128
  import { readCreatedBundlePackage, writeCreatedBundlePackage } from './adapters/bundles.ts'
121
- import { createPublishedContentSource, loadDraftNode } from './adapters/documents.ts'
129
+ import {
130
+ createMediaSource,
131
+ createPublishedContentSource,
132
+ loadDraftNode,
133
+ } from './adapters/documents.ts'
122
134
  import type { Approvals } from './approvals.ts'
123
135
  import { handleApprovalsApi } from './approvals-api.ts'
124
136
  import { CommandError, installBundleContent } from './bundle-install.ts'
137
+ import {
138
+ type BundleMediaFactory,
139
+ createBundleMedia,
140
+ type ResolvedMediaFolder,
141
+ resolveBundleMediaFolders,
142
+ } from './bundle-media.ts'
125
143
  import { BUNDLES_CHANGED_EVENT, type BundleReload, createBundleReloader } from './bundle-reload.ts'
126
144
  import { bundleChains, bundleTablesReport } from './bundle-tables.ts'
127
- import { createBundleRedirects, createServerBundles, validateServerBundles } from './bundles.ts'
145
+ import {
146
+ type BundleMember,
147
+ bundleRouteGroups,
148
+ createBundleRedirects,
149
+ createServerBundles,
150
+ validateServerBundles,
151
+ } from './bundles.ts'
128
152
  import { busyResponse } from './busy.ts'
129
153
  import { listEmailTemplates } from './components.ts'
130
154
  import {
@@ -139,6 +163,7 @@ import { createContentEventSink } from './content-events.ts'
139
163
  import { createContentNotificationRunner, createContentNotifier } from './content-notifications.ts'
140
164
  import { answerContentQuery, contentQueryScope } from './content-query.ts'
141
165
  import { attachDatabase, bootstrapDatabase } from './database.ts'
166
+ import { createDeliveryMediaPort } from './delivery-media.ts'
142
167
  import { createDeliveryMemberSecurity } from './delivery-members.ts'
143
168
  import { createDiagnostics } from './diagnostics.ts'
144
169
  import { syncDomainsFile } from './domains.ts'
@@ -172,6 +197,7 @@ import { ImageProcessor, parseImagingQuery } from './imaging.ts'
172
197
  import { type BackgroundJobs, createBackgroundJobs } from './jobs.ts'
173
198
  import { configureLogging, logger } from './logging.ts'
174
199
  import { createMarketplace } from './marketplace.ts'
200
+ import { createMediaAccess } from './media-access.ts'
175
201
  import { MediaFileStore } from './media-files.ts'
176
202
  import { mediaStoreFromEnvironment } from './media-store.ts'
177
203
  import { createMemberAuth, MEMBER_ROUTE_PREFIX } from './member-auth.ts'
@@ -204,6 +230,7 @@ import {
204
230
  createBundleIdentityProviders,
205
231
  IdentityProviderOverrides,
206
232
  } from './identity-provider-overrides.ts'
233
+ import { callerAddress } from './rate-limit.ts'
207
234
  import { syncConfiguredRedirects } from './redirects.ts'
208
235
  import {
209
236
  bootSchema,
@@ -352,6 +379,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
352
379
  }
353
380
  // The content landed under a cache this process had already constructed.
354
381
  cache.invalidate()
382
+ mediaCache.clear()
355
383
  return { applied: true, runId: result.runId, message: 'Its content was applied.' }
356
384
  },
357
385
  })
@@ -364,7 +392,8 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
364
392
  // Bundles are checked before the database is touched, because a bundle that
365
393
  // owns tables is migrated at boot, and a bad declaration must not get that far.
366
394
  // On every role: a bundle's form types are needed wherever forms render and
367
- // submit. Its routes and tables stay with the nodes that serve the backoffice.
395
+ // submit, and its member and public routes wherever the site is served. Its
396
+ // tables are migrated only by the nodes that own the database.
368
397
  const bundlePackages = extensions.bundles().bundles
369
398
  const formTypes = formTypesOf(config)
370
399
  {
@@ -377,7 +406,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
377
406
  throw new Error(`The configured bundles cannot be mounted:\n- ${problems.join('\n- ')}`)
378
407
  }
379
408
  setFormFieldTypes(formTypes.types, formTypes.renderers)
380
- const chains = servesBackOffice ? bundleChains(config.bundles, bundlePackages) : []
409
+ const chains = bundleChains(config.bundles, bundlePackages)
381
410
  const { db, seededAdminPassword } = owns
382
411
  ? await bootstrapDatabase(config, chains)
383
412
  : await attachDatabase(config)
@@ -556,7 +585,13 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
556
585
  nodeState: schema.nodeState,
557
586
  nodeId: schema.nodeId,
558
587
  })
559
- const cacheOptions = { form: (key: string) => forms.byKey(key) }
588
+ // Media is cached apart from the pages (story 197), item by item within a
589
+ // budget, and shared by the published and draft caches: media has no drafts.
590
+ const mediaCache = new MediaCache(
591
+ createMediaSource(db, { nodeState: schema.nodeState, nodeId: schema.nodeId }),
592
+ { budgetBytes: (config.mediaCacheMegabytes ?? DEFAULT_MEDIA_CACHE_MEGABYTES) * 1024 * 1024 },
593
+ )
594
+ const cacheOptions = { form: (key: string) => forms.byKey(key), media: mediaCache }
560
595
  // Every page as last saved, for previewing in an app (story 053). Built on the
561
596
  // first preview after a change and dropped with the published cache, so a site
562
597
  // nobody previews never holds it. A save on another node announces nothing,
@@ -665,62 +700,153 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
665
700
  removed: domains.removed,
666
701
  })
667
702
  }
703
+ const deliverySettings = resolveDeliveryApiSettings(config.deliveryApi)
704
+ const formCors = corsPolicy(deliverySettings)
668
705
  /**
669
- * The server halves of the site's bundles, mounted only where the backoffice
670
- * is: these are backoffice endpoints, and a `web` node serves none of them.
706
+ * The server halves of the site's bundles. Back-office routes answer only
707
+ * where the backoffice is; member and public routes (story 186) wherever the
708
+ * site is served.
671
709
  *
672
710
  * Capabilities are built here, from what this node already holds, so a bundle
673
711
  * is handed a narrow interface rather than the database. A bad bundle fails the
674
712
  * boot — see `createServerBundles`.
675
713
  */
676
- const bundles = servesBackOffice
677
- ? createServerBundles({
678
- bundles: config.bundles,
679
- packages: bundlePackages,
680
- coreVersion: VERSION,
681
- tables: (bundle) => {
682
- const chain = chains.find((candidate) => candidate.id === bundle.id)
683
- return chain ? createTablesCapability(db, chain.compiled.schema) : undefined
684
- },
685
- pluginApiPath: `${paths.pluginPath}/api`,
686
- host: {
687
- redirects: createBundleRedirects({ db, cache }),
688
- documents: {
689
- url: async (key, culture) => {
690
- const content = await cache.byKey(key, culture ?? null)
691
- return content && content.url !== '#' ? content.url : undefined
714
+ const asBundleMember = (member: {
715
+ key: string
716
+ name: string
717
+ username: string
718
+ email: string
719
+ roles: string[]
720
+ }): BundleMember => ({
721
+ key: member.key,
722
+ name: member.name,
723
+ username: member.username,
724
+ email: member.email,
725
+ groups: member.roles,
726
+ })
727
+ // Story 198: media as the member, built at the first request, when the media
728
+ // operations and the store it writes through exist.
729
+ let bundleMedia: BundleMediaFactory | undefined
730
+ let bundleMediaFolders = new Map<string, ResolvedMediaFolder[]>()
731
+ const bundles =
732
+ config.bundles.length > 0
733
+ ? createServerBundles({
734
+ bundles: config.bundles,
735
+ packages: bundlePackages,
736
+ coreVersion: VERSION,
737
+ tables: (bundle) => {
738
+ const chain = chains.find((candidate) => candidate.id === bundle.id)
739
+ return chain ? createTablesCapability(db, chain.compiled.schema) : undefined
740
+ },
741
+ pluginApiPath: `${paths.pluginPath}/api`,
742
+ host: {
743
+ redirects: createBundleRedirects({ db, cache }),
744
+ documents: {
745
+ url: async (key, culture) => {
746
+ const content = await cache.byKey(key, culture ?? null)
747
+ return content && content.url !== '#' ? content.url : undefined
748
+ },
692
749
  },
750
+ log: bundleLog('bundle'),
751
+ identityProviders: createBundleIdentityProviders({
752
+ overrides: new IdentityProviderOverrides(db, config.secretKey),
753
+ members: config.memberIdentityProviders,
754
+ backoffice: config.backofficeIdentityProviders,
755
+ memberCallbackPath: MEMBER_EXTERNAL_SIGN_IN_PATH,
756
+ backofficeCallbackPath: BACKOFFICE_EXTERNAL_PATH,
757
+ groups: async (audience) =>
758
+ audience === 'user'
759
+ ? (await new UserGroupRepository(db).all()).map((g) => ({
760
+ value: g.alias,
761
+ name: g.name,
762
+ }))
763
+ : (
764
+ await db.query<{ text: string }>(
765
+ 'SELECT text FROM node WHERE node_object_type = ? ORDER BY text',
766
+ [ObjectTypes.MemberGroup],
767
+ )
768
+ ).map((g) => ({ value: String(g.text), name: String(g.text) })),
769
+ }),
693
770
  },
694
- log: bundleLog('bundle'),
695
- identityProviders: createBundleIdentityProviders({
696
- overrides: new IdentityProviderOverrides(db, config.secretKey),
697
- members: config.memberIdentityProviders,
698
- backoffice: config.backofficeIdentityProviders,
699
- memberCallbackPath: MEMBER_EXTERNAL_SIGN_IN_PATH,
700
- backofficeCallbackPath: BACKOFFICE_EXTERNAL_PATH,
701
- groups: async (audience) =>
702
- audience === 'user'
703
- ? (await new UserGroupRepository(db).all()).map((g) => ({
704
- value: g.alias,
705
- name: g.name,
706
- }))
707
- : (
708
- await db.query<{ text: string }>(
709
- 'SELECT text FROM node WHERE node_object_type = ? ORDER BY text',
710
- [ObjectTypes.MemberGroup],
711
- )
712
- ).map((g) => ({ value: String(g.text), name: String(g.text) })),
713
- }),
714
- },
715
- log: (id) => bundleLog(id),
771
+ log: (id) => bundleLog(id),
772
+ callerHost: {
773
+ media: (caller, bundle) => {
774
+ bundleMedia ??= createBundleMedia({
775
+ db,
776
+ operations: managementDeps.mediaOperations as MediaOperations,
777
+ files: mediaFiles,
778
+ cache: mediaCache,
779
+ folders: (id) => bundleMediaFolders.get(id) ?? [],
780
+ bundleName: (id) => bundles?.mounted.find((b) => b.id === id)?.name ?? id,
781
+ stream: (src, search) => streamMemberFile(src, search),
782
+ })
783
+ return bundleMedia(caller, bundle)
784
+ },
785
+ },
786
+ site: {
787
+ session: async (request) => {
788
+ const session = await members.session(request)
789
+ return session && { member: asBundleMember(session.member), verify: session.verify }
790
+ },
791
+ memberByToken: memberAuthorizationEnabled(deliverySettings)
792
+ ? async (token) => {
793
+ const named = await deliveryMembers.member(token)
794
+ if (!named?.approved || named.lockedOut) return undefined
795
+ const member = await new MemberRepository(db).byKey(named.key)
796
+ return member && asBundleMember(member)
797
+ }
798
+ : undefined,
799
+ cors: formCors,
800
+ callerAddress: (request) =>
801
+ callerAddress(peers.get(request), request.headers.get('x-forwarded-for')),
802
+ },
803
+ })
804
+ : undefined
805
+ if (bundles) {
806
+ // A declared folder that is not there would fail on the first upload; the
807
+ // boot says so instead, naming the bundle and the path.
808
+ const names = new Map(bundles.mounted.map((bundle) => [bundle.id, bundle.name]))
809
+ const resolved = await resolveBundleMediaFolders(
810
+ db,
811
+ config.bundles,
812
+ (id) => names.get(id) ?? id,
813
+ )
814
+ if (resolved.problems.length > 0)
815
+ throw new Error(
816
+ `The configured bundles cannot be mounted:\n- ${resolved.problems.join('\n- ')}`,
817
+ )
818
+ bundleMediaFolders = resolved.folders
819
+ }
820
+ for (const bundle of bundles?.mounted ?? []) {
821
+ if (servesBackOffice)
822
+ log.info('Bundle {name} answering below {prefix} for the {section} section', {
823
+ name: bundle.name,
824
+ prefix: bundle.prefix,
825
+ section: bundle.section,
716
826
  })
717
- : undefined
718
- for (const bundle of bundles?.mounted ?? [])
719
- log.info('Bundle {name} answering below {prefix} for the {section} section', {
720
- name: bundle.name,
721
- prefix: bundle.prefix,
722
- section: bundle.section,
723
- })
827
+ if (config.role !== 'api' && bundle.routes.some((route) => route.audience !== 'backoffice'))
828
+ log.info('Bundle {name} answering members and visitors below {prefix}', {
829
+ name: bundle.name,
830
+ prefix: bundle.sitePrefix,
831
+ })
832
+ }
833
+ {
834
+ const named = bundleRouteGroups(config.bundles)
835
+ if (named.length > 0) {
836
+ const existing = new Set(
837
+ (
838
+ await db.query<{ text: string }>('SELECT text FROM node WHERE node_object_type = ?', [
839
+ ObjectTypes.MemberGroup,
840
+ ])
841
+ ).map((row) => String(row.text).toLowerCase()),
842
+ )
843
+ for (const group of named.filter((name) => !existing.has(name.toLowerCase())))
844
+ log.warning(
845
+ 'A bundle route is limited to the member group {group}, which does not exist, so no member can call it yet',
846
+ { group },
847
+ )
848
+ }
849
+ }
724
850
  for (const name of unknownHostProvided(config))
725
851
  log.warning(
726
852
  '{name} is listed as host-provided but is not installed here; exports leave it out regardless',
@@ -745,6 +871,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
745
871
  // read, so an idle node catches up and says so (story 174).
746
872
  content: {
747
873
  served: () => cache.served(),
874
+ covered: (checkpoint) => cache.covered(checkpoint),
748
875
  behind: () => {
749
876
  cache.invalidate()
750
877
  void cache
@@ -754,6 +881,10 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
754
881
  )
755
882
  },
756
883
  },
884
+ media: {
885
+ apply: (change) => mediaCache.apply(change),
886
+ clear: () => mediaCache.clear(),
887
+ },
757
888
  })
758
889
  await poller.start(config.development ? 2_000 : 5_000)
759
890
  const watcher =
@@ -764,6 +895,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
764
895
  { nodeId: schema.nodeId, revision: config.schemaRevision },
765
896
  (report: SyncReport) => {
766
897
  cache.invalidate()
898
+ mediaCache.clear()
767
899
  void afterSync(report).catch((error: unknown) =>
768
900
  schemaLog.error('Recording redirects after an address change failed: {error}', {
769
901
  error: String(error),
@@ -789,14 +921,20 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
789
921
  },
790
922
  )
791
923
  : undefined
792
- const remote = createRemote({ db, config, authenticate, onApplied: () => cache.invalidate() })
924
+ const remote = createRemote({
925
+ db,
926
+ config,
927
+ authenticate,
928
+ onApplied: () => {
929
+ cache.invalidate()
930
+ mediaCache.clear()
931
+ },
932
+ })
793
933
  const members = createMemberAuth(db, config, {
794
934
  nodeState: schema.nodeState,
795
935
  nodeId: schema.nodeId,
796
936
  })
797
- const deliverySettings = resolveDeliveryApiSettings(config.deliveryApi)
798
937
  const caching = resolveCacheSettings(config.cache)
799
- const formCors = corsPolicy(deliverySettings)
800
938
  const deliveryPrefix = DELIVERY_API_PREFIX
801
939
  const deliveryMembers = createDeliveryMemberSecurity({
802
940
  db,
@@ -805,6 +943,33 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
805
943
  })
806
944
  for (const problem of deliveryMembers.problems)
807
945
  log.warning('Delivery API: {problem}', { problem })
946
+ // Story 196: who may read a protected media file, and the back office's permissions for media.
947
+ const mediaAccess = createMediaAccess({
948
+ db,
949
+ member: async (request) => {
950
+ const member = await members.resolve(request)
951
+ return member && { key: member.key, groups: member.roles }
952
+ },
953
+ memberByToken: memberAuthorizationEnabled(deliverySettings)
954
+ ? async (token) => {
955
+ const member = await deliveryMembers.member(token)
956
+ return member?.approved && !member.lockedOut
957
+ ? { key: member.key, groups: member.groups }
958
+ : undefined
959
+ }
960
+ : undefined,
961
+ principal: (request) => authenticate(request),
962
+ onChange: (key) => mediaCache.drop([key]),
963
+ nodeId: schema.nodeId,
964
+ bundleFolders: () =>
965
+ [...bundleMediaFolders].flatMap(([id, folders]) =>
966
+ folders.map((folder) => ({
967
+ bundle: bundles?.mounted.find((b) => b.id === id)?.name ?? id,
968
+ nodePath: folder.nodePath,
969
+ })),
970
+ ),
971
+ })
972
+ const mediaAccessPath = `${paths.pluginPath}/api/media-access`
808
973
  for (const problem of previewProblems(deliverySettings))
809
974
  log.warning('Delivery API: {problem}', { problem })
810
975
 
@@ -892,6 +1057,8 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
892
1057
  },
893
1058
  protection: () => new PublicAccessRepository(db).allRules(),
894
1059
  member: (token) => deliveryMembers.member(token),
1060
+ mediaRules: () => new MediaAccessRepository(db).allRules(),
1061
+ media: createDeliveryMediaPort(db, mediaCache),
895
1062
  security: (request, action) => deliveryMembers.handle(request, action),
896
1063
  search: (term, options) => new SiteSearch(db).query(term, options),
897
1064
  })
@@ -968,6 +1135,12 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
968
1135
  const notifier = createContentNotifier(db, { canSend: Boolean(email) })
969
1136
  const mediaFiles = new MediaFileStore(mediaStore)
970
1137
  const images = new ImageProcessor(mediaStore)
1138
+ const publicMedia = mediaStore.publicUrl?.('media/file')
1139
+ if (publicMedia)
1140
+ log.warning(
1141
+ 'Media files are also served from {where}. Protected files are always sent by this site and never from there, but anyone with a file’s address there can open it: keep protected files in a store nothing public serves.',
1142
+ { where: publicMedia.replace(/media\/file$/, '') },
1143
+ )
971
1144
  const webhooks = createWebhookService({
972
1145
  db,
973
1146
  schemaDir: config.schemaDir,
@@ -1173,6 +1346,9 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1173
1346
  const auditPath = `${paths.pluginPath}/api/audit`
1174
1347
  const hostTokenPath = `${paths.pluginPath}/api/host-token`
1175
1348
  const contentQueryPath = `${paths.pluginPath}/api/content-query`
1349
+ const bundleInstallPaths = new Set(
1350
+ ['install', 'uninstall'].map((action) => `${paths.pluginPath}/api/bundles/${action}`),
1351
+ )
1176
1352
  /** Per node: ten a minute for each person, three hundred in all. */
1177
1353
  const hostTokens = new AttemptLimiter({ max: 10, maxAll: 300, windowMs: 60_000 })
1178
1354
  const auditHost = createAuditHost(db, config.auditRetentionDays)
@@ -1286,11 +1462,24 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1286
1462
  : new Response('Method Not Allowed', { status: 405, headers: { allow: 'POST' } })
1287
1463
  }
1288
1464
 
1465
+ // A bundle's member and public routes (story 186), wherever the site is served.
1466
+ if (config.role !== 'api') {
1467
+ if (pathname === BUNDLE_SCRIPT_PATH)
1468
+ return new Response(BUNDLE_SCRIPT, {
1469
+ headers: {
1470
+ 'content-type': 'text/javascript; charset=utf-8',
1471
+ 'cache-control': config.development ? 'no-cache' : 'public, max-age=3600',
1472
+ },
1473
+ })
1474
+ if (pathname.startsWith(`${BUNDLE_SITE_PATH}/`))
1475
+ return (await bundles?.site(request, url)) ?? new Response('Not Found', { status: 404 })
1476
+ }
1477
+
1289
1478
  // Not on an `api` node, which serves no public site to describe.
1290
1479
  if ((pathname === '/sitemap.xml' || pathname === '/robots.txt') && config.role !== 'api')
1291
1480
  return pathname === '/sitemap.xml' ? seo.sitemap(request, url.host) : seo.robots(request)
1292
1481
 
1293
- if (pathname.startsWith('/media/')) return serveMedia(pathname, url.searchParams)
1482
+ if (pathname.startsWith('/media/')) return serveMedia(request, pathname, url.searchParams)
1294
1483
  if (pathname.startsWith('/css/')) return serveSiteFile(config.stylesheetsDir, pathname, '.css')
1295
1484
  if (pathname.startsWith('/scripts/')) return serveSiteFile(config.scriptsDir, pathname, '.js')
1296
1485
  return renderSite(request, pathname, url.host)
@@ -1308,6 +1497,8 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1308
1497
  if (pathname === hostTokenPath) return
1309
1498
  // A content query is a POST that reads.
1310
1499
  if (pathname === contentQueryPath) return
1500
+ // Installs and removals write their own entry, with the package (story 194).
1501
+ if (bundleInstallPaths.has(pathname)) return
1311
1502
  const principal = await authenticate(request)
1312
1503
  if (!principal) return
1313
1504
  const plan = pluginAuditPlan(request.method, pathname.slice(prefix.length))
@@ -1353,6 +1544,18 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1353
1544
  if (response) return response
1354
1545
  }
1355
1546
 
1547
+ // Non-contract, Media: who may read and change a media folder or item (story 196).
1548
+ if (pathname.startsWith(`${mediaAccessPath}/`)) {
1549
+ const principal = await authenticate(request)
1550
+ if (!principal) return new Response('Unauthorized', { status: 401 })
1551
+ const response = await mediaAccess.handle(
1552
+ request,
1553
+ pathname.slice(mediaAccessPath.length),
1554
+ principal,
1555
+ )
1556
+ if (response) return response
1557
+ }
1558
+
1356
1559
  if (git && pathname.startsWith(`${gitPath}/`)) {
1357
1560
  const principal = await authenticate(request)
1358
1561
  if (!principal) return new Response('Unauthorized', { status: 401 })
@@ -1463,6 +1666,23 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1463
1666
  })
1464
1667
  }
1465
1668
 
1669
+ // A created bundle's package, downloaded from the Created view with or
1670
+ // without its media files (story 195), on the session cookie the
1671
+ // plugin's endpoints use rather than the contract's bearer token.
1672
+ const download = /^created\/([0-9a-f-]{36})\/download$/i.exec(action)
1673
+ if (download && request.method === 'GET') {
1674
+ const built = await managementDeps.packages?.build(download[1] as string, {
1675
+ withMedia: url.searchParams.get('withMedia') === 'true',
1676
+ })
1677
+ if (!built) return new Response('Not Found', { status: 404 })
1678
+ return new Response(built.bytes, {
1679
+ headers: {
1680
+ 'content-type': built.contentType,
1681
+ 'content-disposition': `attachment; filename="${built.fileName}"`,
1682
+ },
1683
+ })
1684
+ }
1685
+
1466
1686
  // A created bundle's npm name and version: not in Umbraco's definition, so
1467
1687
  // not in the contract, and set from the Created view beside it.
1468
1688
  const created = /^created\/([0-9a-f-]{36})\/package$/i.exec(action)
@@ -1492,13 +1712,16 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1492
1712
  name?: unknown
1493
1713
  version?: unknown
1494
1714
  applyContent?: unknown
1715
+ acceptServerCode?: unknown
1495
1716
  }
1496
1717
  const name = typeof body.name === 'string' ? body.name : ''
1497
1718
  const version = typeof body.version === 'string' ? body.version : undefined
1719
+ const acceptServerCode = body.acceptServerCode === true
1498
1720
  const outcome =
1499
1721
  action === 'install'
1500
1722
  ? await marketplace.install(name, version, {
1501
1723
  applyContent: body.applyContent !== false,
1724
+ acceptServerCode,
1502
1725
  })
1503
1726
  : await marketplace.uninstall(name)
1504
1727
  log.info('{user} {action} the package {name}: {outcome}', {
@@ -1507,6 +1730,20 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1507
1730
  name,
1508
1731
  outcome: outcome.ok ? 'ok' : outcome.message,
1509
1732
  })
1733
+ // One entry per install, naming the package and whether server code
1734
+ // was accepted (story 194); the generic plugin-write entry skips these.
1735
+ if (outcome.ok)
1736
+ await recordAudit(db, {
1737
+ category: 'system',
1738
+ action: action === 'install' ? 'Install' : 'Uninstall',
1739
+ entityType: 'Bundle',
1740
+ entityName: outcome.dependency ? `${name}@${outcome.dependency.version}` : name,
1741
+ detail: action === 'install' && acceptServerCode ? 'accepted server code' : null,
1742
+ source: 'request',
1743
+ userKey: principal.id,
1744
+ userName: principal.name,
1745
+ ...clientAddress(request),
1746
+ })
1510
1747
  return Response.json(outcome, { status: outcome.ok ? 200 : 400 })
1511
1748
  }
1512
1749
 
@@ -1939,7 +2176,10 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1939
2176
  db,
1940
2177
  config,
1941
2178
  user: principal.email,
1942
- onApplied: () => cache.invalidate(),
2179
+ onApplied: () => {
2180
+ cache.invalidate()
2181
+ mediaCache.clear()
2182
+ },
1943
2183
  })
1944
2184
  if (response) {
1945
2185
  if (request.method === 'POST')
@@ -2140,17 +2380,37 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2140
2380
  * An uploaded file from the media store; an image with a resize or crop query
2141
2381
  * is served as that variant, computed once and cached in the store.
2142
2382
  *
2143
- * A store that serves its own bytes (a CDN, a presigned bucket URL) gets the
2144
- * browser sent straight there. Otherwise this streams them — from the local
2145
- * file when there is one, so a disk-backed site still gets sendfile.
2383
+ * Only a file something owns is served (story 196): a media item, found
2384
+ * through its indexed `file_url`, or a page's upload value (`node_file`). A protected one, and its crops, go only to someone who
2385
+ * may read it, streamed by this server and kept by nobody; anyone else gets
2386
+ * 404, so a guessed or shared address does not say the file exists.
2387
+ *
2388
+ * An open file whose store serves its own bytes (a CDN, a presigned bucket
2389
+ * URL) gets the browser sent straight there. Otherwise this streams them —
2390
+ * from the local file when there is one, so a disk-backed site still gets
2391
+ * sendfile.
2146
2392
  */
2147
- async function serveMedia(pathname: string, search: URLSearchParams): Promise<Response> {
2393
+ async function serveMedia(
2394
+ request: Request,
2395
+ pathname: string,
2396
+ search: URLSearchParams,
2397
+ ): Promise<Response> {
2398
+ const key = mediaFiles.key(pathname)
2399
+ if (!key) return new Response('Not Found', { status: 404 })
2400
+ const owners = new MediaAccessRepository(db)
2401
+ const urls = [`/media/${key}`, pathname]
2402
+ const owner = await owners.byUrl(urls)
2403
+ if (!owner && !(await owners.ownedElsewhere(urls)))
2404
+ return new Response('Not Found', { status: 404 })
2405
+ const isProtected = owner ? mediaAccess.isProtected(owner) : false
2406
+ if (owner && isProtected && !(await mediaAccess.mayRead(request, owner)))
2407
+ return new Response('Not Found', { status: 404 })
2148
2408
  // Media is what someone else uploaded, served from this origin, so a browser
2149
2409
  // must not guess a type the store did not give.
2150
2410
  // A file's bytes never change at its address — a replacement is placed in a
2151
2411
  // new folder — so it is kept for a year unless its media item or type says
2152
2412
  // otherwise (story 057). Resized images follow their original.
2153
- const item = await cache.mediaAt(pathname)
2413
+ const item = isProtected || !owner ? undefined : await mediaCache.byKey(owner.key)
2154
2414
  const chosen = item
2155
2415
  ? lifetimeFor(
2156
2416
  caching,
@@ -2159,7 +2419,9 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2159
2419
  )
2160
2420
  : undefined
2161
2421
  const cacheable = {
2162
- 'cache-control': cacheControl(chosen) ?? 'public, max-age=31536000, immutable',
2422
+ 'cache-control': isProtected
2423
+ ? PRIVATE_NO_STORE
2424
+ : (cacheControl(chosen) ?? 'public, max-age=31536000, immutable'),
2163
2425
  'x-content-type-options': 'nosniff',
2164
2426
  ...(caching.tagHeader && item ? { [caching.tagHeader]: item.key } : {}),
2165
2427
  }
@@ -2177,20 +2439,21 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2177
2439
  ? { ...cacheable, 'content-security-policy': 'sandbox' }
2178
2440
  : cacheable
2179
2441
  // A prefix may be a path on this host as well as an absolute URL, and
2180
- // Response.redirect insists on the latter.
2442
+ // Response.redirect insists on the latter. A protected file is never sent
2443
+ // elsewhere, where nobody would check who asked.
2444
+ const elsewhereFor = (storeKey: string) =>
2445
+ isProtected ? undefined : mediaStore.publicUrl?.(storeKey)
2181
2446
  const sendTo = (location: string) =>
2182
2447
  new Response(null, { status: 302, headers: { location, ...cacheable } })
2183
- const key = mediaFiles.key(pathname)
2184
- if (!key) return new Response('Not Found', { status: 404 })
2185
- const request = parseImagingQuery(search)
2448
+ const imaging = parseImagingQuery(search)
2186
2449
  const extension = key.split('.').pop()?.toLowerCase() ?? ''
2187
2450
 
2188
- if (request && DEFAULT_UPLOAD_SETTINGS.imageFileTypes.includes(extension)) {
2451
+ if (imaging && DEFAULT_UPLOAD_SETTINGS.imageFileTypes.includes(extension)) {
2189
2452
  const source = await mediaStore.get(key)
2190
2453
  if (source) {
2191
2454
  try {
2192
- const variant = await images.variant(source, request)
2193
- const elsewhere = mediaStore.publicUrl?.(variant.key)
2455
+ const variant = await images.variant(source, imaging)
2456
+ const elsewhere = elsewhereFor(variant.key)
2194
2457
  if (elsewhere) return sendTo(elsewhere)
2195
2458
  return new Response(variant.bytes as Uint8Array<ArrayBuffer>, {
2196
2459
  headers: { ...cacheable, 'content-type': variant.contentType },
@@ -2201,7 +2464,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2201
2464
  }
2202
2465
  }
2203
2466
 
2204
- const elsewhere = mediaStore.publicUrl?.(key)
2467
+ const elsewhere = elsewhereFor(key)
2205
2468
  if (elsewhere) return sendTo(elsewhere)
2206
2469
  const stored = await mediaStore.get(key)
2207
2470
  if (!stored) return new Response('Not Found', { status: 404 })
@@ -2210,6 +2473,37 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2210
2473
  return new Response((await stored.bytes()) as Uint8Array<ArrayBuffer>, { headers })
2211
2474
  }
2212
2475
 
2476
+ /**
2477
+ * A media file, or a variant of an image, sent to someone the media
2478
+ * capability has already let read it (story 198): streamed by this server
2479
+ * and kept by nobody, as a protected file is.
2480
+ */
2481
+ async function streamMemberFile(src: string, search: URLSearchParams): Promise<Response> {
2482
+ const key = mediaFiles.key(src)
2483
+ const source = key ? await mediaStore.get(key) : undefined
2484
+ if (!key || !source)
2485
+ return new Response('Not Found', {
2486
+ status: 404,
2487
+ headers: { 'cache-control': PRIVATE_NO_STORE },
2488
+ })
2489
+ const headers = { 'cache-control': PRIVATE_NO_STORE, 'x-content-type-options': 'nosniff' }
2490
+ const imaging = parseImagingQuery(search)
2491
+ const extension = key.split('.').pop()?.toLowerCase() ?? ''
2492
+ if (imaging && DEFAULT_UPLOAD_SETTINGS.imageFileTypes.includes(extension)) {
2493
+ try {
2494
+ const variant = await images.variant(source, imaging)
2495
+ return new Response(variant.bytes as Uint8Array<ArrayBuffer>, {
2496
+ headers: { ...headers, 'content-type': variant.contentType },
2497
+ })
2498
+ } catch (error) {
2499
+ log.error('Could not process image {path}', { path: src, error })
2500
+ }
2501
+ }
2502
+ return new Response((await source.bytes()) as Uint8Array<ArrayBuffer>, {
2503
+ headers: { ...headers, 'content-type': source.contentType },
2504
+ })
2505
+ }
2506
+
2213
2507
  /**
2214
2508
  * Preview: a signed-in editor with the preview cookie sees drafts. The
2215
2509
  * backoffice's preview app frames `/<document key>`; a routed URL renders the
@@ -2372,7 +2666,8 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2372
2666
  status: 404,
2373
2667
  headers: { 'content-type': 'text/plain; charset=utf-8' },
2374
2668
  })
2375
- const member = preview ? undefined : await members.resolve(request)
2669
+ const session = preview ? undefined : await members.session(request)
2670
+ const member = session?.member
2376
2671
  // What a submission redirected back with, if anything. Read once and
2377
2672
  // cleared, so a reload shows the page rather than the thank-you again.
2378
2673
  const cookie = readCookie(request, FORM_FLASH_COOKIE)
@@ -2385,6 +2680,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2385
2680
  preview ??
2386
2681
  (await renderer.render(pathname, host, {
2387
2682
  member,
2683
+ antiforgery: session?.antiforgery,
2388
2684
  submission,
2389
2685
  access: async (content) => {
2390
2686
  if ((await members.decide(content, undefined)).status !== 'allowed') personal = true