@crombolo/server 0.37.0 → 0.38.1

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.
Files changed (79) hide show
  1. package/package.json +15 -14
  2. package/src/access.ts +29 -27
  3. package/src/adapters/audit.ts +1 -1
  4. package/src/adapters/blueprints.ts +22 -13
  5. package/src/adapters/content.ts +1 -1
  6. package/src/adapters/dictionary.ts +1 -1
  7. package/src/adapters/documents.ts +17 -10
  8. package/src/adapters/elements.ts +47 -37
  9. package/src/adapters/file-system.ts +1 -1
  10. package/src/adapters/health.ts +10 -5
  11. package/src/adapters/media.ts +12 -8
  12. package/src/adapters/member-groups.ts +8 -6
  13. package/src/adapters/members.ts +6 -4
  14. package/src/adapters/public-access.ts +7 -5
  15. package/src/adapters/redirects.ts +1 -1
  16. package/src/adapters/references.ts +1 -1
  17. package/src/adapters/relations.ts +1 -1
  18. package/src/adapters/schema-files.ts +33 -1
  19. package/src/adapters/search-index.ts +1 -1
  20. package/src/adapters/template-query.ts +1 -1
  21. package/src/adapters/users.ts +13 -13
  22. package/src/adapters/webhooks.ts +1 -1
  23. package/src/anonymise-rules.ts +83 -0
  24. package/src/approvals-api.ts +1 -1
  25. package/src/approvals.ts +75 -38
  26. package/src/back-office-url.ts +20 -0
  27. package/src/backup.ts +26 -2
  28. package/src/bundle-code.ts +1 -1
  29. package/src/bundle-grants.ts +265 -0
  30. package/src/bundle-install.ts +13 -2
  31. package/src/bundle-media.ts +12 -11
  32. package/src/bundles.ts +126 -43
  33. package/src/component-snippets.ts +1 -1
  34. package/src/components.ts +6 -1
  35. package/src/config.ts +61 -3
  36. package/src/content-notifications.ts +13 -9
  37. package/src/content-operations.ts +23 -65
  38. package/src/content-query.ts +1 -1
  39. package/src/core.ts +663 -0
  40. package/src/cron.ts +139 -0
  41. package/src/custom-tables.ts +274 -0
  42. package/src/database.ts +22 -14
  43. package/src/dictionary-transfer.ts +1 -1
  44. package/src/git-routes.ts +1 -1
  45. package/src/identity-provider-overrides.ts +18 -16
  46. package/src/imaging.ts +65 -15
  47. package/src/index.ts +10 -1
  48. package/src/job-wake.ts +23 -0
  49. package/src/live-reload.ts +195 -0
  50. package/src/log-viewer.ts +6 -1
  51. package/src/marketplace.ts +82 -10
  52. package/src/media-access.ts +12 -9
  53. package/src/member-auth.ts +6 -4
  54. package/src/models-builder.ts +1 -1
  55. package/src/node-operations.ts +122 -0
  56. package/src/owner-jobs.ts +428 -0
  57. package/src/ports.ts +36 -154
  58. package/src/preview-tokens.ts +6 -12
  59. package/src/remote.ts +3 -1
  60. package/src/schema.ts +8 -3
  61. package/src/seed/compile.ts +7 -5
  62. package/src/seed/export.ts +6 -4
  63. package/src/seo.ts +2 -2
  64. package/src/server.ts +333 -452
  65. package/src/settings.ts +18 -2
  66. package/src/site-data.ts +195 -0
  67. package/src/site-file.ts +30 -4
  68. package/src/site-queries.ts +140 -0
  69. package/src/site-replace.ts +25 -19
  70. package/src/site-sections.ts +1 -1
  71. package/src/site-services.ts +23 -6
  72. package/src/status-pages.ts +19 -5
  73. package/src/status.ts +11 -9
  74. package/src/url-settings.ts +1 -2
  75. package/src/webhook-files.ts +1 -1
  76. package/src/webhooks.ts +31 -23
  77. package/src/worker-watch.ts +73 -0
  78. package/src/worker.ts +138 -0
  79. package/src/bundle-tables.ts +0 -161
