@crombolo/server 0.71.0 → 0.73.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.71.0",
3
+ "version": "0.73.0",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -32,19 +32,19 @@
32
32
  "access": "public"
33
33
  },
34
34
  "dependencies": {
35
- "@crombolo/api-delivery": "0.71.0",
36
- "@crombolo/api-management": "0.71.0",
37
- "@crombolo/auth": "0.71.0",
38
- "@crombolo/backoffice-host": "0.71.0",
39
- "@crombolo/common": "0.71.0",
40
- "@crombolo/content": "0.71.0",
41
- "@crombolo/contracts": "0.71.0",
42
- "@crombolo/core": "0.71.0",
43
- "@crombolo/data": "0.71.0",
44
- "@crombolo/extension": "0.71.0",
45
- "@crombolo/render": "0.71.0",
46
- "@crombolo/schema": "0.71.0",
47
- "@crombolo/transfer": "0.71.0",
35
+ "@crombolo/api-delivery": "0.73.0",
36
+ "@crombolo/api-management": "0.73.0",
37
+ "@crombolo/auth": "0.73.0",
38
+ "@crombolo/backoffice-host": "0.73.0",
39
+ "@crombolo/common": "0.73.0",
40
+ "@crombolo/content": "0.73.0",
41
+ "@crombolo/contracts": "0.73.0",
42
+ "@crombolo/core": "0.73.0",
43
+ "@crombolo/data": "0.73.0",
44
+ "@crombolo/extension": "0.73.0",
45
+ "@crombolo/render": "0.73.0",
46
+ "@crombolo/schema": "0.73.0",
47
+ "@crombolo/transfer": "0.73.0",
48
48
  "@logtape/logtape": "^2.3.8",
49
49
  "@opentelemetry/api": "1.10.0",
50
50
  "@opentelemetry/context-async-hooks": "3.0.0",
@@ -20,6 +20,7 @@ import {
20
20
  DbDate,
21
21
  DocumentRepository,
22
22
  type DocumentRepositoryOptions,
23
+ SCHEDULE_PREFIX,
23
24
  TransferRunRepository,
24
25
  type Workspace,
25
26
  WorkspaceFileRepository,
@@ -32,6 +33,7 @@ import type {
32
33
  ChangeBundlePage,
33
34
  ChangePageState,
34
35
  ChangeValue,
36
+ PageSchedule,
35
37
  } from '@crombolo/transfer'
36
38
  import type { MediaFileStore } from './media-files.ts'
37
39
  import type { WorkspaceMerging } from './node-operations.ts'
@@ -249,8 +251,18 @@ export function createChangeTransfer(options: ChangeTransferOptions) {
249
251
  JSON.parse(i.before as string),
250
252
  ]),
251
253
  ) as Map<string, DocumentAggregate>
