@crombolo/server 0.24.1 → 0.26.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.24.1",
3
+ "version": "0.26.0",
4
4
  "description": "The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -30,18 +30,18 @@
30
30
  "access": "public"
31
31
  },
32
32
  "dependencies": {
33
- "@crombolo/api-delivery": "0.24.1",
34
- "@crombolo/api-management": "0.24.1",
35
- "@crombolo/assistant": "0.24.1",
36
- "@crombolo/auth": "0.24.1",
37
- "@crombolo/backoffice-host": "0.24.1",
38
- "@crombolo/content": "0.24.1",
39
- "@crombolo/contracts": "0.24.1",
40
- "@crombolo/core": "0.24.1",
41
- "@crombolo/data": "0.24.1",
42
- "@crombolo/render": "0.24.1",
43
- "@crombolo/schema": "0.24.1",
44
- "@crombolo/transfer": "0.24.1",
45
- "@logtape/logtape": "^2.3.8"
33
+ "@crombolo/api-delivery": "0.26.0",
34
+ "@crombolo/api-management": "0.26.0",
35
+ "@crombolo/auth": "0.26.0",
36
+ "@crombolo/backoffice-host": "0.26.0",
37
+ "@crombolo/content": "0.26.0",
38
+ "@crombolo/contracts": "0.26.0",
39
+ "@crombolo/core": "0.26.0",
40
+ "@crombolo/data": "0.26.0",
41
+ "@crombolo/render": "0.26.0",
42
+ "@crombolo/schema": "0.26.0",
43
+ "@crombolo/transfer": "0.26.0",
44
+ "@logtape/logtape": "^2.3.8",
45
+ "jose": "^6.2.12"
46
46
  }
47
47
  }
@@ -1,6 +1,6 @@
1
1
  /** The dictionary port over the repository, with `.udt` import and export. */
2
2
  import type { DictionaryPort } from '@crombolo/api-management'
3
- import { type Db, DictionaryRepository } from '@crombolo/data'
3
+ import { appendCacheInstruction, type Db, DictionaryRepository } from '@crombolo/data'
4
4
  import { importDictionaryUdt } from '../dictionary-transfer.ts'
5
5
  import type { MediaFileStore } from '../media-files.ts'
6
6
  import { readUdt, type UdtItem, writeUdt } from '../udt.ts'