package/src/ports.ts CHANGED
@@ -22,15 +22,7 @@ import {
22
22
  type ExtensionRegistry,
23
23
  toResponseModels,
24
24
  } from '@crombolo/backoffice-host'
25
- import {
26
- type ApprovalsGate,
27
- type ContentPrincipal,
28
- createDocumentOperations,
29
- createMediaOperations,
30
- type DocumentOperations,
31
- type EventSink,
32
- SILENT,
33
- } from '@crombolo/content'
25
+ import type { EventSink } from '@crombolo/content'
34
26
  import {
35
27
  CORE_SECTION_ALIASES,
36
28
  DEFAULT_UPLOAD_SETTINGS,
@@ -39,13 +31,11 @@ import {
39
31
  permissionsForPath,
40
32
  } from '@crombolo/core'
41
33
  import {
42
- appendCacheInstruction,
43
34
  ContentEventRepository,
44
35
  ContentTypeRepository,
45
36
  type Db,
46
37
  DynamicRootRepository,
47
38
  LanguageRepository,
48
- RedirectRepository,
49
39
  TagRepository,
50
40
  UserRepository,
51
41
  } from '@crombolo/data'
@@ -74,31 +64,27 @@ import { createReferencePort } from './adapters/references.ts'
74
64
  import { createRelationPort } from './adapters/relations.ts'
75
65
  import {
76
66
  createSchemaFileWriter,
77
- type SchemaFiles,
78
67
  type SchemaFileWriter,
68
+ schemaFiles,
79
69
  } from './adapters/schema-files.ts'
80
70
  import { createSearchIndexPort } from './adapters/search-index.ts'
81
71
  import { createTemplateFileStore } from './adapters/template-files.ts'
82
72
  import { createTemplateQueryPort } from './adapters/template-query.ts'
83
73
  import { avatarUrls, createUserPorts } from './adapters/users.ts'
84
74
  import { createWebhookPort } from './adapters/webhooks.ts'
85
- import { type Approvals, createApprovals } from './approvals.ts'
75
+ import { backOfficeUrl } from './back-office-url.ts'
86
76
  import { COMPONENT_SNIPPETS } from './component-snippets.ts'
87
77
  import { type CromboloConfig, type UserLinkSender, VERSION } from './config.ts'
88
- import { createMediaEventSink } from './content-events.ts'
89
78
  import type { ContentNotifier } from './content-notifications.ts'
90
- import { writeDomainsFor } from './domains.ts'
91
79
  import { type EmailPort, resolveEmailPort } from './email.ts'
92
- import { createFileIntake, TemporaryFileMissingError } from './file-intake.ts'
93
- import { formTypesFor } from './form-types.ts'
80
+ import { createFileIntake } from './file-intake.ts'
94
81
  import { createLogViewerPort } from './log-viewer.ts'
95
82
  import { logger } from './logging.ts'
96
83
  import { MediaFileStore } from './media-files.ts'
97
84
  import { createModelsBuilderPort } from './models-builder.ts'
85
+ import { createNodeOperations, type NodeOperations } from './node-operations.ts'
98
86
  import { createOEmbedService } from './oembed.ts'
99
- import { createRedirectTracker } from './redirects.ts'
100
- import { componentAliasesIn, type SchemaBoot } from './schema.ts'
101
- import { publishSchema } from './schema-store.ts'
87
+ import type { SchemaBoot } from './schema.ts'
102
88
  import { TwoFactorService, USER_TWO_FACTOR_PROVIDER } from './two-factor.ts'
103
89
  import { createWebhookService, type WebhookService } from './webhooks.ts'
104
90
 
@@ -364,34 +350,6 @@ export function resolveUserLinkSender(
364
350
  return config.development ? logUserLink : undefined
365
351
  }
366
352
 
367
- /** Where the backoffice writes schema files, and whether it may. */
368
- export function schemaFiles(config: CromboloConfig): SchemaFiles {
369
- const store = config.schemaStore
370
- return {
371
- schemaDir: config.schemaDir,
372
- writable: config.schemaWritable,
373
- componentAliases: () => componentAliasesIn(config.componentsDir),
374
- formTypes: formTypesFor(config),
375
- // Only when a store is configured: a schema directory in a repository is
376
- // already where the files durably live.
377
- onChanged: store
378
- ? async () => {
379
- const report = await publishSchema(store, config.schemaDir)
380
- if (report.written.length > 0 || report.removed.length > 0) {
381
- logger('schema').info(
382
- 'Published schema to {store}: {written} written, {removed} removed',
383
- {
384
- store: store.description,
385
- written: report.written.length,
386
- removed: report.removed.length,
387
- },
388
- )
389
- }
390
- }
391
- : undefined,
392
- }
393
- }
394
-
395
353
  export interface DepsOptions {
396
354
  /** Published pages a site route answers in place of, for the health check (story 211). */
397
355
  hiddenByRoutes?: () => Promise<Array<{ route: string; owner: string; page: string; url: string }>>
@@ -430,24 +388,8 @@ export interface DepsOptions {
430
388
  onSearchQueued?: () => void
431
389
  /** Queues content notifications for changes made outside the router (story 045). */
432
390
  notifier?: ContentNotifier
433
- }
434
-
435
- /** The back office's address, e.g. `https://site.example/crombolo`; undefined when the site's own is not set. */
436
- export function backOfficeUrl(
437
- config: Pick<CromboloConfig, 'applicationUrl' | 'backOfficePath'>,
438
- ): string | undefined {
439
- return config.applicationUrl
440
- ? `${config.applicationUrl.replace(/\/$/, '')}${config.backOfficePath}`
441
- : undefined
442
- }
443
-
444
- /** A page's address in the back office, for a link in an e-mail. */
445
- export function documentEditUrl(
446
- config: Pick<CromboloConfig, 'applicationUrl' | 'backOfficePath'>,
447
- key: string,
448
- ): string | undefined {
449
- const base = backOfficeUrl(config)
450
- return base ? `${base}/section/content/workspace/document/edit/${key}` : undefined
391
+ /** The node's document and media operations, when it has built them already. */
392
+ operations?: NodeOperations
451
393
  }
452
394
 
453
395
  function createTemporaryFilePort(files: MediaFileStore): TemporaryFilePort {
@@ -496,7 +438,25 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
496
438
  const mediaFiles =
497
439
  options.mediaFiles ?? new MediaFileStore(options.config.mediaStore ?? options.config.mediaDir)
498
440
  deps.temporaryFiles = createTemporaryFilePort(mediaFiles)
499
- const valueIntake = createFileIntake(mediaFiles)
441
+ const operations =
442
+ options.operations ??
443
+ (options.db
444
+ ? createNodeOperations({
445
+ db: options.db,
446
+ config: options.config,
447
+ cache: options.cache,
448
+ nodeState: options.schema?.nodeState,
449
+ nodeId: options.schema?.nodeId,
450
+ mediaFiles,
451
+ email,
452
+ notifier: options.notifier,
453
+ contentEvents: options.contentEvents,
454
+ webhooks: options.webhooks,
455
+ nudgeEvents: options.nudgeEvents,
456
+ backOfficeUrl: backOfficeUrl(options.config),
457
+ })
458
+ : undefined)
459
+ const valueIntake = operations?.valueIntake ?? createFileIntake(mediaFiles)
500
460
  deps.oembed = createOEmbedService(options.fetch)
501
461
  // The whole components tree, which is one root with folders rather than
502
462
  // Umbraco's split of ~/Views and ~/Views/Partials. The backoffice reaches it
@@ -585,20 +545,7 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
585
545
  valueIntake,
586
546
  })
587
547
  // Every media write, whoever starts it (story 165).
588
- deps.mediaOperations = createMediaOperations({
589
- db: options.db,
590
- repository: {
591
- nodeState: options.schema?.nodeState,
592
- nodeId: options.schema?.nodeId,
593
- valueIntake,
594
- },
595
- events: createMediaEventSink({ webhooks: options.webhooks, nudge: options.nudgeEvents }),
596
- files: mediaFiles,
597
- // Only the items it touched: a media change leaves the pages alone (story 197).
598
- onChange: (change) => options.cache?.media?.apply(change),
599
- refusalReason: (error) =>
600
- error instanceof TemporaryFileMissingError ? error.message : undefined,
601
- })
548
+ deps.mediaOperations = operations?.media
602
549
  deps.blueprints = createBlueprintPort(options.db, {
603
550
  nodeState: options.schema?.nodeState,
604
551
  valueIntake,
@@ -683,7 +630,7 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
683
630
  rebuild: async () => {
684
631
  cache.invalidate()
685
632
  cache.media?.clear()
686
- await cache.snapshot()
633
+ await cache.fresh()
687
634
  },
688
635
  isRebuilding: () => false,
689
636
  }
@@ -692,21 +639,7 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
692
639
  onChange: () => options.cache?.invalidate(),
693
640
  nodeId: options.schema?.nodeId,
694
641
  })