254
+ // Story 395: a page's schedule, as the change set it.
255
+ const schedules = new Map(
256
+ items
257
+ .filter((i) => i.path.startsWith(SCHEDULE_PREFIX) && i.after !== null)
258
+ .map((i) => [
259
+ normaliseUuid(i.path.slice(SCHEDULE_PREFIX.length)),
260
+ JSON.parse(i.after as string) as PageSchedule,
261
+ ]),
262
+ )
252
263
  for (const item of items) {
253
- if (item.path.startsWith(REMOVED_PAGE_PREFIX)) continue
264
+ if (item.path.startsWith(REMOVED_PAGE_PREFIX) || item.path.startsWith(SCHEDULE_PREFIX))
265
+ continue
254
266
  const versions = await changes.versions(item.path)
255
267
  const at = versions.findIndex((v) => v.changeId === change.id)
256
268
  const earlier = at > 0 ? versions[at - 1] : undefined
@@ -277,6 +289,7 @@ export function createChangeTransfer(options: ChangeTransferOptions) {
277
289
  if (!shape) continue
278
290
  const action =
279
291
  row.action === 'create' ? 'create' : row.action === 'recycle' ? 'delete' : 'update'
292
+ const schedule = schedules.get(normaliseUuid(row.nodeKey))
280
293
  const page = pageOf(
281
294
  row.nodeKey,
282
295
  row.kind,
@@ -286,6 +299,7 @@ export function createChangeTransfer(options: ChangeTransferOptions) {
286
299
  after,
287
300
  await lastChangeOfNode(row.nodeKey, row.beforeEventId, change.key),
288
301
  )
302
+ if (page.after && schedule) page.after.schedule = schedule
289
303
  pages.push(page)
290
304
  depends.push(...(await madeBy([page.after], change.key)))
291
305
  if (page.lastChange && page.action !== 'create') depends.push(page.lastChange)
@@ -463,9 +477,18 @@ export function createChangeTransfer(options: ChangeTransferOptions) {
463
477
  }
464
478
  if (schemaTouched) await options.schema()?.build({ id: workspace.id, key: workspace.key })
465
479
  const staged = [...(workspace.stagedChanges ?? [])]
466
- for (const { change } of todo)
480
+ for (const { change } of todo) {
481
+ // Story 395: a schedule is set on Shared once the change is merged, as a merge drops a workspace's.
482
+ const schedules = change.pages.flatMap((p) =>
483
+ p.after?.schedule ? [{ key: p.key, kind: p.kind, entries: p.after.schedule }] : [],
484
+ )
467
485
  if (!staged.some((s) => s.key === change.key))
468
- staged.push({ key: change.key, name: change.name })
486
+ staged.push({
487
+ key: change.key,
488
+ name: change.name,
489
+ ...(schedules.length > 0 ? { schedules } : {}),
490
+ })
491
+ }
469
492
  await workspaces.setStaged(workspace.id, staged)
470
493
  return { workspace: (await workspaces.byKey(workspace.key)) ?? workspace, skipped, conflicts }
471
494
  }
@@ -667,9 +690,29 @@ export function createChangeTransfer(options: ChangeTransferOptions) {
667
690
  conflicts: outcome.blockers.map((says) => ({ change: workspace.key, item: '', says })),
668
691
  workspace: workspace.key,
669
692
  }
693
+ for (const change of applied)
694
+ for (const page of change.schedules ?? []) await scheduleHere(page)
670
695
  return { ok: true, skipped, changeId: outcome.changeId ?? null }
671
696
  }
672
697
 
698
+ /** A page's schedule as a change carries it, replacing what Shared had for the page. */
699
+ async function scheduleHere(page: { key: string; kind: string; entries: PageSchedule }) {
700
+ const here = repo(page.kind as PageKind)
701
+ if (!(await here.byKey(page.key))) return
702
+ const had = await here.schedules(page.key)
703
+ const cleared = [...new Set(had.map((s) => s.culture))]
704
+ .filter((culture) => !page.entries.some((e) => e.culture === culture))
705
+ .map((culture) => ({ culture, publishTime: null, unpublishTime: null }))
706
+ await here.setSchedule(page.key, [
707
+ ...cleared,
708
+ ...page.entries.map((e) => ({
709
+ culture: e.culture,
710
+ publishTime: e.publishTime ? new Date(e.publishTime) : null,
711
+ unpublishTime: e.unpublishTime ? new Date(e.unpublishTime) : null,
712
+ })),
713
+ ])
714
+ }
715
+
673
716
  return { exportChange, exportWorkspace, exportSince, stage, apply, mergeStaged }
674
717
  }
675
718
 
package/src/config.ts CHANGED
@@ -257,9 +257,9 @@ export function runsOnLocalhost(config: CromboloConfig): boolean {
257
257
  }
258
258
  }
259
259
 
260
- /** The body limit to listen with: raised for remote uploads when the remote is on. */
260
+ /** The body limit to listen with: raised for uploads when the remote or workspaces are on. */
261
261
  export function listeningBodyLimit(config: CromboloConfig): number {
262
- return config.remote.enabled
262
+ return config.remote.enabled || workspacesOn(config)
263
263
  ? Math.max(config.maxRequestBodyBytes, config.remote.maxUploadBytes)
264
264
  : config.maxRequestBodyBytes
265
265
  }