@@ -8,10 +8,22 @@ import { readUdt, type UdtItem, writeUdt } from '../udt.ts'
8
8
  export function createDictionaryPort(
9
9
  db: Db,
10
10
  files: MediaFileStore,
11
- options: { onChange?: () => void } = {},
11
+ options: { onChange?: () => void; nodeId?: string } = {},
12
12
  ): DictionaryPort {
13
13
  const repo = new DictionaryRepository(db)
14
- const changed = <T>(result: T): T => {
14
+ /** Every node is told in the change's own transaction (story 174). */
15
+ const instruct = (on: Db) =>
16
+ appendCacheInstruction(on, {
17
+ kind: 'content',
18
+ payload: { dictionary: true },
19
+ by: options.nodeId,
20
+ })
21
+ const write = async <T>(change: (tx: DictionaryRepository) => Promise<T>): Promise<T> => {
22
+ const result = await db.transaction(async (tx) => {
23
+ const done = await change(new DictionaryRepository(tx))
24
+ if (done === 'Success') await instruct(tx)
25
+ return done
26
+ })
15
27
  if (result === 'Success') options.onChange?.()
16
28
  return result
17
29
  }
@@ -34,10 +46,10 @@ export function createDictionaryPort(
34
46
  items: (keys) => repo.many(keys),
35
47
  children: (parentKey) => repo.children(parentKey),
36
48
  ancestry: (key) => repo.ancestry(key),
37
- create: async (item) => changed(await repo.create(item)),
38
- update: async (key, change) => changed(await repo.update(key, change)),
39
- move: async (key, parentKey) => changed(await repo.move(key, parentKey)),
40
- delete: async (key) => changed(await repo.delete(key)),
49
+ create: (item) => write((tx) => tx.create(item)),
50
+ update: (key, change) => write((tx) => tx.update(key, change)),
51
+ move: (key, parentKey) => write((tx) => tx.move(key, parentKey)),
52
+ delete: (key) => write((tx) => tx.delete(key)),
41
53
 
42
54
  async export(key, includeChildren) {
43
55
  const item = await toUdt(key, includeChildren)
@@ -69,6 +81,7 @@ export function createDictionaryPort(
69
81
  status: 'Invalid',
70
82
  reason: 'No item in the file could be imported: its name is already in use.',
71
83
  }
84
+ await instruct(db)
72
85
  options.onChange?.()
73
86
  return { ok: true, key: items[0]?.key as string }
74
87
  },
@@ -24,6 +24,7 @@ import {
24
24
  DomainRepository,
25
25
  InvalidParentError,
26
26
  LanguageRepository,
27
+ latestCheckpoint,
27
28
  NOTIFIABLE_ACTIONS,
28
29
  type NodeRow,
29
30
  NotificationRepository,
@@ -607,6 +608,16 @@ export function createPublishedContentSource(
607
608
  source: row.source,
608
609
  }))
609
610
  },
611
+
612
+ /**
613
+ * Every load in one read snapshot, the checkpoint read first inside it
614
+ * (story 174), so the snapshot holds exactly the changes up to that number.
615
+ */
616
+ withSnapshot: (fn) =>
617
+ db.readSnapshot(async (reader) => {
618
+ const checkpoint = await latestCheckpoint(reader)
619
+ return fn(createPublishedContentSource(reader, options), checkpoint)
620
+ }),
610
621
  }
611
622
  }
612
623
 
@@ -4,10 +4,13 @@
4
4
  */
5
5
  import type { DiagnosticsPort, HealthCheckGroup, HealthCheckResult } from '@crombolo/api-management'
6
6
  import {
7
+ changedSince,
7
8
  compareStates,
8
9
  cromboloPlan,
9
10
  currentSchemaState,
10
11
  type Db,
12
+ type LiveNode,
13
+ latestCheckpoint,
11
14
  liveNodes,
12
15
  type NodeSchemaState,
13
16
  pendingMigrations,
@@ -72,6 +75,36 @@ const GROUPS: HealthCheckGroup[] = [
72
75
  },
73
76
  ]
74
77
 