695
- const db = options.db
696
- const tracker = options.cache
697
- ? createRedirectTracker({
698
- cache: options.cache,
699
- redirects: new RedirectRepository(db),
700
- enabled: options.config.trackRedirects,
701
- instruct: () =>
702
- appendCacheInstruction(db, {
703
- kind: 'content',
704
- payload: { redirects: true },
705
- by: options.schema?.nodeId,
706
- }),
707
- })
708
- : undefined
709
- if (options.cache)
642
+ if (operations && options.cache)
710
643
  deps.documents = createDocumentPort(
711
644
  options.db,
712
645
  options.cache,
@@ -715,50 +648,13 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
715
648
  nodeId: options.schema?.nodeId,
716
649
  valueIntake,
717
650
  },
718
- tracker,
651
+ operations.tracker,
719
652
  options.config.siteDir,
720
653
  Boolean(email),
721
654
  )
722
- if (deps.documents) {
723
- const db = options.db
724
- // Every document write, whoever starts it (story 170). Approvals publish
725
- // through it too, so what an approval publishes is cached, tracked and
726
- // announced as any publish is.
727
- let operations: DocumentOperations | undefined
728
- const approvals = createApprovals({
729
- db,
730
- nodeState: options.schema?.nodeState,
731
- email,
732
- backOfficeUrl: backOfficeUrl(options.config),
733
- notifier: options.notifier,
734
- publisher: {
735
- publish: (key, cultures, actor, approvedHead) =>
736
- (operations as DocumentOperations).publish(actor, key, {
737
- cultures,
738
- expectedHead: approvedHead,
739
- }),
740
- unpublish: (key, cultures, actor) =>
741
- (operations as DocumentOperations).unpublish(actor, key, cultures),
742
- },
743
- })
744
- deps.approvals = approvals
745
- operations = createDocumentOperations({
746
- db,
747
- repository: {
748
- nodeState: options.schema?.nodeState,
749
- nodeId: options.schema?.nodeId,
750
- valueIntake,
751
- },
752
- events: options.contentEvents ?? SILENT,
753
- approvals: approvalsGate(approvals),
754
- redirects: tracker,
755
- onChange: () => options.cache?.invalidate(),
756
- afterDomains: (node, assignment) =>
757
- writeDomainsFor(db, options.config.siteDir, node, assignment),
758
- refusalReason: (error) =>
759
- error instanceof TemporaryFileMissingError ? error.message : undefined,
760
- })
761
- deps.documentOperations = operations
655
+ if (deps.documents && operations) {
656
+ deps.approvals = operations.approvals
657
+ deps.documentOperations = operations.documents
762
658
  }
763
659
  }
