@crombolo/server 0.19.0 → 0.21.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.19.0",
3
+ "version": "0.21.0",
4
4
  "description": "The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -30,17 +30,17 @@
30
30
  "access": "public"
31
31
  },
32
32
  "dependencies": {
33
- "@crombolo/api-delivery": "0.19.0",
34
- "@crombolo/api-management": "0.19.0",
35
- "@crombolo/assistant": "0.19.0",
36
- "@crombolo/auth": "0.19.0",
37
- "@crombolo/backoffice-host": "0.19.0",
38
- "@crombolo/contracts": "0.19.0",
39
- "@crombolo/core": "0.19.0",
40
- "@crombolo/data": "0.19.0",
41
- "@crombolo/render": "0.19.0",
42
- "@crombolo/schema": "0.19.0",
43
- "@crombolo/transfer": "0.19.0",
33
+ "@crombolo/api-delivery": "0.21.0",
34
+ "@crombolo/api-management": "0.21.0",
35
+ "@crombolo/assistant": "0.21.0",
36
+ "@crombolo/auth": "0.21.0",
37
+ "@crombolo/backoffice-host": "0.21.0",
38
+ "@crombolo/contracts": "0.21.0",
39
+ "@crombolo/core": "0.21.0",
40
+ "@crombolo/data": "0.21.0",
41
+ "@crombolo/render": "0.21.0",
42
+ "@crombolo/schema": "0.21.0",
43
+ "@crombolo/transfer": "0.21.0",
44
44
  "@logtape/logtape": "^2.3.8"
45
45
  }
46
46
  }