78
+ /** Behind the latest content for longer than this, a node is worth a warning: it is not catching up. */
79
+ export const CONTENT_STALE_AFTER_MS = 60_000
80
+
81
+ /**
82
+ * Which nodes serve older published content than the latest committed, and for
83
+ * how long (story 174). Pure: `since` is when the first change a node lacks was
84
+ * recorded. Numbers and times only, never content.
85
+ */
86
+ export function freshnessResults(
87
+ nodes: ReadonlyArray<Pick<LiveNode, 'nodeId' | 'servedCheckpoint'>>,
88
+ latest: number,
89
+ since: ReadonlyMap<string, Date>,
90
+ at: Date,
91
+ ): HealthCheckResult[] {
92
+ const results: HealthCheckResult[] = []
93
+ for (const node of nodes) {
94
+ if (node.servedCheckpoint === null) continue
95
+ if (node.servedCheckpoint >= latest) continue
96
+ const from = since.get(node.nodeId)
97
+ if (from && at.getTime() - from.getTime() > CONTENT_STALE_AFTER_MS)
98
+ results.push(
99
+ result(
100
+ 'Warning',
101
+ `${node.nodeId} serves published content as of change ${node.servedCheckpoint}; the latest is ${latest}, since ${from.toISOString()}. It is not catching up: check it can reach the database, or restart it.`,
102
+ ),
103
+ )
104
+ }
105
+ return results
106
+ }
107
+
75
108
  const QUEUE_LABELS = {
76
109
  changes: 'change(s) waiting to be passed on',
77
110
  webhooks: 'webhook delivery(ies)',
@@ -250,9 +283,16 @@ export function createDiagnosticsPort(options: HealthCheckOptions): DiagnosticsP
250
283
  const results = live.map((node) =>
251
284
  result(
252
285
  'Info',
253
- `${node.nodeId}${node.role ? ` (${node.role})` : ''} runs Crombolo ${node.cromboloVersion ?? 'of an unknown release'} with schema ${node.version ?? '?'} revision ${node.revision ?? '?'}, last seen ${ago(node.lastSeen, at)}.`,
286
+ `${node.nodeId}${node.role ? ` (${node.role})` : ''} runs Crombolo ${node.cromboloVersion ?? 'of an unknown release'} with schema ${node.version ?? '?'} revision ${node.revision ?? '?'}, last seen ${ago(node.lastSeen, at)}${node.servedCheckpoint === null ? '' : `, serving published content as of change ${node.servedCheckpoint} of ${latest}`}.`,
254
287
  ),
255
288
  )
289
+ const latest = await latestCheckpoint(db)
290
+ const since = new Map<string, Date>()
291
+ for (const node of live)
292
+ if (node.servedCheckpoint !== null && node.servedCheckpoint < latest) {
293
+ const from = await changedSince(db, node.servedCheckpoint)
294
+ if (from) since.set(node.nodeId, from)
295
+ }
256
296
  const releases = new Set(live.map((node) => node.cromboloVersion ?? 'unknown'))
257
297
  const schemas = new Set(live.map((node) => `${node.version}/${node.revision}`))
258
298
  if (releases.size > 1)
@@ -273,6 +313,7 @@ export function createDiagnosticsPort(options: HealthCheckOptions): DiagnosticsP
273
313
  results.unshift(
274
314
  result('Success', `${live.length} server(s) running Crombolo ${[...releases][0]}.`),
275
315
  )
316
+ results.unshift(...freshnessResults(live, latest, since, at))
276
317
  return results
277
318
  }
278
319
 
@@ -9,13 +9,18 @@
9
9
 
10
10
  import type { RedirectListing, RedirectPort } from '@crombolo/api-management'
11
11
  import type { Page } from '@crombolo/core'
12
- import { type Db, RedirectRepository, type RedirectRow } from '@crombolo/data'
12
+ import {
13
+ appendCacheInstruction,
14
+ type Db,
15
+ RedirectRepository,
16
+ type RedirectRow,
17
+ } from '@crombolo/data'
13
18
  import type { PublishedCache } from '@crombolo/render'
14
19
 