764
660
  return deps
@@ -805,19 +701,5 @@ function userTwoFactorPort(service: TwoFactorService): UserTwoFactorPort {
805
701
  }
806
702
  }
807
703
 
808
- /**
809
- * The approval workflows as the document operations meet them. A user's principal
810
- * is the backoffice's own, passed straight through; a local operator has none.
811
- */
812
- export function approvalsGate(approvals: Approvals): ApprovalsGate {
813
- const as = (who: ContentPrincipal | undefined) => who as Principal | undefined
814
- return {
815
- publishRefusal: (who, key, action) => approvals.publishRefusal(as(who), key, action),
816
- branchRefusal: (who, key) => approvals.branchRefusal(as(who), key),
817
- newPageRefusal: (who, parentKey, typeKey) =>
818
- approvals.newPageRefusal(as(who), parentKey, typeKey),
819
- beforeSave: (who, key) => approvals.beforeSave(as(who), key),
820
- afterSave: (who, key) => approvals.afterSave(as(who), key),
821
- afterDirectPublish: (who, key, what) => approvals.afterDirectPublish(as(who), key, what),
822
- }
823
- }
704
+ export { schemaFiles } from './adapters/schema-files.ts'
705
+ export { backOfficeUrl, documentEditUrl } from './back-office-url.ts'
@@ -78,18 +78,12 @@ export async function previewUser(
78
78
  db: Db,
79
79
  where: { id: number } | { key: string },
80
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]
81
+ const row = await db.q
82
+ .selectFrom('user_account')
83
+ .select(['id', 'security_stamp', 'is_locked_out', 'is_approved'])
84
+ .$if('id' in where, (q) => q.where('id', '=', (where as { id: number }).id))
85
+ .$if(!('id' in where), (q) => q.where('key', '=', (where as { key: string }).key))
86
+ .executeTakeFirst()
93
87
  if (!row || fromDbBool(row.is_locked_out) || !fromDbBool(row.is_approved)) return undefined