@@ -116,6 +116,7 @@ export function createDocumentPort(
116
116
  return {
117
117
  byKey: (key) => repo.byKey(key),
118
118
  propertyAliases: (key) => repo.propertyAliases(key),
119
+ propertyTypes: (key) => repo.propertyTypeKeys(key),
119
120
  byKeyPublished: (key) => repo.byKeyPublished(key),
120
121
  validate: (input, cultures) => repo.validate(input, cultures),
121
122
 
@@ -608,17 +608,15 @@ export function createUserPorts(
608
608
 
609
609
  async permissions(principal, tree, keys) {
610
610
  if (tree !== 'document') {
611
- // Media carries no verbs; element verbs are the groups' own until the Library exists
612
- const verbs =
613
- tree === 'element'
614
- ? [
615
- ...new Set(
616
- principal.groups.flatMap((g) =>
617
- g.defaults.filter((p) => p.startsWith('Umb.Element')),
618
- ),
619
- ),
620
- ]
621
- : []
611
+ // Media and element verbs are the groups' own: neither has per-node permissions
612
+ const prefixes = tree === 'element' ? ['Umb.Element'] : ['Crombolo.Media.']
613
+ const verbs = [
614
+ ...new Set(
615
+ principal.groups.flatMap((g) =>
616
+ g.defaults.filter((p) => prefixes.some((prefix) => p.startsWith(prefix))),
617
+ ),
618
+ ),
619
+ ]
622
620
  return keys.map((nodeKey) => ({ nodeKey: normaliseUuid(nodeKey), permissions: verbs }))
623
621
  }
624
622
  const found = await nodes.documents(keys)
@@ -11,7 +11,13 @@ import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
11
11
  import { join } from 'node:path'
12
12
  import type { Principal } from '@crombolo/api-management'
13
13
  import type { SchemaWorkflow } from '@crombolo/core'
14
- import { type Db, readWorkflows, syncWorkflows, UserGroupRepository } from '@crombolo/data'
14
+ import {
15
+ type ApprovalScheduleEntry,
16
+ type Db,
17
+ readWorkflows,
18
+ syncWorkflows,
19
+ UserGroupRepository,
20
+ } from '@crombolo/data'
15
21
  import {
16
22
  fileNameFor,
17
23
  loadSchemaDirectory,
@@ -51,12 +57,27 @@ async function changePreview(approvals: Approvals, principal: Principal, workflo
51
57
  )
52
58
  const version = workflowVersion(workflow)
53
59
  if (stored && stored.version === version) return []
60
+ // A scheduled request is decided already: a change leaves it alone.
54
61
  const waiting = (await approvals.inFlight(principal)).filter(
55
- (r) => (r.workflow.key ?? r.workflow.alias) === id,
62
+ (r) => r.state === 'waiting' && (r.workflow.key ?? r.workflow.alias) === id,
56
63
  )
57
64
  return waiting.map((r) => ({ key: r.key, page: r.nodeName, outcome: workflow.onChange }))
58
65
  }
59
66
 
67
+ /**
68
+ * `schedule`: `[{ culture, publishTime, unpublishTime }]`, times in ISO form.
69
+ * A time that does not parse stays an invalid date, which the engine refuses.
70
+ */
71
+ function readSchedule(value: unknown): ApprovalScheduleEntry[] | null {
72
+ if (!Array.isArray(value)) return null
73
+ const time = (t: unknown) => (typeof t === 'string' && t ? new Date(t) : null)
74
+ return value.map((e: Record<string, unknown>) => ({
75
+ culture: typeof e?.culture === 'string' && e.culture ? e.culture : null,
76
+ publishTime: time(e?.publishTime),
77
+ unpublishTime: time(e?.unpublishTime),
78
+ }))
79
+ }
80
+
60
81
  export async function handleApprovalsApi(
61
82
  request: Request,
62
83
  path: string,
@@ -81,6 +102,7 @@ export async function handleApprovalsApi(
81
102
  b.action === 'unpublish' ? 'unpublish' : 'publish',
82
103
  cultures && cultures.length > 0 ? cultures : null,
83
104
  text(b.comment),
105
+ readSchedule(b.schedule),
84
106
  ),
85
107
  )
86
108
  }
package/src/approvals.ts CHANGED
@@ -5,7 +5,8 @@
5
5
  *
6
6
  * The graph rules are `@crombolo/core`'s; the record is `ApprovalRepository`'s.
7
7
  * This decides: who may act, what an edit does to a waiting request, when a
8
- * stage is done, and when the page is published.
8
+ * stage is done, and when the page is published — at once, or at the time the
9
+ * request asked for (story 029), the schedule job doing the publishing.
9
10
  */
10
11
 
11
12
  import type { Principal } from '@crombolo/api-management'
@@ -13,6 +14,7 @@ import {
13
14
  approvalsNeeded,
14
15
  DocumentPermissions,
15
16
  descendantStages,
17
+ hasPathAccess,
16
18
  normaliseUuid,
17
19
  permissionsForPath,
18
20
  type SchemaWorkflow,
@@ -27,6 +29,7 @@ import {
27
29
  ApprovalRepository,
28
30
  type ApprovalRepository as ApprovalRepositoryType,
29
31
  type ApprovalRequest,
32
+ type ApprovalScheduleEntry,
30
33
  type ApprovalStep,
31
34
  AuditLog,
32
35
  type Db,
@@ -78,6 +81,7 @@ interface PageFacts {
78
81
  key: string
79
82
  name: string
80
83
  chain: string[]
84
+ trashed: boolean
81
85
  contentTypeAlias: string | undefined
82
86
  variesByCulture: boolean
83
87
  }
@@ -100,6 +104,12 @@ export interface RequestView {
100
104
  action: ApprovalAction
101
105
  cultures: string[] | null
102
106
  state: ApprovalRequest['state']
107
+ /** The times it asked for, in ISO form; null to publish on approval. */
108
+ schedule: Array<{
109
+ culture: string | null
110
+ publishTime: string | null
111
+ unpublishTime: string | null
112
+ }> | null
103
113
  requestedBy: string
104
114
  requestedAt: string
105
115
  workflow: SchemaWorkflow
@@ -141,12 +151,24 @@ export interface Approvals {
141
151
  beforeSave(principal: Principal, key: string): Promise<string | undefined>
142
152
  /** What the save does to a waiting request, once it has gone through. */
143
153
  afterSave(principal: Principal, key: string): Promise<void>
154
+ /** A direct publish, schedule or unpublish by someone allowed to: a scheduled request ends. */
155
+ afterDirectPublish(principal: Principal, key: string, what: string): Promise<void>
156
+ /** The schedule job fired one of a page's schedules: a scheduled request goes on or ends. */
157
+ scheduleFired(
158
+ key: string,
159
+ culture: string | null,
160
+ action: 'Release' | 'Expire',
161
+ result: { ok: true } | { ok: false; reason: string },
162
+ ): Promise<void>
163
+ /** Ends scheduled requests whose schedule is gone: the recycle bin, an import, the CLI. */
164
+ sweepScheduled(now?: number): Promise<void>
144
165
  send(
145
166
  principal: Principal,
146
167
  key: string,
147
168
  action: ApprovalAction,
148
169
  cultures: string[] | null,
149
170
  comment?: string,
171
+ schedule?: ApprovalScheduleEntry[] | null,
150
172
  ): Promise<RequestView>
151
173
  approve(
152
174
  principal: Principal,
@@ -172,12 +194,69 @@ export interface Approvals {
172
194
  ): Promise<{ total: number; items: RequestView[] }>
173
195
  }
174
196
 
197
+ const SWEEP_GRACE_MS = 5 * 60_000
198
+
199
+ /** A time as a person reads it in a history or an e-mail, in UTC. Pure. */
200
+ export const describeTime = (time: Date): string =>
201
+ `${time.toISOString().slice(0, 16).replace('T', ' ')} UTC`
202
+
203
+ /** "published at …" for each time a request asks for, culture by culture. Pure. */
204
+ export function describeSchedule(
205
+ action: ApprovalAction,
206
+ entries: readonly ApprovalScheduleEntry[],
207
+ ): string {
208
+ return entries
209
+ .flatMap((e) => {
210
+ const culture = e.culture ? ` (${e.culture})` : ''
211
+ return [
212
+ ...(action === 'publish' && e.publishTime
213
+ ? [`published at ${describeTime(e.publishTime)}${culture}`]
214
+ : []),
215
+ ...(e.unpublishTime ? [`taken down at ${describeTime(e.unpublishTime)}${culture}`] : []),
216
+ ]
217
+ })
218
+ .join(', ')
219
+ }
220
+
221
+ /** Why a request may not carry these times, or undefined when it may. Pure. */
222
+ export function scheduleRefusal(
223
+ workflow: SchemaWorkflow,
224
+ action: ApprovalAction,
225
+ cultures: readonly string[] | null,
226
+ entries: readonly ApprovalScheduleEntry[],
227
+ now = Date.now(),
228
+ ): string | undefined {
229
+ if (entries.length === 0) return undefined
230
+ if (!workflow.scheduling)
231
+ return `"${workflow.name}" does not let a request say when to publish. Send it without a time.`
232
+ const named = new Set((cultures ?? []).map((c) => c.toLowerCase()))
233
+ const seen = new Set<string>()
234
+ for (const e of entries) {
235
+ if (action === 'unpublish' && e.publishTime)
236
+ return 'A request to take the page down can only say when to take it down.'
237
+ for (const time of [e.publishTime, e.unpublishTime])
238
+ if (time && (Number.isNaN(time.getTime()) || time.getTime() <= now))
239
+ return 'Pick a time in the future.'
240
+ if (e.publishTime && e.unpublishTime && e.unpublishTime <= e.publishTime)
241
+ return 'The page has to be taken down after it is published.'
242
+ const culture = e.culture?.toLowerCase() ?? null
243
+ if (culture === null ? cultures !== null : !named.has(culture))
244
+ return culture === null
245
+ ? 'This request names its languages: give each one its own time.'
246
+ : `"${e.culture}" is not one of the languages this request sends.`
247
+ if (seen.has(culture ?? '')) return 'Give each language one time.'
248
+ seen.add(culture ?? '')
249
+ }
250
+ return undefined
251
+ }
252
+
175
253
  export function createApprovals(options: ApprovalsOptions): Approvals {
176
254
  const { db } = options
177
255
  const requests = (tx: Db = db): ApprovalRepositoryType => new ApprovalRepository(tx)
178
256
  const nodes = new NodeRepository(db)
179
257
  const groups = new UserGroupRepository(db)
180
258
  const audit = new AuditLog(db)
259
+ const documents = () => new DocumentRepository(db, { nodeState: options.nodeState })
181
260
 
182
261
  const page = async (key: string): Promise<PageFacts | undefined> => {
183
262
  const node = await nodes.byKey(key)
@@ -196,6 +275,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
196
275
  key: node.key,
197
276
  name: node.text ?? node.key,
198
277
  chain: ids.flatMap((id) => keyOf.get(id) ?? []),
278
+ trashed: node.trashed,
199
279
  contentTypeAlias: type[0]?.alias,
200
280
  // Umbraco's flags: 1 is culture, 2 is segment.
201
281
  variesByCulture: (Number(type[0]?.variations ?? 0) & 1) === 1,
@@ -218,6 +298,19 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
218
298
  action === 'publish' ? DocumentPermissions.Publish : DocumentPermissions.Unpublish,
219
299
  )
220
300
 
301
+ /**
302
+ * Refuses, with a 403, a caller who cannot reach the page through their start
303
+ * nodes or lacks a verb on it: asking about a page needs what opening it does.
304
+ */
305
+ const assertMayReach = (principal: Principal, facts: PageFacts, verbs: readonly string[]) => {
306
+ const granted = permissionsForPath(principal.groups, facts.chain)
307
+ if (
308
+ !hasPathAccess(principal.startNodes.document, facts.chain, facts.trashed) ||
309
+ !verbs.every((verb) => granted.has(verb))
310
+ )
311
+ throw new ApprovalRefused('You do not have access to this page.', 403)
312
+ }
313
+
221
314
  const covers = (workflow: SchemaWorkflow | undefined, action: ApprovalAction) =>
222
315
  workflow !== undefined && (action === 'publish' || workflow.unpublish)
223
316
 
@@ -388,11 +481,66 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
388
481
  return false
389
482
  }
390
483
 
484
+ /** The time a request's entry asks it to act at: publish for a publish request, take down otherwise. */
485
+ const dueAt = (request: ApprovalRequest, entry: ApprovalScheduleEntry) =>
486
+ request.action === 'publish' ? entry.publishTime : entry.unpublishTime
487
+
488
+ /** Removes the schedule rows a request wrote, culture by culture. */
489
+ const clearSchedule = async (request: ApprovalRequest) => {
490
+ if (!request.schedule) return
491
+ await documents().setSchedule(
492
+ request.nodeKey,
493
+ request.schedule.map((e) => ({ culture: e.culture, publishTime: null, unpublishTime: null })),
494
+ )
495
+ }
496
+
497
+ /** An approved page that could not be published goes back to its editor with the reason. */
498
+ const unpublishable = async (
499
+ request: ApprovalRequest,
500
+ facts: PageFacts | undefined,
501
+ reason: string,
502
+ ) => {
503
+ const repo = requests()
504
+ await repo.setState(request.id, 'sent-back')
505
+ await repo.record(request.id, {
506
+ kind: 'sent-back',
507
+ comment: `approved, but it could not be ${request.action === 'publish' ? 'published' : 'taken down'}: ${reason}`,
508
+ })
509
+ await notify(
510
+ 'editor',
511
+ request,
512
+ [],
513
+ `Could not publish: ${facts?.name ?? 'a page'}`,
514
+ `"${facts?.name}" was approved but could not be published: ${reason}`,
515
+ )
516
+ }
517
+
518
+ /** The request is done: recorded as approved, and its editor told. */
519
+ const approved = async (request: ApprovalRequest, principal: Principal | undefined) => {
520
+ const facts = await page(request.nodeKey)
521
+ await requests().setState(request.id, 'approved')
522
+ await auditStep(
523
+ principal,
524
+ facts,
525
+ request.action === 'publish' ? 'Published on approval' : 'Unpublished on approval',
526
+ `through "${request.workflow.name}"`,
527
+ )
528
+ await notify(
529
+ 'editor',
530
+ request,
531
+ [],
532
+ `Approved: ${facts?.name ?? 'a page'}`,
533
+ `"${facts?.name}" was approved through "${request.workflow.name}" and is now ${request.action === 'publish' ? 'published' : 'taken down'}.`,
534
+ )
535
+ }
536
+
391
537
  /**
392
538
  * Publishes (or takes down) a fully approved page, outside any transaction:
393
539
  * publishing takes the content tree's lock, which must never be waited on
394
- * from inside one. A page that cannot be published goes back to its editor
395
- * with the reason, rather than sitting approved and unpublished.
540
+ * from inside one. What the request asked to happen later is scheduled
541
+ * instead, and the request stays open until it has. A page that cannot be
542
+ * published goes back to its editor with the reason, rather than sitting
543
+ * approved and unpublished.
396
544
  */
397
545
  const finish = async (
398
546
  request: ApprovalRequest,
@@ -400,48 +548,73 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
400
548
  ): Promise<void> => {
401
549
  const repo = requests()
402
550
  const facts = await page(request.nodeKey)
403
- const result =
404
- request.action === 'publish'
405
- ? await options.publisher.publish(request.nodeKey, request.cultures)
406
- : await options.publisher.unpublish(request.nodeKey, request.cultures)
407
- if (!result.ok) {
408
- await repo.setState(request.id, 'sent-back')
551
+ const now = Date.now()
552
+ const later: ApprovalScheduleEntry[] = []
553
+ const expires: ApprovalScheduleEntry[] = []
554
+ let cultures: string[] | null | undefined = request.cultures
555
+ let passed = false
556
+ if (request.schedule) {
557
+ const nowCultures: Array<string | null> = []
558
+ for (const entry of request.schedule) {
559
+ const due = dueAt(request, entry)
560
+ if (due && due.getTime() > now) {
561
+ later.push(request.action === 'publish' ? entry : { ...entry, publishTime: null })
562
+ continue
563
+ }
564
+ if (due) passed = true
565
+ nowCultures.push(entry.culture)
566
+ if (request.action === 'publish' && entry.unpublishTime)
567
+ expires.push({ ...entry, publishTime: null })
568
+ }
569
+ // Cultures the request names without a time publish on approval.
570
+ const timed = new Set(request.schedule.map((e) => e.culture?.toLowerCase()))
571
+ const untimed = (request.cultures ?? []).filter((c) => !timed.has(c.toLowerCase()))
572
+ cultures = nowCultures.includes(null)
573
+ ? request.cultures
574
+ : nowCultures.length + untimed.length > 0
575
+ ? [...(nowCultures as string[]), ...untimed]
576
+ : undefined
577
+ }
578
+ if (cultures !== undefined) {
579
+ const result =
580
+ request.action === 'publish'
581
+ ? await options.publisher.publish(request.nodeKey, cultures)
582
+ : await options.publisher.unpublish(request.nodeKey, cultures)
583
+ if (!result.ok) return unpublishable(request, facts, result.reason)
409
584
  await repo.record(request.id, {
410
- kind: 'sent-back',
411
- comment: `approved, but it could not be ${request.action === 'publish' ? 'published' : 'taken down'}: ${result.reason}`,
585
+ kind: request.action === 'publish' ? 'published' : 'unpublished',
586
+ userKey: principal?.id ?? null,
587
+ comment: passed ? 'the requested time had passed when it was approved' : null,
412
588
  })
413
- await notify(
414
- 'editor',
415
- request,
416
- [],
417
- `Could not publish: ${facts?.name ?? 'a page'}`,
418
- `"${facts?.name}" was approved but could not be published: ${result.reason}`,
419
- )
420
- return
589
+ if (request.action === 'publish')
590
+ await options.notifier?.raise(
591
+ { actions: ['Umb.Document.Publish'], key: request.nodeKey, keyKind: 'document' },
592
+ principal ? { key: principal.id, name: principal.name } : null,
593
+ `approved through "${request.workflow.name}"`,
594
+ )
421
595
  }
422
- await repo.setState(request.id, 'approved')
596
+ if (later.length + expires.length > 0)
597
+ await documents().setSchedule(request.nodeKey, [...later, ...expires])
598
+ if (later.length === 0) return approved(request, principal)
599
+ const when = describeSchedule(request.action, later)
600
+ await repo.setState(request.id, 'scheduled')
423
601
  await repo.record(request.id, {
424
- kind: request.action === 'publish' ? 'published' : 'unpublished',
602
+ kind: 'scheduled',
425
603
  userKey: principal?.id ?? null,
604
+ comment: when,
426
605
  })
427
606
  await auditStep(
428
607
  principal,
429
608
  facts,
430
- request.action === 'publish' ? 'Published on approval' : 'Unpublished on approval',
431
- `through "${request.workflow.name}"`,
609
+ 'Scheduled on approval',
610
+ `${when}, through "${request.workflow.name}"`,
432
611
  )
433
- if (request.action === 'publish')
434
- await options.notifier?.raise(
435
- { actions: ['Umb.Document.Publish'], key: request.nodeKey, keyKind: 'document' },
436
- principal ? { key: principal.id, name: principal.name } : null,
437
- `approved through "${request.workflow.name}"`,
438
- )
439
612
  await notify(
440
613
  'editor',
441
614
  request,
442
615
  [],
443
616
  `Approved: ${facts?.name ?? 'a page'}`,
444
- `"${facts?.name}" was approved through "${request.workflow.name}" and is now ${request.action === 'publish' ? 'published' : 'taken down'}.`,
617
+ `"${facts?.name}" was approved through "${request.workflow.name}" and will be ${when}.`,
445
618
  )
446
619
  }
447
620
 
@@ -501,6 +674,12 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
501
674
  action: request.action,
502
675
  cultures: request.cultures,
503
676
  state: request.state,
677
+ schedule:
678
+ request.schedule?.map((e) => ({
679
+ culture: e.culture,
680
+ publishTime: e.publishTime?.toISOString() ?? null,
681
+ unpublishTime: e.unpublishTime?.toISOString() ?? null,
682
+ })) ?? null,
504
683
  requestedBy: request.requestedBy,
505
684
  requestedAt: request.requestedAt.toISOString(),
506
685
  workflow: request.workflow,
@@ -518,7 +697,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
518
697
  ? []
519
698
  : actionable.filter((s) => !already(s.alias)).map((s) => s.alias),
520
699
  sendBack: actionable.map((s) => s.alias),
521
- withdraw: waiting && (ownChange || principal.isAdmin),
700
+ withdraw: (waiting || request.state === 'scheduled') && (ownChange || principal.isAdmin),
522
701
  },
523
702
  }
524
703
  }
@@ -586,6 +765,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
586
765
  key: '',
587
766
  name: 'This page',
588
767
  chain: parent?.chain ?? [],
768
+ trashed: false,
589
769
  contentTypeAlias: type[0]?.alias,
590
770
  variesByCulture: false,
591
771
  }
@@ -593,9 +773,14 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
593
773
  },
594
774
 
595
775
  async beforeSave(principal, key) {
596
- const request = await requests().waitingFor(key)
776
+ const request = await requests().openFor(key)
597
777
  if (!request || principal.isAdmin) return undefined
598
778
  const edit = request.workflow.onEdit
779
+ if (request.state === 'scheduled') {
780
+ if (edit === 'lock' || edit === 'lock-after-first-approval')
781
+ return `This page is approved and will be ${describeSchedule(request.action, request.schedule ?? [])}. It cannot be changed until then; withdraw the request to change it.`
782
+ return undefined
783
+ }
599
784
  if (edit === 'lock')
600
785
  return 'This page is waiting for approval and cannot be changed until it is decided.'
601
786
  if (edit === 'lock-after-first-approval') {
@@ -608,7 +793,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
608
793
 
609
794
  async afterSave(principal, key) {
610
795
  const repo = requests()
611
- const request = await repo.waitingFor(key)
796
+ const request = await repo.openFor(key)
612
797
  if (!request) return
613
798
  const head =
614
799
  (await new DocumentRepository(db, { nodeState: options.nodeState }).eventMarkers(key))
@@ -622,15 +807,17 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
622
807
  userKey: principal.id,
623
808
  comment: 'the page was changed after it was sent',
624
809
  })
810
+ if (request.state === 'scheduled') await clearSchedule(request)
625
811
  return
626
812
  }
627
813
  await repo.setEvent(request.id, head)
628
814
  await repo.record(request.id, { kind: 'edited', userKey: principal.id })
629
815
  },
630
816
 
631
- async send(principal, key, action, cultures, comment) {
817
+ async send(principal, key, action, cultures, comment, schedule) {
632
818
  const facts = await page(key)
633
819
  if (!facts) throw new ApprovalRefused('The page could not be found.', 404)
820
+ assertMayReach(principal, facts, [DocumentPermissions.Read, DocumentPermissions.Update])
634
821
  const workflow = await covering(facts)
635
822
  if (!workflow || !covers(workflow, action))
636
823
  throw new ApprovalRefused(
@@ -638,13 +825,22 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
638
825
  ? 'No workflow covers this page: it can be published directly.'
639
826
  : 'Taking this page down needs no approval.',
640
827
  )
828
+ const timed = (schedule ?? []).filter((e) => e.publishTime || e.unpublishTime)
829
+ const refusal = scheduleRefusal(workflow, action, cultures, timed)
830
+ if (refusal) throw new ApprovalRefused(refusal)
641
831
  const stored = (await readWorkflows(db)).find(
642
832
  (s) => (s.workflow.key ?? s.workflow.alias) === (workflow.key ?? workflow.alias),
643
833
  )
644
834
  const outcome = await db.transaction(async (tx) => {
645
835
  const repo = requests(tx)
646
- if (await repo.waitingFor(key))
647
- throw new ApprovalRefused('This page is already waiting for approval.', 409)
836
+ const open = await repo.openFor(key)
837
+ if (open)
838
+ throw new ApprovalRefused(
839
+ open.state === 'scheduled'
840
+ ? `This page is already approved and will be ${describeSchedule(open.action, open.schedule ?? [])}. Withdraw that request to send it with another time.`
841
+ : 'This page is already waiting for approval.',
842
+ 409,
843
+ )
648
844
  const head =
649
845
  (await new DocumentRepository(tx, { nodeState: options.nodeState }).eventMarkers(key))
650
846
  ?.head ?? null
@@ -656,11 +852,13 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
656
852
  workflow,
657
853
  workflowVersion: stored?.version ?? '',
658
854
  requestedBy: principal.id,
855
+ schedule: timed.length > 0 ? timed : null,
659
856
  })
857
+ const when = timed.length > 0 ? describeSchedule(action, timed) : ''
660
858
  await repo.record(request.id, {
661
859
  kind: 'sent',
662
860
  userKey: principal.id,
663
- comment: comment?.trim() || null,
861
+ comment: [comment?.trim(), when && `to be ${when}`].filter(Boolean).join('\n\n') || null,
664
862
  })
665
863
  const first = startStages(workflow)
666
864
  await reach(repo, request, first)
@@ -669,7 +867,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
669
867
  request,
670
868
  first,
671
869
  `Waiting for your approval: ${facts.name}`,
672
- `${principal.name} sent "${facts.name}" for approval through "${workflow.name}".${comment ? `\n\n${comment}` : ''}`,
870
+ `${principal.name} sent "${facts.name}" for approval through "${workflow.name}".${when ? ` It is to be ${when}.` : ''}${comment ? `\n\n${comment}` : ''}`,
673
871
  )
674
872
  const complete = await settle(repo, request)
675
873
  await auditStep(
@@ -784,7 +982,10 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
784
982
  },
785
983
 
786
984
  async withdraw(principal, requestKey) {
787
- const request = await waitingRequest(requestKey)
985
+ const request = await requests().byKey(requestKey)
986
+ if (!request) throw new ApprovalRefused('There is no such request.', 404)
987
+ if (request.state !== 'waiting' && request.state !== 'scheduled')
988
+ throw new ApprovalRefused('This request has already been decided.', 409)
788
989
  if (normaliseUuid(principal.id) !== request.requestedBy && !principal.isAdmin)
789
990
  throw new ApprovalRefused(
790
991
  'Only the person who sent it, or an administrator, can withdraw it.',
@@ -792,6 +993,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
792
993
  )
793
994
  await requests().setState(request.id, 'withdrawn')
794
995
  await requests().record(request.id, { kind: 'withdrawn', userKey: principal.id })
996
+ if (request.state === 'scheduled') await clearSchedule(request)
795
997
  await auditStep(
796
998
  principal,
797
999
  await page(request.nodeKey),
@@ -801,12 +1003,89 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
801
1003
  return view(principal, (await requests().byKey(request.key)) as ApprovalRequest)
802
1004
  },
803
1005
 
1006
+ async afterDirectPublish(principal, key, what) {
1007
+ const repo = requests()
1008
+ const request = await repo.openFor(key)
1009
+ if (request?.state !== 'scheduled') return
1010
+ await repo.setState(request.id, 'superseded')
1011
+ await repo.record(request.id, {
1012
+ kind: 'superseded',
1013
+ userKey: principal.id,
1014
+ comment: `${principal.name} ${what} directly`,
1015
+ })
1016
+ await auditStep(
1017
+ principal,
1018
+ await page(key),
1019
+ 'Superseded approval request',
1020
+ `scheduled under "${request.workflow.name}"`,
1021
+ )
1022
+ },
1023
+
1024
+ async scheduleFired(key, culture, action, result) {
1025
+ const repo = requests()
1026
+ const request = await repo.openFor(key)
1027
+ if (request?.state !== 'scheduled' || !request.schedule) return
1028
+ // An expiry on a page a request published is an ordinary schedule by then.
1029
+ if (action !== (request.action === 'publish' ? 'Release' : 'Expire')) return
1030
+ const same = (a: string | null, b: string | null) =>
1031
+ (a?.toLowerCase() ?? null) === (b?.toLowerCase() ?? null)
1032
+ if (!request.schedule.some((e) => same(e.culture, culture))) return
1033
+ const facts = await page(key)
1034
+ if (!result.ok) {
1035
+ await clearSchedule(request)
1036
+ return unpublishable(request, facts, result.reason)
1037
+ }
1038
+ await repo.record(request.id, {
1039
+ kind: request.action === 'publish' ? 'published' : 'unpublished',
1040
+ comment: `as scheduled${culture ? ` (${culture})` : ''}`,
1041
+ })
1042
+ const left = (await documents().schedules(key)).some(
1043
+ (row) =>
1044
+ row.action === action && request.schedule?.some((e) => same(e.culture, row.culture)),
1045
+ )
1046
+ if (!left) await approved(request, undefined)
1047
+ },
1048
+
1049
+ async sweepScheduled(now = Date.now()) {
1050
+ for (const request of await requests().scheduled()) {
1051
+ const node = await nodes.byKey(request.nodeKey)
1052
+ if (!node || node.trashed) {
1053
+ if (node) await clearSchedule(request)
1054
+ await requests().setState(request.id, 'withdrawn')
1055
+ await requests().record(request.id, {
1056
+ kind: 'withdrawn',
1057
+ comment: node ? 'the page was moved to the recycle bin' : 'the page was deleted',
1058
+ })
1059
+ continue
1060
+ }
1061
+ const action = request.action === 'publish' ? 'Release' : 'Expire'
1062
+ const rows = await documents().schedules(request.nodeKey)
1063
+ const left = rows.some(
1064
+ (row) =>
1065
+ row.action === action &&
1066
+ request.schedule?.some(
1067
+ (e) => (e.culture?.toLowerCase() ?? null) === (row.culture?.toLowerCase() ?? null),
1068
+ ),
1069
+ )
1070
+ if (left) continue
1071
+ // A row the job has claimed and is publishing is gone too: give it time to report.
1072
+ const due = (request.schedule ?? []).flatMap((e) => dueAt(request, e) ?? [])
1073
+ if (due.some((d) => d.getTime() <= now && d.getTime() > now - SWEEP_GRACE_MS)) continue
1074
+ await requests().setState(request.id, 'withdrawn')
1075
+ await requests().record(request.id, {
1076
+ kind: 'withdrawn',
1077
+ comment: 'the schedule was removed',
1078
+ })
1079
+ }
1080
+ },
1081
+
804
1082
  async forPage(principal, key) {
805
1083
  const facts = await page(key)
806
1084
  if (!facts) throw new ApprovalRefused('The page could not be found.', 404)
1085
+ assertMayReach(principal, facts, [DocumentPermissions.Read])
807
1086
  const workflow = await covering(facts)
808
1087
  const all = await requests().forNode(key)
809
- const waiting = all.find((r) => r.state === 'waiting')
1088
+ const waiting = all.find((r) => r.state === 'waiting' || r.state === 'scheduled')
810
1089
  return {
811
1090
  workflow,
812
1091
  request: waiting ? await view(principal, waiting) : undefined,
@@ -826,7 +1105,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
826
1105
 
827
1106
  async waitingFor(principal) {
828
1107
  const out: RequestView[] = []
829
- for (const request of await requests().waiting()) {
1108
+ for (const request of await requests().open()) {
830
1109
  const v = await view(principal, request)
831
1110
  if (v.can.approve.length > 0 || v.can.sendBack.length > 0) out.push(v)
832
1111
  }
@@ -834,7 +1113,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
834
1113
  },
835
1114
 
836
1115
  async inFlight(principal) {
837
- return Promise.all((await requests().waiting()).map((r) => view(principal, r)))
1116
+ return Promise.all((await requests().open()).map((r) => view(principal, r)))
838
1117
  },
839
1118
 
840
1119
  async finished(principal, skip, take) {
package/src/config.ts CHANGED
@@ -740,4 +740,4 @@ export function describeDatabase(
740
740
  }
741
741
  }
742
742
 
743
- export const VERSION = '0.19.0'
743
+ export const VERSION = '0.21.0'
@@ -26,6 +26,7 @@ import {
26
26
  externalLoginProvider,
27
27
  } from '@crombolo/data'
28
28
  import type { IdentityProvider } from './identity-providers.ts'
29
+ import { originOf } from './seo.ts'
29
30
 
30
31
  /** A member or user, as far as signing in is concerned. */
31
32
  export interface ExternalAccount {
@@ -155,10 +156,13 @@ export function createExternalSignIn(
155
156
  return key
156
157
  }
157
158
  const flowCookie = `crombolo-external-${audience.audience}`
158
- const originOf = (request: Request) =>
159
- (options.applicationUrl || new URL(request.url).origin).replace(/\/$/, '')
159
+ // The address the visitor used, as a proxy in front says it, so a site
160
+ // reached by several names signs in on the one it was opened on. The
161
+ // provider still refuses a callback it was not registered with.
162
+ const callbackOrigin = (request: Request) =>
163
+ originOf(request, { applicationUrl: options.applicationUrl })
160
164
  const callbackUrl = (request: Request, id: string) =>
161
- `${originOf(request)}${audience.basePath}/${id}/callback`
165
+ `${callbackOrigin(request)}${audience.basePath}/${id}/callback`
162
166
  const redirect = (location: string, cookies: string[] = []) => {
163
167
  const headers = new Headers({ location })
164
168
  for (const cookie of cookies) headers.append('set-cookie', cookie)
package/src/jobs.ts CHANGED
@@ -18,6 +18,7 @@ import {
18
18
  } from '@crombolo/data'
19
19
  import type { PublishedCache } from '@crombolo/render'
20
20
  import { auditRetainedSince, recordAudit } from './adapters/audit.ts'
21
+ import type { Approvals } from './approvals.ts'
21
22
  import type {
22
23
  ContentNotificationRunner,
23
24
  ContentNotificationRunReport,
@@ -61,6 +62,8 @@ export interface JobsOptions {
61
62
  contentNotificationsMs?: number
62
63
  /** Queues the notifications scheduled publishing makes, as an editor's publish does. */
63
64
  notifier?: ContentNotifier
65
+ /** Told what scheduled publishing did, for the approval requests waiting on it (story 029). */
66
+ approvals?: Pick<Approvals, 'scheduleFired' | 'sweepScheduled'>
64
67
  }
65
68
 
66
69
  export interface ScheduledRun {
@@ -123,11 +126,17 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
123
126
  detail: `Scheduled${due.culture ? ` (${due.culture})` : ''}`,
124
127
  })
125
128
  options.onDocumentChanged?.(due.key)
129
+ await options.approvals?.scheduleFired(due.key, due.culture, due.action, { ok: true })
126
130
  } catch (error) {
127
131
  if (!(error instanceof PublishBlockedError)) throw error
128
132
  run.failed.push({ key: due.key, reason: error.message })
133
+ await options.approvals?.scheduleFired(due.key, due.culture, due.action, {
134
+ ok: false,
135
+ reason: error.message,
136
+ })
129
137
  }
130
138
  }
139
+ await options.approvals?.sweepScheduled(now.getTime())
131
140
  if (run.published.length + run.unpublished.length > 0) options.cache.invalidate()
132
141
  for (const key of run.published) {
133
142
  await options.webhooks?.raise({ alias: 'Umbraco.ContentPublish', key })
package/src/server.ts CHANGED
@@ -893,6 +893,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
893
893
  const jobs = createBackgroundJobs({
894
894
  db,
895
895
  cache,
896
+ approvals: managementDeps.approvals as Approvals | undefined,
896
897
  nodeState: schema.nodeState,
897
898
  nodeId: schema.nodeId,
898
899
  versionCleanup: config.versionCleanup,