15
20
  export function createRedirectPort(
16
21
  db: Db,
17
22
  cache: PublishedCache | undefined,
18
- options: { isTracking: boolean; onChange?: () => void },
23
+ options: { isTracking: boolean; onChange?: () => void; nodeId?: string },
19
24
  ): RedirectPort {
20
25
  const redirects = new RedirectRepository(db)
21
26
 
@@ -62,9 +67,16 @@ export function createRedirectPort(
62
67
  const found = await redirects.byKey(key)
63
68
  if (!found) return 'notFound'
64
69
  if (found.source === 'config') return 'configured'
65
- await redirects.delete(key)
66
- // The rules live in the published cache's snapshot, so it has to be dropped
67
- // for the redirect to stop answering.
70
+ // The rules live in the published cache's snapshot: every node is told in
71
+ // the delete's own transaction (story 174), and this one drops its copy.
72
+ await db.transaction(async (tx) => {
73
+ await new RedirectRepository(tx).delete(key)
74
+ await appendCacheInstruction(tx, {
75
+ kind: 'content',
76
+ payload: { redirects: true },
77
+ by: options.nodeId,
78
+ })
79
+ })
68
80
  options.onChange?.()
69
81
  return 'deleted'
70
82
  },
@@ -160,7 +160,12 @@ function locate(target: string, siteDir: string): { directory: string; dependenc
160
160
  * The bundle a path or a package name names, read whole, or a refusal: a
161
161
  * half-copied bundle must never be checked as though complete.
162
162
  */
163
- export function readBundle(target: string, siteDir: string, passphrase?: string): ResolvedBundle {
163
+ export function readBundle(
164
+ target: string,
165
+ siteDir: string,
166
+ passphrase?: string,
167
+ options: { withoutPeople?: boolean } = {},
168
+ ): ResolvedBundle {
164
169
  const { directory, dependency } = locate(target, siteDir)
165
170
  const json = readPackageJson(join(directory, 'package.json'))
166
171
  if (!json) {
@@ -199,9 +204,10 @@ export function readBundle(target: string, siteDir: string, passphrase?: string)
199
204
  people: undefined,
200
205
  openBlob: (_key, bytes) => bytes,
201
206
  }
202
- if (passphrase !== undefined && passphrase !== '')
207
+ const peopleOnly = options.withoutPeople && loaded.set.manifest.content !== 'sealed'
208
+ if ((passphrase !== undefined && passphrase !== '') || peopleOnly)
203
209
  try {
204
- opened = openBundle(loaded, passphrase)
210
+ opened = openBundle(loaded, passphrase || undefined, options)
205
211
  } catch (error) {
206
212
  if (error instanceof WrongPassphraseError)
207
213
  throw new PassphraseError(
@@ -269,6 +275,8 @@ export interface TransferInput extends SectionOptions {
269
275
  by?: string
270
276
  /** Opens what the bundle sealed; used for this request only, never stored. */
271
277
  passphrase?: string
278
+ /** Leave the file's members, users and their groups out: this site's own are untouched. */
279
+ excludePeople?: boolean
272
280
  }
273
281
 
274
282
  /**
@@ -312,6 +320,7 @@ export async function transferOptions(
312
320
  allowMissingBlobs: input.allowMissingBlobs ?? pending?.allowMissingBlobs ?? false,
313
321
  hasBlob: async (key: string) => Boolean(await store.get(key)),
314
322
  backOfficePath: config.backOfficePath,
323
+ ...(input.excludePeople ? { excludePeople: true } : {}),
315
324
  },
316
325
  under,
317
326
  problems: saved.problems,
@@ -341,7 +350,9 @@ export async function checkBundleContent(
341
350
  config: CromboloConfig,
342
351
  input: TransferInput,
343
352
  ): Promise<ContentCheckResult> {
344
- const bundle = readBundle(input.bundle, config.siteDir, input.passphrase)
353
+ const bundle = readBundle(input.bundle, config.siteDir, input.passphrase, {
354
+ withoutPeople: input.excludePeople,
355
+ })
345
356
  const set = bundle.set
346
357
  const prepared = await transferOptions(db, config, bundle, input)
347
358
  const check = await checkBundle(db, set, prepared.options)
@@ -493,7 +504,9 @@ export async function installBundleContent(
493
504
  config: CromboloConfig,
494
505
  input: ContentImportInput,
495
506
  ): Promise<ContentImportResult> {
496
- const bundle = readBundle(input.bundle, config.siteDir, input.passphrase)
507
+ const bundle = readBundle(input.bundle, config.siteDir, input.passphrase, {
508
+ withoutPeople: input.excludePeople,
509
+ })
497
510
  const { set, blobs, carried } = bundle
498
511
  // Before the backup and the sections: nothing of a bundle that cannot be
499
512
  // opened is applied.
@@ -538,6 +551,10 @@ export async function installBundleContent(
538
551
  ])
539
552
  referencedPresent = true
540
553
  }
554
+ if (replace === 'replace-all' && input.excludePeople)
555
+ return refuse([
556
+ "--replace-all deletes the people the file lacks, so it cannot leave the file's people out; use --replace",
557
+ ])
541
558
  if (replace === 'replace-all' && !carriesAdministrator(set.people))
542
559
  return refuse([
543
560
  'this file carries no back-office administrator, so replacing everything would leave nobody able to sign in; export it with --with-users, or use --replace',
package/src/config.ts CHANGED
@@ -12,10 +12,10 @@ import {
12
12
  type RedirectRule,
13
13
  type SnapshotLimits,
14
14
  } from '@crombolo/render'
15
- import type { AssistantConfig } from './assistant.ts'
16
15
  import type { ServerBundle } from './bundles.ts'
17
16
  import type { EmailPort } from './email.ts'
18
17
  import type { GitConfig } from './git-routes.ts'
18
+ import { checkHost, type HostConfig } from './host-token.ts'
19
19
  import { checkIdentityProviders, type IdentityProvider } from './identity-providers.ts'
20
20
  import type { MediaStore } from './media-store.ts'
21
21
  import type { SchemaStore } from './schema-store.ts'
@@ -380,6 +380,13 @@ export interface CromboloConfig {
380
380
  * (`bundles.ts`, `docs/bundles.md`).
381
381
  */
382
382
  bundles: ServerBundle[]
383
+ /**
384
+ * Package names this installation provides to every site it runs, rather
385
+ * than the site choosing them (story 177): a whole-site file leaves them out
386
+ * of what it requires, so the site starts anywhere without them. Set by
387
+ * whoever runs the installation, in code only, as `bundles` is.
388
+ */
389
+ hostProvided: readonly string[]
383
390
  /**
384
391
  * Whether installing a bundle from the Marketplace also applies the content it
385
392
  * carries — its schema, components and content — straight after `bun add`. On
@@ -414,12 +421,11 @@ export interface CromboloConfig {
414
421
  */
415
422
  git: GitConfig | undefined
416
423
  /**
417
- * The AI helper in the backoffice. Absent means the feature does not exist: no
418
- * route, no tools, no model client, and nothing in the backoffice. When it is
419
- * configured the assistant can read the CMS and propose changes, and a person
420
- * approves each one — it cannot write, and it cannot publish.
424
+ * The host this installation's back office vouches for its user to (story
425
+ * 178): its origin, the key that signs host tokens, and that key's id. From
426
+ * `crombolo.config.ts` only; without it no token is issued.
421
427
  */
422
- assistant: AssistantConfig | undefined
428
+ host: HostConfig | undefined
423
429
  }
424
430
 
425
431
  export type SiteConfig = CromboloConfig
@@ -688,11 +694,13 @@ export function loadConfig(
688
694
  }),
689
695
  // No environment variable: a bundle is an import, which is code.
690
696
  bundles: [],
697
+ // Nor here: it is the installation's decision about that code.
698
+ hostProvided: [],
691
699
  marketplaceUrl: setting('CROMBOLO_MARKETPLACE_URL') ?? DEFAULTS.marketplaceUrl,
692
700
  packageKeyword: setting('CROMBOLO_PACKAGE_KEYWORD') ?? DEFAULTS.packageKeyword,
693
701
  npmRegistry: setting('CROMBOLO_NPM_REGISTRY') ?? DEFAULTS.npmRegistry,
694
- // No environment variable: enabling it takes a provider, which is code.
695
- assistant: undefined,
702
+ // Nor here: a host reads its own variables inside `defineConfig`, if it wants them.
703
+ host: undefined,
696
704
  }
697
705
  const merged: CromboloConfig = { ...fromEnv, ...stripUndefined(overrides) }
698
706
  checkIdentityProviders(merged.memberIdentityProviders, 'member')
@@ -701,6 +709,13 @@ export function loadConfig(
701
709
  merged.seo = { ...fromEnv.seo, ...stripUndefined(overrides.seo ?? {}) }
702
710
  merged.remote = { ...fromEnv.remote, ...stripUndefined(overrides.remote ?? {}) }
703
711
  checkApiClient(merged.apiClient)
712
+ checkHost(merged.host)
713
+ // The key itself is refused, so a config left over from before says so rather
714
+ // than starting without the feature it asked for.
715
+ if ('assistant' in overrides)
716
+ throw new Error(
717
+ "The AI assistant was removed from crombolo in 0.26 (story 179), so 'assistant' is no longer a setting. See the 0.26 release notes, and 'Tools a host provides' in docs/bundles.md for how a host offers such a tool now.",
718
+ )
704
719
  if (!/^[a-z][a-z0-9-]{0,62}$/.test(merged.remote.environment))
705
720
  throw new Error(
706
721
  `remote.environment "${merged.remote.environment}" must be lower case letters, digits and dashes.`,
@@ -798,7 +813,7 @@ export function describeDatabase(
798
813
  }
799
814
  }
800
815
 
801
- export const VERSION = '0.24.1'
816
+ export const VERSION = '0.26.0'
802
817
 
803
818
  /** A whole number of seconds from the environment; undefined when unset or not one. */
804
819
  function numberSetting(name: Parameters<typeof setting>[0]): number | undefined {
@@ -11,7 +11,12 @@ import {
11
11
  type DocumentOperations,
12
12
  type EventSink,
13
13
  } from '@crombolo/content'
14
- import { currentSchemaState, type Db, RedirectRepository } from '@crombolo/data'
14
+ import {
15
+ appendCacheInstruction,
16
+ currentSchemaState,
17
+ type Db,
18
+ RedirectRepository,
19
+ } from '@crombolo/data'
15
20
  import { PublishedCache } from '@crombolo/render'
16
21
  import { createPublishedContentSource } from './adapters/documents.ts'
17
22
  import { createApprovals } from './approvals.ts'
@@ -75,6 +80,12 @@ export async function siteDocumentOperations(
75
80
  cache,
76
81
  redirects: new RedirectRepository(db),
77
82
  enabled: config.trackRedirects,
83
+ instruct: () =>
84
+ appendCacheInstruction(db, {
85
+ kind: 'content',
86
+ payload: { redirects: true },
87
+ by: `cli:${config.nodeId}`,
88
+ }),
78
89
  }),
79
90
  afterDomains: (node, assignment) => writeDomainsFor(db, config.siteDir, node, assignment),
80
91
  refusalReason: (error) =>
@@ -0,0 +1,69 @@
1
+ /**
2
+ * A host token (story 178): the back office's signed statement, for a service
3
+ * the host runs elsewhere, of who is signed in. Short-lived, addressed to the
4
+ * one host origin configured, and signed with a key the host holds.
5
+ * docs/bundles.md, "Tools a host provides".
6
+ */
7
+ import { SignJWT } from 'jose'
8
+
9
+ /** The installation's host, from `crombolo.config.ts` only. */
10
+ export interface HostConfig {
11
+ /** The host service's origin, which every token is addressed to. */
12
+ origin: string
13
+ /** The HS256 key, at least 32 bytes; it both signs and verifies. */
14
+ signingKey: string
15
+ /** Names the key in each token's header, for a host running many installations. */
16
+ keyId: string
17
+ }
18
+
19
+ /** How long a token lasts, in seconds. */
20
+ export const HOST_TOKEN_SECONDS = 300
21
+
22
+ /** Refuses a `host` that could not be used, naming the field. */
23
+ export function checkHost(host: HostConfig | undefined): void {
24
+ if (!host) return
25
+ let url: URL | undefined
26
+ try {
27
+ url = new URL(host.origin)
28
+ } catch {
29
+ url = undefined
30
+ }
31
+ const local = url?.protocol === 'http:' && ['localhost', '127.0.0.1'].includes(url.hostname)
32
+ if (!url || (url.protocol !== 'https:' && !local) || url.origin !== host.origin)
33
+ throw new Error(
34
+ `host.origin "${host.origin}" must be an https origin with no path, such as https://tools.example.com.`,
35
+ )
36
+ if (new TextEncoder().encode(host.signingKey ?? '').length < 32)
37
+ throw new Error('host.signingKey must be at least 32 bytes.')
38
+ if (typeof host.keyId !== 'string' || host.keyId.trim() === '')
39
+ throw new Error('host.keyId must name the key.')
40
+ }
41
+
42
+ /** Who the token is about, and which site says so. */
43
+ export interface HostTokenSubject {
44
+ user: { key: string; name: string }
45
+ groups: readonly string[]
46
+ sections: readonly string[]
47
+ site: { name: string; nodeId: string; url?: string }
48
+ }
49
+
50
+ export async function issueHostToken(
51
+ host: HostConfig,
52
+ subject: HostTokenSubject,
53
+ now = new Date(),
54
+ ): Promise<string> {
55
+ const issuedAt = Math.floor(now.getTime() / 1000)
56
+ const token = new SignJWT({
57
+ name: subject.user.name,
58
+ groups: [...subject.groups],
59
+ sections: [...subject.sections],
60
+ site: { name: subject.site.name, nodeId: subject.site.nodeId },
61
+ })
62
+ .setProtectedHeader({ alg: 'HS256', kid: host.keyId, typ: 'JWT' })
63
+ .setSubject(subject.user.key)
64
+ .setAudience(host.origin)
65
+ .setIssuedAt(issuedAt)
66
+ .setExpirationTime(issuedAt + HOST_TOKEN_SECONDS)
67
+ if (subject.site.url) token.setIssuer(subject.site.url)
68
+ return token.sign(new TextEncoder().encode(host.signingKey))
69
+ }
package/src/index.ts CHANGED
@@ -53,6 +53,7 @@ export * from './forms.ts'
53
53
  export * from './git.ts'
54
54
  export * from './git-github.ts'
55
55
  export * from './git-routes.ts'
56
+ export * from './host-token.ts'
56
57
  export * from './identity-provider-overrides.ts'
57
58
  export * from './identity-providers.ts'
58
59
  export * from './imaging.ts'
package/src/ports.ts CHANGED
@@ -17,7 +17,6 @@ import type {
17
17
  import { AuthStore, expireCookie, serializeCookie } from '@crombolo/auth'
18
18
  import {
19
19
  APP_PREVIEW_MANIFEST_ID,
20
- ASSISTANT_MANIFEST_ID,
21
20
  type BackOfficePaths,
22
21
  collectManifests,
23
22
  type ExtensionRegistry,
@@ -39,6 +38,7 @@ import {
39
38
  permissionsForPath,
40
39
  } from '@crombolo/core'
41
40
  import {
41
+ appendCacheInstruction,
42
42
  ContentEventRepository,
43
43
  ContentTypeRepository,
44
44
  type Db,
@@ -473,12 +473,12 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
473
473
  const deps: ManagementApiDeps = {
474
474
  server: createServerPort(options.config, Boolean(sendUserLink)),
475
475
  preview: createPreviewPort(options.config, options.previewInApp),
476
- // An unconfigured assistant contributes no extension, so the backoffice has
477
- // no drawer, no button and nothing to load; Preview in app likewise.
478
- manifests: createManifestPort(options.paths, options.extensions, [
479
- ...(options.config.assistant ? [] : [ASSISTANT_MANIFEST_ID]),
480
- ...(options.previewInApp ? [] : [APP_PREVIEW_MANIFEST_ID]),
481
- ]),
476
+ // Without an app to preview in, Preview in app contributes no extension.
477
+ manifests: createManifestPort(
478
+ options.paths,
479
+ options.extensions,
480
+ options.previewInApp ? [] : [APP_PREVIEW_MANIFEST_ID],
481
+ ),
482
482
  localization: createLocalizationPort(
483
483
  options.db,
484
484
  options.db ? createSchemaFileWriter(options.db, schemaFiles(options.config)) : undefined,
@@ -638,6 +638,7 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
638
638
  deps.redirects = createRedirectPort(options.db, options.cache, {
639
639
  isTracking: options.config.trackRedirects,
640
640
  onChange: () => options.cache?.invalidate(),
641
+ nodeId: options.schema?.nodeId,
641
642
  })
642
643
  deps.packages = createPackagePort(options.db, {
643
644
  siteName: options.config.siteName,
@@ -668,12 +669,20 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
668
669
  }
669
670
  deps.dictionary = createDictionaryPort(options.db, mediaFiles, {
670
671
  onChange: () => options.cache?.invalidate(),
672
+ nodeId: options.schema?.nodeId,
671
673
  })
674
+ const db = options.db
672
675
  const tracker = options.cache
673
676
  ? createRedirectTracker({
674
677
  cache: options.cache,
675
- redirects: new RedirectRepository(options.db),
678
+ redirects: new RedirectRepository(db),
676
679
  enabled: options.config.trackRedirects,
680
+ instruct: () =>
681
+ appendCacheInstruction(db, {
682
+ kind: 'content',
683
+ payload: { redirects: true },
684
+ by: options.schema?.nodeId,
685
+ }),
677
686
  })
678
687
  : undefined
679
688
  if (options.cache)
package/src/redirects.ts CHANGED
@@ -39,6 +39,12 @@ export function createRedirectTracker(options: {
39
39
  cache: PublishedCache
40
40
  redirects: RedirectRepository
41
41
  enabled: boolean
42
+ /**
43
+ * Tells every node a redirect was written (story 174). The routes it compares
44
+ * are read from the published cache once the change has committed, so this
45
+ * moves the checkpoint just after the change rather than inside it.
46
+ */
47
+ instruct?: () => Promise<unknown>
42
48
  }): RedirectTracker {
43
49
  if (!options.enabled) return NO_REDIRECT_TRACKING
44
50
  const { cache, redirects } = options
@@ -99,7 +105,10 @@ export function createRedirectTracker(options: {
99
105
  // The rules are part of the cache's snapshot, and reading the new routes
100
106
  // above has just rebuilt it — so without this the redirect just written
101
107
  // would not answer until something else dropped the cache.
102
- if (wrote) cache.invalidate()
108
+ if (wrote) {
109
+ await options.instruct?.()
110
+ cache.invalidate()
111
+ }
103
112
  },
104
113
  }
105
114
  }
package/src/remote.ts CHANGED
@@ -17,7 +17,7 @@ import { tmpdir } from 'node:os'
17
17
  import { join, sep } from 'node:path'
18
18
  import type { Principal } from '@crombolo/api-management'
19
19
  import { DEVICE_CODE_GRANT, REMOTE_CLIENT_ID } from '@crombolo/auth'
20
- import { MANAGEMENT_API_PATH, RemotePermissions, type RemoteVerb } from '@crombolo/core'
20
+ import { managementApiPath, RemotePermissions, type RemoteVerb } from '@crombolo/core'
21
21
  import { type Db, type RemoteJob, RemoteJobRepository } from '@crombolo/data'
22
22
  import type { ContentSet } from '@crombolo/transfer'
23
23
  import { recordAudit } from './adapters/audit.ts'
@@ -117,14 +117,17 @@ export function createRemote(options: RemoteOptions): Remote {
117
117
  protected: settings.protected,
118
118
  })
119
119
 
120
+ // Under the back office, as the editor's own API calls are; a command line
121
+ // follows these addresses rather than building its own.
122
+ const managementApi = managementApiPath(config.backOfficePath.replace(/\/+$/, ''))
120
123
  const discovery = (origin: string) => ({
121
124
  protocol: 'crombolo-remote',
122
125
  versions: [REMOTE_PROTOCOL_VERSION],
123
126
  name: config.siteName,
124
127
  api: `${origin}${REMOTE_API_PATH}`,
125
128
  auth: {
126
- deviceAuthorization: `${origin}${MANAGEMENT_API_PATH}/security/back-office/device`,
127
- token: `${origin}${MANAGEMENT_API_PATH}/security/back-office/token`,
129
+ deviceAuthorization: `${origin}${managementApi}/security/back-office/device`,
130
+ token: `${origin}${managementApi}/security/back-office/token`,
128
131
  clientId: REMOTE_CLIENT_ID,
129
132
  grantType: DEVICE_CODE_GRANT,
130
133
  },