94
88
  return { id: Number(row.id), stamp: stampDigest(row.security_stamp) }
95
89
  }
package/src/remote.ts CHANGED
@@ -15,7 +15,7 @@ import { createWriteStream } from 'node:fs'
15
15
  import { mkdir, rm } from 'node:fs/promises'
16
16
  import { tmpdir } from 'node:os'
17
17
  import { join, sep } from 'node:path'
18
- import { hasSection, type Principal } from '@crombolo/api-management'
18
+ import { hasSection, type Principal } from '@crombolo/api-management/domain'
19
19
  import { DEVICE_CODE_GRANT, REMOTE_CLIENT_ID } from '@crombolo/auth'
20
20
  import { managementApiPath, RemotePermissions, type RemoteVerb } from '@crombolo/core'
21
21
  import { AuditLog, auditRecord, type Db, type RemoteJob, RemoteJobRepository } from '@crombolo/data'
@@ -255,6 +255,8 @@ export function createRemote(options: RemoteOptions): Remote {
255
255
  anonymise: !full,
256
256
  withMembers: full,
257
257
  withUsers: full,
258
+ // Anonymised, it carries what the owners' rules allow.
259
+ withSiteData: true,
258
260
  sealContent: true,
259
261
  passphrase,
260
262
  })
package/src/schema.ts CHANGED
@@ -252,7 +252,8 @@ export interface CachePollerOptions {
252
252
  */
253
253
  content?: {
254
254
  served(): { checkpoint: number | undefined; builtAt: Date } | undefined
255
- behind(latest: number): void
255
+ /** Resolves once the rebuild it starts has finished, so a poll ends caught up. */
256
+ behind(latest: number): Promise<void> | void
256
257
  /**
257
258
  * Told that every change from the one it serves up to `checkpoint` left the
258
259
  * pages alone — media only (story 197) — so its snapshot holds them too.
@@ -302,6 +303,7 @@ export class CacheInstructionPoller {
302
303
  #paused: WritesPaused | undefined
303
304
  /** The checkpoint this node last asked its cache to catch up to, and when. */
304
305
  #asked: { checkpoint: number; at: number } | undefined
306
+ #catchingUp: Promise<void> | void = undefined
305
307
  #latest: number | undefined
306
308
  /** The checkpoint whose changes have all been read for the caches; undefined before the start. */
307
309
  #followed: number | undefined
@@ -400,7 +402,10 @@ export class CacheInstructionPoller {
400
402
  }
401
403
  for (const id of this.#seen) if (id <= this.#cursor - CURSOR_WINDOW) this.#seen.delete(id)
402
404
  await this.#follow(latest)
403
- const served = this.#catchUp(latest)
405
+ this.#catchUp(latest)
406
+ await this.#catchingUp
407
+ this.#catchingUp = undefined
408
+ const served = this.#options.content?.served()
404
409
  await touchServer(db, {
405
410
  nodeId,
406
411
  ...nodeState,
@@ -480,7 +485,7 @@ export class CacheInstructionPoller {
480
485
  const asked = this.#asked
481
486
  if (!asked || asked.checkpoint < latest || Date.now() - asked.at > REASK_AFTER_MS) {
482
487
  this.#asked = { checkpoint: latest, at: Date.now() }
483
- content.behind(latest)
488
+ this.#catchingUp = content.behind(latest)
484
489
  }
485
490
  return served
486
491
  }
@@ -170,11 +170,13 @@ export async function compileSeed(db: Db, config: CromboloConfig): Promise<SeedB
170
170
  return { key: keyOf.get(seeded) as string, typeAlias: mediaTypeAlias.get(seeded) ?? 'Image' }
171
171
  const key = looksLikeKey(ref) ? normaliseUuid(ref) : await siteNode(ref, ObjectTypes.Media, why)
172
172
  if (!key) return undefined
173
- const rows = await db.query<{ alias: string }>(
174
- `SELECT ct.alias FROM node n JOIN content c ON c.node_id = n.id
175
- JOIN content_type ct ON ct.node_id = c.content_type_id WHERE n.unique_id = ?`,
176
- [key],
177
- )
173
+ const rows = await db.q
174
+ .selectFrom('node as n')
175
+ .innerJoin('content as c', 'c.node_id', 'n.id')
176
+ .innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
177
+ .select('ct.alias')
178
+ .where('n.unique_id', '=', key)
179
+ .execute()
178
180
  return { key, typeAlias: rows[0] ? String(rows[0].alias) : 'Image' }
179
181
  }
180
182
  const libraryKey = async (ref: string, why: string) => {
@@ -114,10 +114,12 @@ export async function exportSeed(
114
114
  const aliasOf = async (typeKey: string) => {
115
115
  const key = normaliseUuid(typeKey)
116
116
  if (!typeAliases.has(key)) {
117
- const rows = await db.query<{ alias: string }>(
118
- 'SELECT ct.alias FROM node n JOIN content_type ct ON ct.node_id = n.id WHERE n.unique_id = ?',
119
- [key],
120
- )
117
+ const rows = await db.q
118
+ .selectFrom('node as n')
119
+ .innerJoin('content_type as ct', 'ct.node_id', 'n.id')
120
+ .select('ct.alias')
121
+ .where('n.unique_id', '=', key)
122
+ .execute()
121
123
  typeAliases.set(key, rows[0] ? String(rows[0].alias) : typeKey)
122
124
  }
123
125
  return typeAliases.get(key) as string
package/src/seo.ts CHANGED
@@ -6,8 +6,8 @@
6
6
  * backoffice; an override is stored in `key_value` as JSON, field by field, so
7
7
  * clearing one falls back to the config again.
8
8
  */
9
- import type { Principal } from '@crombolo/api-management'
10
- import { hasSection } from '@crombolo/api-management'
9
+ import type { Principal } from '@crombolo/api-management/domain'
10
+ import { hasSection } from '@crombolo/api-management/domain'
11
11
  import { SYSTEM_CONTENT_TYPE_KEYS } from '@crombolo/core'
12
12
  import { ContentTypeRepository, type Db, readKeyValue, writeKeyValue } from '@crombolo/data'
13
13
  import {