@@ -523,6 +523,11 @@ export interface CromboloConfig {
523
523
  * needs workspaces on.
524
524
  */
525
525
  workspacesRequired: boolean
526
+ /**
527
+ * Who may stage or apply a change (story 394): `exchange` honours Apply changes only
528
+ * for a sign-in exchanged for applying one. `CROMBOLO_APPLY_CHANGES_BY`, any unless set.
529
+ */
530
+ applyChangesBy: 'any' | 'exchange'
526
531
  /**
527
532
  * How many workspaces with changed views render at once on a node, each in a
528
533
  * process of its own (story 378); past it the least recently used is stopped.
@@ -1128,6 +1133,7 @@ export function loadConfig(
1128
1133
  cliTokenMaxDays: Math.floor(positiveNumber(setting('CROMBOLO_CLI_TOKEN_MAX_DAYS'), 90)),
1129
1134
  workspaces: setting('CROMBOLO_WORKSPACES') === 'true',
1130
1135
  workspacesRequired: setting('CROMBOLO_WORKSPACES_REQUIRED') === 'true',
1136
+ applyChangesBy: (setting('CROMBOLO_APPLY_CHANGES_BY') || 'any') as 'any' | 'exchange',
1131
1137
  purgeAfterDays: Math.floor(nonNegativeNumber(setting('CROMBOLO_PURGE_AFTER_DAYS'), 0)),
1132
1138
  workspacesHost: setting('CROMBOLO_WORKSPACES_HOST') || undefined,
1133
1139
  workspaceLinkMaxDays: Math.floor(
@@ -1326,6 +1332,10 @@ export function loadConfig(
1326
1332
  throw new Error(
1327
1333
  `users.managedAt is "${merged.users.managedAt}": it is an http or https address, with {email}, {key} or {userName}.`,
1328
1334
  )
1335
+ if (merged.applyChangesBy !== 'any' && merged.applyChangesBy !== 'exchange')
1336
+ throw new Error(
1337
+ `applyChangesBy is "${String(merged.applyChangesBy)}": it is any or exchange (CROMBOLO_APPLY_CHANGES_BY).`,
1338
+ )
1329
1339
  if (merged.workspacesRequired && !merged.workspaces)
1330
1340
  throw new Error(
1331
1341
  'Workspaces are required (CROMBOLO_WORKSPACES_REQUIRED) but not turned on: set CROMBOLO_WORKSPACES=true as well.',
@@ -1482,7 +1492,7 @@ export function describeDatabase(
1482
1492
  }
1483
1493
  }
1484
1494
 
1485
- export const VERSION = '0.71.0'
1495
+ export const VERSION = '0.73.0'
1486
1496
 
1487
1497
  /** A whole number of seconds from the environment; undefined when unset or not one. */
1488
1498
  /** A positive number from a setting, else the default. */
@@ -26,8 +26,16 @@ import {
26
26
  notificationFor,
27
27
  webhookFor,
28
28
  } from '@crombolo/content'
29
- import { AuditLog, ChangeRepository, ContentEventRepository, type Db } from '@crombolo/data'
29
+ import {
30
+ AuditLog,
31
+ ChangeRepository,
32
+ ContentEventRepository,
33
+ currentAuditContext,
34
+ type Db,
35
+ DocumentRepository,
36
+ } from '@crombolo/data'
30
37
  import type { ContentNotifier } from './content-notifications.ts'
38
+ import { neededBy, servedView } from './served-schema.ts'
31
39
  import type { WebhookService } from './webhooks.ts'
32
40
 
33
41
  export interface ContentEventSinkOptions {
@@ -75,6 +83,43 @@ export const outboxActor = (actor: MediaActor) => {
75
83
  }
76
84
  }
77
85
 
86
+ /** A page's schedule as a change carries it: per language, when it goes live and comes down. */
87
+ export const scheduleEntries = (
88
+ rows: ReadonlyArray<{ culture: string | null; action: 'Release' | 'Expire'; date: Date }>,
89
+ ) => {
90
+ const byCulture = new Map<
91
+ string | null,
92
+ { culture: string | null; publishTime: string | null; unpublishTime: string | null }
93
+ >()
94
+ for (const row of rows) {
95
+ const entry = byCulture.get(row.culture) ?? {
96
+ culture: row.culture,
97
+ publishTime: null,
98
+ unpublishTime: null,
99
+ }
100
+ if (row.action === 'Release') entry.publishTime = row.date.toISOString()
101
+ else entry.unpublishTime = row.date.toISOString()
102
+ byCulture.set(row.culture, entry)
103
+ }
104
+ return [...byCulture.values()]
105
+ }
106
+
107
+ /** Story 395: a person, or a tool acting for one (a sign-in exchanged with an actor, 364). */
108
+ async function madeBy(): Promise<{ by: 'person' | 'tool'; tool?: { id: string; name: string } }> {
109
+ const actor = currentAuditContext()?.exchange?.actor
110
+ return actor
111
+ ? { by: 'tool', tool: { id: actor.id, name: actor.name ?? actor.id } }
112
+ : { by: 'person' }
113
+ }
114
+
115
+ /** Story 395: the unserved changes a page needs, once a host reports what is served. */
116
+ async function needsOf(tx: Db, key: string) {
117
+ const view = await servedView(tx)
118
+ if (!view) return {}
119
+ const page = await new DocumentRepository(tx).byKey(key)
120
+ return page ? { needs: neededBy(view, page) } : {}
121
+ }
122
+
78
123
  export function createContentEventSink(options: ContentEventSinkOptions): EventSink {
79
124
  /** A person's own write in the back office or the API, not a merge's nor the site's code. */
80
125
  const ownEdit = (actor: Actor) => actor.kind === 'user' && !actor.origin.via
@@ -86,9 +131,15 @@ export function createContentEventSink(options: ContentEventSinkOptions): EventS
86
131
  if (!key || !userKey || !ownEdit(actor)) return
87
132
  const changes = new ChangeRepository(tx)
88
133
  if (SAVES.has(event.type)) await changes.pageSavedBy(userKey, { key, kind: 'document' })
89
- if (!PUBLISHES.has(event.type)) return
90
- const change = await changes.publishedBy(userKey, { key, kind: 'document' })
91
- if (!change) return
134
+ // Story 395: setting or clearing a schedule is passed on as a publish is.
135
+ const scheduled = event.type === 'scheduled'
136
+ if (!PUBLISHES.has(event.type) && !scheduled) return
137
+ const schedule = await new DocumentRepository(tx).schedules(key)
138
+ if (scheduled || schedule.length > 0)
139
+ await changes.scheduleOf(userKey, { key, kind: 'document' }, scheduleEntries(schedule))
140
+ const closed = await changes.publishedBy(userKey, { key, kind: 'document' })
141
+ if (!closed) return
142
+ const change = { ...closed, ...(await madeBy()), ...(await needsOf(tx, key)) }
92
143
  const hook = { alias: CHANGE_PUBLISHED, key }
93
144
  await new ContentEventRepository(tx).record({
94
145
  kind: 'change-published',
@@ -62,6 +62,8 @@ export interface IdentityProviderOptions {
62
62
  /** How a provider's tokens are exchanged at the remote (stories 364 and 366). */
63
63
  export interface RemoteExchangeOptions {
64
64
  audience?: string
65
+ /** The audience of a token exchanged for applying a change (story 394). */
66
+ applyAudience?: string
65
67
  actors?: Readonly<Record<string, string>>
66
68
  }
67
69
 
@@ -248,12 +250,27 @@ export function exchangeAudienceClashes(
248
250
  backoffice: readonly IdentityProvider[],
249
251
  ): string[] {
250
252
  return exchanging.flatMap((provider) => {
251
- const audience = provider.remoteExchange?.audience
253
+ const { audience, applyAudience } = provider.remoteExchange ?? {}
252
254
  const clash = audience ? backoffice.find((p) => p.oidc.clientId === audience) : undefined
253
- return clash
254
- ? [
255
- `The ${provider.oidc.name} identity provider's remoteExchange audience is the client id ${clash.oidc.name} signs in with. Name the audience of an app used only for the remote, so a sign-in token can never be exchanged.`,
256
- ]
257
- : []
255
+ const applyClash = applyAudience
256
+ ? backoffice.find((p) => p.oidc.clientId === applyAudience)
257
+ : undefined
258
+ return [
259
+ ...(clash
260
+ ? [
261
+ `The ${provider.oidc.name} identity provider's remoteExchange audience is the client id ${clash.oidc.name} signs in with. Name the audience of an app used only for the remote, so a sign-in token can never be exchanged.`,
262
+ ]
263
+ : []),
264
+ ...(applyClash
265
+ ? [
266
+ `The ${provider.oidc.name} identity provider's remoteExchange applyAudience is the client id ${applyClash.oidc.name} signs in with. Name the audience of an app used only for applying changes.`,
267
+ ]
268
+ : []),
269
+ ...(applyAudience !== undefined && applyAudience === audience
270
+ ? [
271
+ `The ${provider.oidc.name} identity provider's remoteExchange applyAudience is its audience. Name another, so a token for applying changes is told apart from any other.`,
272
+ ]
273
+ : []),
274
+ ]
258
275
  })
259
276
  }
package/src/principal.ts CHANGED
@@ -31,7 +31,14 @@ export async function principalOf(
31
31
  )),
32
32
  ...(identity.viewingAs ? { viewingAs: identity.viewingAs } : {}),
33
33
  ...(viaToken ? { viaToken } : {}),
34
- ...(identity.exchangedThrough ? { viaExchange: { provider: identity.exchangedThrough } } : {}),
34
+ ...(identity.exchangedThrough
35
+ ? {
36
+ viaExchange: {
37
+ provider: identity.exchangedThrough,
38
+ ...(identity.exchangedForApplying ? { forApplying: true as const } : {}),
39
+ },
40
+ }
41
+ : {}),
35
42
  ...(identity.viaClient ? { viaClient: identity.viaClient } : {}),
36
43
  }
37
44
  }
@@ -6,7 +6,8 @@
6
6
  * Install code too when the change carries templates or the site's own code.
7
7
  * docs/changes.md.
8
8
  */
9
- import { mkdtempSync, rmSync } from 'node:fs'
9
+ import { createHash } from 'node:crypto'
10
+ import { createWriteStream, mkdtempSync, rmSync } from 'node:fs'
10
11
  import { tmpdir } from 'node:os'
11
12
  import { join } from 'node:path'
12
13
  import type { Principal } from '@crombolo/api-management/domain'
@@ -47,6 +48,44 @@ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
47
48
  const ONE = /^changes\/([0-9a-f-]{36})\/bundle$/i
48
49
  const WORKSPACE = /^workspaces\/([0-9a-f-]{36})\/change$/i
49
50
 
51
+ /**
52
+ * Whether the principal may stage or apply a change (story 394): Apply changes, and
53
+ * under `exchange` only for a sign-in exchanged for applying one.
54
+ */
55
+ export const mayApplyChanges = (
56
+ principal: Principal,
57
+ by: 'any' | 'exchange',
58
+ may: (principal: Principal, verb: RemoteVerb) => boolean,
59
+ ) =>
60
+ may(principal, RemotePermissions.ApplyChanges) &&
61
+ (by === 'any' || principal.viaExchange?.forApplying === true)
62
+
63
+ /** Streams a request body to a file, hashing it as it goes; undefined when it carried none. */
64
+ export async function streamBody(
65
+ request: Request,
66
+ path: string,
67
+ maxBytes: number,
68
+ ): Promise<{ sha256: string; size: number } | undefined> {
69
+ if (!request.body) return undefined
70
+ const hasher = createHash('sha256')
71
+ let size = 0
72
+ const sink = createWriteStream(path)
73
+ const reader = request.body.getReader()
74
+ try {
75
+ for (;;) {
76
+ const { done, value } = await reader.read()
77
+ if (done) break
78
+ size += value.length
79
+ if (size > maxBytes) throw new Error('too large')
80
+ hasher.update(value)
81
+ if (!sink.write(value)) await new Promise((r) => sink.once('drain', r))
82
+ }
83
+ } finally {
84
+ await new Promise<void>((resolve) => sink.end(() => resolve()))
85
+ }
86
+ return { sha256: hasher.digest('hex'), size }
87
+ }
88
+
50
89
  /** A change bundle packed as a tarball, as it travels. */
51
90
  export function packChange(change: ChangeBundle, media: ReadonlyMap<string, Uint8Array>) {
52
91
  const encoder = new TextEncoder()
@@ -100,6 +100,8 @@ export interface ExchangeAccounts {
100
100
  seconds: number,
101
101
  ip: string | undefined,
102
102
  actor: ExchangeActor | undefined,
103
+ /** Exchanged for applying a change (story 394), by the provider's apply audience. */
104
+ forApplying?: boolean,
103
105
  ): Promise<{ accessToken: string } | { refused: string }>
104
106
  }
105
107
 
@@ -261,6 +263,7 @@ export function createPeopleExchange(options: {
261
263
  )
262
264
 
263
265
  const audience = audienceOf(provider, url.origin)
266
+ const applyAudience = provider.remoteExchange?.applyAudience
264
267
  const signInClients = await Promise.all(
265
268
  options.backoffice.map(
266
269
  async (p) => (await options.resolve(p).catch(() => p)).oidc.clientId,
@@ -268,12 +271,14 @@ export function createPeopleExchange(options: {
268
271
  )
269
272
  if (signInClients.includes(audience))
270
273
  return refuse(request, ip, 'its audience is a sign-in client id', provider)
274
+ if (applyAudience && (applyAudience === audience || signInClients.includes(applyAudience)))
275
+ return refuse(request, ip, 'its audience for applying changes is not its own', provider)
271
276
 
272
277
  let claims: JWTPayload
273
278
  try {
274
279
  ;({ payload: claims } = await jwtVerify(token, await keysOf(issuer), {
275
280
  issuer,
276
- audience,
281
+ audience: applyAudience ? [audience, applyAudience] : audience,
277
282
  algorithms: ASYMMETRIC,
278
283
  requiredClaims: ['exp', 'iat'],
279
284
  }))
@@ -285,6 +290,10 @@ export function createPeopleExchange(options: {
285
290
  provider,
286
291
  )
287
292
  }
293
+ const audiences = typeof claims.aud === 'string' ? [claims.aud] : (claims.aud ?? [])
294
+ const forApplying = applyAudience !== undefined && audiences.includes(applyAudience)
295
+ if (forApplying && audiences.includes(audience))
296
+ return refuse(request, ip, 'it names both of its audiences', provider)
288
297
  if (claims.nonce !== undefined)
289
298
  return refuse(request, ip, 'it is a sign-in ID token, which carries a nonce', provider)
290
299
  const exp = claims.exp as number
@@ -322,6 +331,7 @@ export function createPeopleExchange(options: {
322
331
  PERSON_TOKEN_SECONDS,
323
332
  ip,
324
333
  actor,
334
+ forApplying,
325
335
  )
326
336
  if ('refused' in signedIn) return refuse(request, ip, signedIn.refused, provider)
327
337
  await options.onExchange({ ok: true, provider, account, actor }, request)
package/src/remote.ts CHANGED
@@ -78,7 +78,12 @@ import { type MediaStore, streamOf } from './media-store.ts'
78
78
  import { siteMemberPorts } from './member-admin.ts'
79
79
  import { describeProvenance, provenanceProblem, verifyProvenance } from './provenance.ts'
80
80
  import { createBackgroundJobRoutes } from './remote-background-jobs.ts'
81
- import { type ChangeRouteOptions, createChangeRoutes } from './remote-changes.ts'
81
+ import {
82
+ type ChangeRouteOptions,
83
+ createChangeRoutes,
84
+ mayApplyChanges,
85
+ streamBody,
86
+ } from './remote-changes.ts'
82
87
  import { createCiSignIn, readRuleInput, trustedIssuers, unverifiedIssuer } from './remote-ci.ts'
83
88
  import { createExtensionActivityRoutes } from './remote-extension-activity.ts'
84
89
  import { createMediaLibraryRoutes } from './remote-media-library.ts'
@@ -359,7 +364,10 @@ export function createRemote(options: RemoteOptions): Remote {
359
364
  problem,
360
365
  atLeast,
361
366
  notAtLevel,
362
- may,
367
+ may: (principal, verb) =>
368
+ verb === RemotePermissions.ApplyChanges
369
+ ? mayApplyChanges(principal, config.applyChangesBy, may)
370
+ : may(principal, verb),
363
371
  receive: (request, path) => receive(request, path),
364
372
  })
365
373
  : undefined
@@ -789,28 +797,11 @@ export function createRemote(options: RemoteOptions): Remote {
789
797
  }
790
798
 
791
799
  /** Streams a request body to a file, hashing it as it goes; undefined when it is not what it claimed. */
792
- async function receive(
800
+ function receive(
793
801
  request: Request,
794
802
  path: string,
795
803
  ): Promise<{ sha256: string; size: number } | undefined> {
796
- if (!request.body) return undefined
797
- const hasher = createHash('sha256')
798
- let size = 0
799
- const sink = createWriteStream(path)
800
- const reader = request.body.getReader()
801
- try {
802
- for (;;) {
803
- const { done, value } = await reader.read()
804
- if (done) break
805
- size += value.length
806
- if (size > settings.maxUploadBytes) throw new Error('too large')
807
- hasher.update(value)
808
- if (!sink.write(value)) await new Promise((r) => sink.once('drain', r))
809
- }
810
- } finally {
811
- await new Promise<void>((resolve) => sink.end(() => resolve()))
812
- }
813
- return { sha256: hasher.digest('hex'), size }
804
+ return streamBody(request, path, settings.maxUploadBytes)
814
805
  }
815
806
 
816
807
  /** The options a site apply was sent with, in `Crombolo-Options` (story 167). */
@@ -1628,7 +1619,7 @@ export function createRemote(options: RemoteOptions): Remote {
1628
1619
  applyChanges:
1629
1620
  Boolean(changeRoutes?.capabilities().length) &&
1630
1621
  atLeast('content') &&
1631
- may(principal, RemotePermissions.ApplyChanges),
1622
+ mayApplyChanges(principal, config.applyChangesBy, may),
1632
1623
  },
1633
1624
  },
1634
1625
  ])
@@ -1811,6 +1802,7 @@ export function createRemote(options: RemoteOptions): Remote {
1811
1802
  return (
1812
1803
  url.pathname === `${prefix}pushes` ||
1813
1804
  url.pathname === `${prefix}bundles` ||
1805
+ url.pathname === `${prefix}changes` ||
1814
1806
  url.pathname.startsWith(`${prefix}media/`) ||
1815
1807
  (mediaLibraryRoutes?.isUpload(url.pathname.slice(prefix.length), request.method) ?? false)
1816
1808
  )
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Story 395's routes. A host reports each change it applied to the served copy
3
+ * (`PUT <plugin>/api/changes/served`) and reads back the newest (`GET`), and leaves
4
+ * a person a notice of how it went (`POST <plugin>/api/notices`): each needs Apply
5
+ * changes. The back office takes a person's own notices (`GET .../notices/mine`).
6
+ */
7
+
8
+ import type { Principal } from '@crombolo/api-management/domain'
9
+ import { normaliseUuid } from '@crombolo/core'
10
+ import {
11
+ BackofficeNoticeRepository,
12
+ ChangeRepository,
13
+ type Db,
14
+ ServedChangeRepository,
15
+ } from '@crombolo/data'
16
+ import { servedView } from './served-schema.ts'
17
+
18
+ export interface ServedApiOptions {
19
+ /** Whether the caller may apply changes here, as the change routes decide it. */
20
+ mayApply(principal: Principal): Promise<boolean>
21
+ }
22
+
23
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
24
+ const json = (body: unknown, status = 200) => Response.json(body, { status })
25
+ const refused = (message: string, status: number) => json({ message }, status)
26
+
27
+ /** A link a notice may carry: a path in the back office, or a web address. Pure. */
28
+ export const noticeLink = (link: unknown): string | null | undefined => {
29
+ if (link === undefined || link === null || link === '') return null
30
+ if (typeof link !== 'string' || link.length > 1000) return undefined
31
+ if (link.startsWith('/') && !link.startsWith('//')) return link
32
+ try {
33
+ const url = new URL(link)
34
+ return url.protocol === 'https:' || url.protocol === 'http:' ? url.href : undefined
35
+ } catch {
36
+ return undefined
37
+ }
38
+ }
39
+
40
+ export function createServedApi(db: Db, options: ServedApiOptions) {
41
+ const served = new ServedChangeRepository(db)
42
+ const notices = new BackofficeNoticeRepository(db)
43
+
44
+ async function servedRoute(request: Request, principal: Principal): Promise<Response> {
45
+ if (!(await options.mayApply(principal)))
46
+ return refused('Reporting what the live site holds needs the Apply changes right.', 403)
47
+ if (request.method === 'PUT') {
48
+ const body = (await request.json().catch(() => undefined)) as { key?: unknown } | undefined
49
+ const key = typeof body?.key === 'string' ? body.key.trim() : ''
50
+ if (!UUID.test(key)) return refused('Name the change applied there by its key.', 400)
51
+ const held = await new ChangeRepository(db).held([key])
52
+ if (!held.has(normaliseUuid(key))) return refused('There is no such change here.', 404)
53
+ await served.report(key, principal.id)
54
+ } else if (request.method !== 'GET') return new Response(null, { status: 405 })
55
+ const newest = await served.newest()
56
+ const view = await servedView(db)
57
+ const waiting = new Set(
58
+ [...(view?.pending.values() ?? [])].flatMap((i) => i.changes.map((c) => c.key)),
59
+ )
60
+ return json({
61
+ newest: newest
62
+ ? { key: newest.key, name: newest.name, reportedAt: newest.reportedAt.toISOString() }
63
+ : null,
64
+ waiting: waiting.size,
65
+ })
66
+ }
67
+
68
+ async function post(request: Request, principal: Principal): Promise<Response> {
69
+ if (!(await options.mayApply(principal)))
70
+ return refused('Leaving someone a notice needs the Apply changes right.', 403)
71
+ const body = (await request.json().catch(() => undefined)) as
72
+ | Record<string, unknown>
73
+ | undefined
74
+ const user = typeof body?.user === 'string' ? body.user.trim() : ''
75
+ if (!UUID.test(user)) return refused('Name the person by their key.', 400)
76
+ const message = typeof body?.message === 'string' ? body.message.trim() : ''
77
+ if (!message || message.length > 1000)
78
+ return refused('Say what happened, in at most 1000 characters.', 400)
79
+ const kind = body?.kind ?? 'success'
80
+ if (kind !== 'success' && kind !== 'failure')
81
+ return refused('A notice is a success or a failure.', 400)
82
+ const link = noticeLink(body?.link)
83
+ if (link === undefined) return refused('A link is a back office path or a web address.', 400)
84
+ const found = await db.q
85
+ .selectFrom('user_account')
86
+ .select('id')
87
+ .where('key', '=', normaliseUuid(user))
88
+ .execute()
89
+ if (found.length === 0) return refused('There is no such person here.', 404)
90
+ const id = await notices.add({ userKey: user, kind, message, link })
91
+ return json({ id }, 201)
92
+ }
93
+
94
+ return {
95
+ /** Answers the route at `rest` under the changes path, if it is this one. */
96
+ async changes(
97
+ request: Request,
98
+ principal: Principal,
99
+ rest: string,
100
+ ): Promise<Response | undefined> {
101
+ return rest === '/served' ? servedRoute(request, principal) : undefined
102
+ },
103
+
104
+ /** Answers `<plugin>/api/notices` and `/notices/mine`. */
105
+ async notices(request: Request, principal: Principal, rest: string): Promise<Response> {
106
+ if (rest === '' && request.method === 'POST') return post(request, principal)
107
+ if (rest === '/mine' && request.method === 'GET') {
108
+ const taken = await notices.take(principal.id)
109
+ return json({
110
+ items: taken.map((n) => ({
111
+ kind: n.kind,
112
+ message: n.message,
113
+ link: n.link,
114
+ createdAt: n.createdAt.toISOString(),
115
+ })),
116
+ })
117
+ }
118
+ return new Response(null, { status: rest === '' || rest === '/mine' ? 405 : 404 })
119
+ },
120
+ }
121
+ }