@crombolo/server 0.18.0 → 0.20.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 +12 -12
- package/src/adapters/documents.ts +6 -2
- package/src/approvals-api.ts +24 -2
- package/src/approvals.ts +302 -42
- package/src/config.ts +1 -1
- package/src/jobs.ts +9 -0
- package/src/member-auth.ts +7 -26
- package/src/ports.ts +5 -1
- package/src/seo.ts +5 -5
- package/src/server.ts +34 -6
- package/src/two-factor.ts +17 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crombolo/server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.20.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.
|
|
34
|
-
"@crombolo/api-management": "0.
|
|
35
|
-
"@crombolo/assistant": "0.
|
|
36
|
-
"@crombolo/auth": "0.
|
|
37
|
-
"@crombolo/backoffice-host": "0.
|
|
38
|
-
"@crombolo/contracts": "0.
|
|
39
|
-
"@crombolo/core": "0.
|
|
40
|
-
"@crombolo/data": "0.
|
|
41
|
-
"@crombolo/render": "0.
|
|
42
|
-
"@crombolo/schema": "0.
|
|
43
|
-
"@crombolo/transfer": "0.
|
|
33
|
+
"@crombolo/api-delivery": "0.20.0",
|
|
34
|
+
"@crombolo/api-management": "0.20.0",
|
|
35
|
+
"@crombolo/assistant": "0.20.0",
|
|
36
|
+
"@crombolo/auth": "0.20.0",
|
|
37
|
+
"@crombolo/backoffice-host": "0.20.0",
|
|
38
|
+
"@crombolo/contracts": "0.20.0",
|
|
39
|
+
"@crombolo/core": "0.20.0",
|
|
40
|
+
"@crombolo/data": "0.20.0",
|
|
41
|
+
"@crombolo/render": "0.20.0",
|
|
42
|
+
"@crombolo/schema": "0.20.0",
|
|
43
|
+
"@crombolo/transfer": "0.20.0",
|
|
44
44
|
"@logtape/logtape": "^2.3.8"
|
|
45
45
|
}
|
|
46
46
|
}
|
|
@@ -464,8 +464,12 @@ export function createDocumentPort(
|
|
|
464
464
|
return toTreeItems(repo, await repo.nodes.byKeys(keys))
|
|
465
465
|
},
|
|
466
466
|
|
|
467
|
-
async collection(
|
|
468
|
-
|
|
467
|
+
async collection(
|
|
468
|
+
parentKey: string | null,
|
|
469
|
+
paging: SkipTake,
|
|
470
|
+
excludeKeys: readonly string[] = [],
|
|
471
|
+
): Promise<Page<DocumentAggregate>> {
|
|
472
|
+
const page = await repo.children(parentKey, paging.skip, paging.take, excludeKeys)
|
|
469
473
|
const items: DocumentAggregate[] = []
|
|
470
474
|
for (const row of page.items) {
|
|
471
475
|
const aggregate = await repo.load(row)
|
package/src/approvals-api.ts
CHANGED
|
@@ -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 {
|
|
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'
|
|
@@ -27,6 +28,7 @@ import {
|
|
|
27
28
|
ApprovalRepository,
|
|
28
29
|
type ApprovalRepository as ApprovalRepositoryType,
|
|
29
30
|
type ApprovalRequest,
|
|
31
|
+
type ApprovalScheduleEntry,
|
|
30
32
|
type ApprovalStep,
|
|
31
33
|
AuditLog,
|
|
32
34
|
type Db,
|
|
@@ -100,6 +102,12 @@ export interface RequestView {
|
|
|
100
102
|
action: ApprovalAction
|
|
101
103
|
cultures: string[] | null
|
|
102
104
|
state: ApprovalRequest['state']
|
|
105
|
+
/** The times it asked for, in ISO form; null to publish on approval. */
|
|
106
|
+
schedule: Array<{
|
|
107
|
+
culture: string | null
|
|
108
|
+
publishTime: string | null
|
|
109
|
+
unpublishTime: string | null
|
|
110
|
+
}> | null
|
|
103
111
|
requestedBy: string
|
|
104
112
|
requestedAt: string
|
|
105
113
|
workflow: SchemaWorkflow
|
|
@@ -141,12 +149,24 @@ export interface Approvals {
|
|
|
141
149
|
beforeSave(principal: Principal, key: string): Promise<string | undefined>
|
|
142
150
|
/** What the save does to a waiting request, once it has gone through. */
|
|
143
151
|
afterSave(principal: Principal, key: string): Promise<void>
|
|
152
|
+
/** A direct publish, schedule or unpublish by someone allowed to: a scheduled request ends. */
|
|
153
|
+
afterDirectPublish(principal: Principal, key: string, what: string): Promise<void>
|
|
154
|
+
/** The schedule job fired one of a page's schedules: a scheduled request goes on or ends. */
|
|
155
|
+
scheduleFired(
|
|
156
|
+
key: string,
|
|
157
|
+
culture: string | null,
|
|
158
|
+
action: 'Release' | 'Expire',
|
|
159
|
+
result: { ok: true } | { ok: false; reason: string },
|
|
160
|
+
): Promise<void>
|
|
161
|
+
/** Ends scheduled requests whose schedule is gone: the recycle bin, an import, the CLI. */
|
|
162
|
+
sweepScheduled(now?: number): Promise<void>
|
|
144
163
|
send(
|
|
145
164
|
principal: Principal,
|
|
146
165
|
key: string,
|
|
147
166
|
action: ApprovalAction,
|
|
148
167
|
cultures: string[] | null,
|
|
149
168
|
comment?: string,
|
|
169
|
+
schedule?: ApprovalScheduleEntry[] | null,
|
|
150
170
|
): Promise<RequestView>
|
|
151
171
|
approve(
|
|
152
172
|
principal: Principal,
|
|
@@ -172,12 +192,69 @@ export interface Approvals {
|
|
|
172
192
|
): Promise<{ total: number; items: RequestView[] }>
|
|
173
193
|
}
|
|
174
194
|
|
|
195
|
+
const SWEEP_GRACE_MS = 5 * 60_000
|
|
196
|
+
|
|
197
|
+
/** A time as a person reads it in a history or an e-mail, in UTC. Pure. */
|
|
198
|
+
export const describeTime = (time: Date): string =>
|
|
199
|
+
`${time.toISOString().slice(0, 16).replace('T', ' ')} UTC`
|
|
200
|
+
|
|
201
|
+
/** "published at …" for each time a request asks for, culture by culture. Pure. */
|
|
202
|
+
export function describeSchedule(
|
|
203
|
+
action: ApprovalAction,
|
|
204
|
+
entries: readonly ApprovalScheduleEntry[],
|
|
205
|
+
): string {
|
|
206
|
+
return entries
|
|
207
|
+
.flatMap((e) => {
|
|
208
|
+
const culture = e.culture ? ` (${e.culture})` : ''
|
|
209
|
+
return [
|
|
210
|
+
...(action === 'publish' && e.publishTime
|
|
211
|
+
? [`published at ${describeTime(e.publishTime)}${culture}`]
|
|
212
|
+
: []),
|
|
213
|
+
...(e.unpublishTime ? [`taken down at ${describeTime(e.unpublishTime)}${culture}`] : []),
|
|
214
|
+
]
|
|
215
|
+
})
|
|
216
|
+
.join(', ')
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Why a request may not carry these times, or undefined when it may. Pure. */
|
|
220
|
+
export function scheduleRefusal(
|
|
221
|
+
workflow: SchemaWorkflow,
|
|
222
|
+
action: ApprovalAction,
|
|
223
|
+
cultures: readonly string[] | null,
|
|
224
|
+
entries: readonly ApprovalScheduleEntry[],
|
|
225
|
+
now = Date.now(),
|
|
226
|
+
): string | undefined {
|
|
227
|
+
if (entries.length === 0) return undefined
|
|
228
|
+
if (!workflow.scheduling)
|
|
229
|
+
return `"${workflow.name}" does not let a request say when to publish. Send it without a time.`
|
|
230
|
+
const named = new Set((cultures ?? []).map((c) => c.toLowerCase()))
|
|
231
|
+
const seen = new Set<string>()
|
|
232
|
+
for (const e of entries) {
|
|
233
|
+
if (action === 'unpublish' && e.publishTime)
|
|
234
|
+
return 'A request to take the page down can only say when to take it down.'
|
|
235
|
+
for (const time of [e.publishTime, e.unpublishTime])
|
|
236
|
+
if (time && (Number.isNaN(time.getTime()) || time.getTime() <= now))
|
|
237
|
+
return 'Pick a time in the future.'
|
|
238
|
+
if (e.publishTime && e.unpublishTime && e.unpublishTime <= e.publishTime)
|
|
239
|
+
return 'The page has to be taken down after it is published.'
|
|
240
|
+
const culture = e.culture?.toLowerCase() ?? null
|
|
241
|
+
if (culture === null ? cultures !== null : !named.has(culture))
|
|
242
|
+
return culture === null
|
|
243
|
+
? 'This request names its languages: give each one its own time.'
|
|
244
|
+
: `"${e.culture}" is not one of the languages this request sends.`
|
|
245
|
+
if (seen.has(culture ?? '')) return 'Give each language one time.'
|
|
246
|
+
seen.add(culture ?? '')
|
|
247
|
+
}
|
|
248
|
+
return undefined
|
|
249
|
+
}
|
|
250
|
+
|
|
175
251
|
export function createApprovals(options: ApprovalsOptions): Approvals {
|
|
176
252
|
const { db } = options
|
|
177
253
|
const requests = (tx: Db = db): ApprovalRepositoryType => new ApprovalRepository(tx)
|
|
178
254
|
const nodes = new NodeRepository(db)
|
|
179
255
|
const groups = new UserGroupRepository(db)
|
|
180
256
|
const audit = new AuditLog(db)
|
|
257
|
+
const documents = () => new DocumentRepository(db, { nodeState: options.nodeState })
|
|
181
258
|
|
|
182
259
|
const page = async (key: string): Promise<PageFacts | undefined> => {
|
|
183
260
|
const node = await nodes.byKey(key)
|
|
@@ -388,11 +465,66 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
|
|
|
388
465
|
return false
|
|
389
466
|
}
|
|
390
467
|
|
|
468
|
+
/** The time a request's entry asks it to act at: publish for a publish request, take down otherwise. */
|
|
469
|
+
const dueAt = (request: ApprovalRequest, entry: ApprovalScheduleEntry) =>
|
|
470
|
+
request.action === 'publish' ? entry.publishTime : entry.unpublishTime
|
|
471
|
+
|
|
472
|
+
/** Removes the schedule rows a request wrote, culture by culture. */
|
|
473
|
+
const clearSchedule = async (request: ApprovalRequest) => {
|
|
474
|
+
if (!request.schedule) return
|
|
475
|
+
await documents().setSchedule(
|
|
476
|
+
request.nodeKey,
|
|
477
|
+
request.schedule.map((e) => ({ culture: e.culture, publishTime: null, unpublishTime: null })),
|
|
478
|
+
)
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/** An approved page that could not be published goes back to its editor with the reason. */
|
|
482
|
+
const unpublishable = async (
|
|
483
|
+
request: ApprovalRequest,
|
|
484
|
+
facts: PageFacts | undefined,
|
|
485
|
+
reason: string,
|
|
486
|
+
) => {
|
|
487
|
+
const repo = requests()
|
|
488
|
+
await repo.setState(request.id, 'sent-back')
|
|
489
|
+
await repo.record(request.id, {
|
|
490
|
+
kind: 'sent-back',
|
|
491
|
+
comment: `approved, but it could not be ${request.action === 'publish' ? 'published' : 'taken down'}: ${reason}`,
|
|
492
|
+
})
|
|
493
|
+
await notify(
|
|
494
|
+
'editor',
|
|
495
|
+
request,
|
|
496
|
+
[],
|
|
497
|
+
`Could not publish: ${facts?.name ?? 'a page'}`,
|
|
498
|
+
`"${facts?.name}" was approved but could not be published: ${reason}`,
|
|
499
|
+
)
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/** The request is done: recorded as approved, and its editor told. */
|
|
503
|
+
const approved = async (request: ApprovalRequest, principal: Principal | undefined) => {
|
|
504
|
+
const facts = await page(request.nodeKey)
|
|
505
|
+
await requests().setState(request.id, 'approved')
|
|
506
|
+
await auditStep(
|
|
507
|
+
principal,
|
|
508
|
+
facts,
|
|
509
|
+
request.action === 'publish' ? 'Published on approval' : 'Unpublished on approval',
|
|
510
|
+
`through "${request.workflow.name}"`,
|
|
511
|
+
)
|
|
512
|
+
await notify(
|
|
513
|
+
'editor',
|
|
514
|
+
request,
|
|
515
|
+
[],
|
|
516
|
+
`Approved: ${facts?.name ?? 'a page'}`,
|
|
517
|
+
`"${facts?.name}" was approved through "${request.workflow.name}" and is now ${request.action === 'publish' ? 'published' : 'taken down'}.`,
|
|
518
|
+
)
|
|
519
|
+
}
|
|
520
|
+
|
|
391
521
|
/**
|
|
392
522
|
* Publishes (or takes down) a fully approved page, outside any transaction:
|
|
393
523
|
* publishing takes the content tree's lock, which must never be waited on
|
|
394
|
-
* from inside one.
|
|
395
|
-
*
|
|
524
|
+
* from inside one. What the request asked to happen later is scheduled
|
|
525
|
+
* instead, and the request stays open until it has. A page that cannot be
|
|
526
|
+
* published goes back to its editor with the reason, rather than sitting
|
|
527
|
+
* approved and unpublished.
|
|
396
528
|
*/
|
|
397
529
|
const finish = async (
|
|
398
530
|
request: ApprovalRequest,
|
|
@@ -400,48 +532,73 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
|
|
|
400
532
|
): Promise<void> => {
|
|
401
533
|
const repo = requests()
|
|
402
534
|
const facts = await page(request.nodeKey)
|
|
403
|
-
const
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
535
|
+
const now = Date.now()
|
|
536
|
+
const later: ApprovalScheduleEntry[] = []
|
|
537
|
+
const expires: ApprovalScheduleEntry[] = []
|
|
538
|
+
let cultures: string[] | null | undefined = request.cultures
|
|
539
|
+
let passed = false
|
|
540
|
+
if (request.schedule) {
|
|
541
|
+
const nowCultures: Array<string | null> = []
|
|
542
|
+
for (const entry of request.schedule) {
|
|
543
|
+
const due = dueAt(request, entry)
|
|
544
|
+
if (due && due.getTime() > now) {
|
|
545
|
+
later.push(request.action === 'publish' ? entry : { ...entry, publishTime: null })
|
|
546
|
+
continue
|
|
547
|
+
}
|
|
548
|
+
if (due) passed = true
|
|
549
|
+
nowCultures.push(entry.culture)
|
|
550
|
+
if (request.action === 'publish' && entry.unpublishTime)
|
|
551
|
+
expires.push({ ...entry, publishTime: null })
|
|
552
|
+
}
|
|
553
|
+
// Cultures the request names without a time publish on approval.
|
|
554
|
+
const timed = new Set(request.schedule.map((e) => e.culture?.toLowerCase()))
|
|
555
|
+
const untimed = (request.cultures ?? []).filter((c) => !timed.has(c.toLowerCase()))
|
|
556
|
+
cultures = nowCultures.includes(null)
|
|
557
|
+
? request.cultures
|
|
558
|
+
: nowCultures.length + untimed.length > 0
|
|
559
|
+
? [...(nowCultures as string[]), ...untimed]
|
|
560
|
+
: undefined
|
|
561
|
+
}
|
|
562
|
+
if (cultures !== undefined) {
|
|
563
|
+
const result =
|
|
564
|
+
request.action === 'publish'
|
|
565
|
+
? await options.publisher.publish(request.nodeKey, cultures)
|
|
566
|
+
: await options.publisher.unpublish(request.nodeKey, cultures)
|
|
567
|
+
if (!result.ok) return unpublishable(request, facts, result.reason)
|
|
409
568
|
await repo.record(request.id, {
|
|
410
|
-
kind: '
|
|
411
|
-
|
|
569
|
+
kind: request.action === 'publish' ? 'published' : 'unpublished',
|
|
570
|
+
userKey: principal?.id ?? null,
|
|
571
|
+
comment: passed ? 'the requested time had passed when it was approved' : null,
|
|
412
572
|
})
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
)
|
|
420
|
-
return
|
|
573
|
+
if (request.action === 'publish')
|
|
574
|
+
await options.notifier?.raise(
|
|
575
|
+
{ actions: ['Umb.Document.Publish'], key: request.nodeKey, keyKind: 'document' },
|
|
576
|
+
principal ? { key: principal.id, name: principal.name } : null,
|
|
577
|
+
`approved through "${request.workflow.name}"`,
|
|
578
|
+
)
|
|
421
579
|
}
|
|
422
|
-
|
|
580
|
+
if (later.length + expires.length > 0)
|
|
581
|
+
await documents().setSchedule(request.nodeKey, [...later, ...expires])
|
|
582
|
+
if (later.length === 0) return approved(request, principal)
|
|
583
|
+
const when = describeSchedule(request.action, later)
|
|
584
|
+
await repo.setState(request.id, 'scheduled')
|
|
423
585
|
await repo.record(request.id, {
|
|
424
|
-
kind:
|
|
586
|
+
kind: 'scheduled',
|
|
425
587
|
userKey: principal?.id ?? null,
|
|
588
|
+
comment: when,
|
|
426
589
|
})
|
|
427
590
|
await auditStep(
|
|
428
591
|
principal,
|
|
429
592
|
facts,
|
|
430
|
-
|
|
431
|
-
|
|
593
|
+
'Scheduled on approval',
|
|
594
|
+
`${when}, through "${request.workflow.name}"`,
|
|
432
595
|
)
|
|
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
596
|
await notify(
|
|
440
597
|
'editor',
|
|
441
598
|
request,
|
|
442
599
|
[],
|
|
443
600
|
`Approved: ${facts?.name ?? 'a page'}`,
|
|
444
|
-
`"${facts?.name}" was approved through "${request.workflow.name}" and
|
|
601
|
+
`"${facts?.name}" was approved through "${request.workflow.name}" and will be ${when}.`,
|
|
445
602
|
)
|
|
446
603
|
}
|
|
447
604
|
|
|
@@ -501,6 +658,12 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
|
|
|
501
658
|
action: request.action,
|
|
502
659
|
cultures: request.cultures,
|
|
503
660
|
state: request.state,
|
|
661
|
+
schedule:
|
|
662
|
+
request.schedule?.map((e) => ({
|
|
663
|
+
culture: e.culture,
|
|
664
|
+
publishTime: e.publishTime?.toISOString() ?? null,
|
|
665
|
+
unpublishTime: e.unpublishTime?.toISOString() ?? null,
|
|
666
|
+
})) ?? null,
|
|
504
667
|
requestedBy: request.requestedBy,
|
|
505
668
|
requestedAt: request.requestedAt.toISOString(),
|
|
506
669
|
workflow: request.workflow,
|
|
@@ -518,7 +681,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
|
|
|
518
681
|
? []
|
|
519
682
|
: actionable.filter((s) => !already(s.alias)).map((s) => s.alias),
|
|
520
683
|
sendBack: actionable.map((s) => s.alias),
|
|
521
|
-
withdraw: waiting && (ownChange || principal.isAdmin),
|
|
684
|
+
withdraw: (waiting || request.state === 'scheduled') && (ownChange || principal.isAdmin),
|
|
522
685
|
},
|
|
523
686
|
}
|
|
524
687
|
}
|
|
@@ -593,9 +756,14 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
|
|
|
593
756
|
},
|
|
594
757
|
|
|
595
758
|
async beforeSave(principal, key) {
|
|
596
|
-
const request = await requests().
|
|
759
|
+
const request = await requests().openFor(key)
|
|
597
760
|
if (!request || principal.isAdmin) return undefined
|
|
598
761
|
const edit = request.workflow.onEdit
|
|
762
|
+
if (request.state === 'scheduled') {
|
|
763
|
+
if (edit === 'lock' || edit === 'lock-after-first-approval')
|
|
764
|
+
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.`
|
|
765
|
+
return undefined
|
|
766
|
+
}
|
|
599
767
|
if (edit === 'lock')
|
|
600
768
|
return 'This page is waiting for approval and cannot be changed until it is decided.'
|
|
601
769
|
if (edit === 'lock-after-first-approval') {
|
|
@@ -608,7 +776,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
|
|
|
608
776
|
|
|
609
777
|
async afterSave(principal, key) {
|
|
610
778
|
const repo = requests()
|
|
611
|
-
const request = await repo.
|
|
779
|
+
const request = await repo.openFor(key)
|
|
612
780
|
if (!request) return
|
|
613
781
|
const head =
|
|
614
782
|
(await new DocumentRepository(db, { nodeState: options.nodeState }).eventMarkers(key))
|
|
@@ -622,13 +790,14 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
|
|
|
622
790
|
userKey: principal.id,
|
|
623
791
|
comment: 'the page was changed after it was sent',
|
|
624
792
|
})
|
|
793
|
+
if (request.state === 'scheduled') await clearSchedule(request)
|
|
625
794
|
return
|
|
626
795
|
}
|
|
627
796
|
await repo.setEvent(request.id, head)
|
|
628
797
|
await repo.record(request.id, { kind: 'edited', userKey: principal.id })
|
|
629
798
|
},
|
|
630
799
|
|
|
631
|
-
async send(principal, key, action, cultures, comment) {
|
|
800
|
+
async send(principal, key, action, cultures, comment, schedule) {
|
|
632
801
|
const facts = await page(key)
|
|
633
802
|
if (!facts) throw new ApprovalRefused('The page could not be found.', 404)
|
|
634
803
|
const workflow = await covering(facts)
|
|
@@ -638,13 +807,22 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
|
|
|
638
807
|
? 'No workflow covers this page: it can be published directly.'
|
|
639
808
|
: 'Taking this page down needs no approval.',
|
|
640
809
|
)
|
|
810
|
+
const timed = (schedule ?? []).filter((e) => e.publishTime || e.unpublishTime)
|
|
811
|
+
const refusal = scheduleRefusal(workflow, action, cultures, timed)
|
|
812
|
+
if (refusal) throw new ApprovalRefused(refusal)
|
|
641
813
|
const stored = (await readWorkflows(db)).find(
|
|
642
814
|
(s) => (s.workflow.key ?? s.workflow.alias) === (workflow.key ?? workflow.alias),
|
|
643
815
|
)
|
|
644
816
|
const outcome = await db.transaction(async (tx) => {
|
|
645
817
|
const repo = requests(tx)
|
|
646
|
-
|
|
647
|
-
|
|
818
|
+
const open = await repo.openFor(key)
|
|
819
|
+
if (open)
|
|
820
|
+
throw new ApprovalRefused(
|
|
821
|
+
open.state === 'scheduled'
|
|
822
|
+
? `This page is already approved and will be ${describeSchedule(open.action, open.schedule ?? [])}. Withdraw that request to send it with another time.`
|
|
823
|
+
: 'This page is already waiting for approval.',
|
|
824
|
+
409,
|
|
825
|
+
)
|
|
648
826
|
const head =
|
|
649
827
|
(await new DocumentRepository(tx, { nodeState: options.nodeState }).eventMarkers(key))
|
|
650
828
|
?.head ?? null
|
|
@@ -656,11 +834,13 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
|
|
|
656
834
|
workflow,
|
|
657
835
|
workflowVersion: stored?.version ?? '',
|
|
658
836
|
requestedBy: principal.id,
|
|
837
|
+
schedule: timed.length > 0 ? timed : null,
|
|
659
838
|
})
|
|
839
|
+
const when = timed.length > 0 ? describeSchedule(action, timed) : ''
|
|
660
840
|
await repo.record(request.id, {
|
|
661
841
|
kind: 'sent',
|
|
662
842
|
userKey: principal.id,
|
|
663
|
-
comment: comment?.trim() || null,
|
|
843
|
+
comment: [comment?.trim(), when && `to be ${when}`].filter(Boolean).join('\n\n') || null,
|
|
664
844
|
})
|
|
665
845
|
const first = startStages(workflow)
|
|
666
846
|
await reach(repo, request, first)
|
|
@@ -669,7 +849,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
|
|
|
669
849
|
request,
|
|
670
850
|
first,
|
|
671
851
|
`Waiting for your approval: ${facts.name}`,
|
|
672
|
-
`${principal.name} sent "${facts.name}" for approval through "${workflow.name}".${comment ? `\n\n${comment}` : ''}`,
|
|
852
|
+
`${principal.name} sent "${facts.name}" for approval through "${workflow.name}".${when ? ` It is to be ${when}.` : ''}${comment ? `\n\n${comment}` : ''}`,
|
|
673
853
|
)
|
|
674
854
|
const complete = await settle(repo, request)
|
|
675
855
|
await auditStep(
|
|
@@ -784,7 +964,10 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
|
|
|
784
964
|
},
|
|
785
965
|
|
|
786
966
|
async withdraw(principal, requestKey) {
|
|
787
|
-
const request = await
|
|
967
|
+
const request = await requests().byKey(requestKey)
|
|
968
|
+
if (!request) throw new ApprovalRefused('There is no such request.', 404)
|
|
969
|
+
if (request.state !== 'waiting' && request.state !== 'scheduled')
|
|
970
|
+
throw new ApprovalRefused('This request has already been decided.', 409)
|
|
788
971
|
if (normaliseUuid(principal.id) !== request.requestedBy && !principal.isAdmin)
|
|
789
972
|
throw new ApprovalRefused(
|
|
790
973
|
'Only the person who sent it, or an administrator, can withdraw it.',
|
|
@@ -792,6 +975,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
|
|
|
792
975
|
)
|
|
793
976
|
await requests().setState(request.id, 'withdrawn')
|
|
794
977
|
await requests().record(request.id, { kind: 'withdrawn', userKey: principal.id })
|
|
978
|
+
if (request.state === 'scheduled') await clearSchedule(request)
|
|
795
979
|
await auditStep(
|
|
796
980
|
principal,
|
|
797
981
|
await page(request.nodeKey),
|
|
@@ -801,12 +985,88 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
|
|
|
801
985
|
return view(principal, (await requests().byKey(request.key)) as ApprovalRequest)
|
|
802
986
|
},
|
|
803
987
|
|
|
988
|
+
async afterDirectPublish(principal, key, what) {
|
|
989
|
+
const repo = requests()
|
|
990
|
+
const request = await repo.openFor(key)
|
|
991
|
+
if (request?.state !== 'scheduled') return
|
|
992
|
+
await repo.setState(request.id, 'superseded')
|
|
993
|
+
await repo.record(request.id, {
|
|
994
|
+
kind: 'superseded',
|
|
995
|
+
userKey: principal.id,
|
|
996
|
+
comment: `${principal.name} ${what} directly`,
|
|
997
|
+
})
|
|
998
|
+
await auditStep(
|
|
999
|
+
principal,
|
|
1000
|
+
await page(key),
|
|
1001
|
+
'Superseded approval request',
|
|
1002
|
+
`scheduled under "${request.workflow.name}"`,
|
|
1003
|
+
)
|
|
1004
|
+
},
|
|
1005
|
+
|
|
1006
|
+
async scheduleFired(key, culture, action, result) {
|
|
1007
|
+
const repo = requests()
|
|
1008
|
+
const request = await repo.openFor(key)
|
|
1009
|
+
if (request?.state !== 'scheduled' || !request.schedule) return
|
|
1010
|
+
// An expiry on a page a request published is an ordinary schedule by then.
|
|
1011
|
+
if (action !== (request.action === 'publish' ? 'Release' : 'Expire')) return
|
|
1012
|
+
const same = (a: string | null, b: string | null) =>
|
|
1013
|
+
(a?.toLowerCase() ?? null) === (b?.toLowerCase() ?? null)
|
|
1014
|
+
if (!request.schedule.some((e) => same(e.culture, culture))) return
|
|
1015
|
+
const facts = await page(key)
|
|
1016
|
+
if (!result.ok) {
|
|
1017
|
+
await clearSchedule(request)
|
|
1018
|
+
return unpublishable(request, facts, result.reason)
|
|
1019
|
+
}
|
|
1020
|
+
await repo.record(request.id, {
|
|
1021
|
+
kind: request.action === 'publish' ? 'published' : 'unpublished',
|
|
1022
|
+
comment: `as scheduled${culture ? ` (${culture})` : ''}`,
|
|
1023
|
+
})
|
|
1024
|
+
const left = (await documents().schedules(key)).some(
|
|
1025
|
+
(row) =>
|
|
1026
|
+
row.action === action && request.schedule?.some((e) => same(e.culture, row.culture)),
|
|
1027
|
+
)
|
|
1028
|
+
if (!left) await approved(request, undefined)
|
|
1029
|
+
},
|
|
1030
|
+
|
|
1031
|
+
async sweepScheduled(now = Date.now()) {
|
|
1032
|
+
for (const request of await requests().scheduled()) {
|
|
1033
|
+
const node = await nodes.byKey(request.nodeKey)
|
|
1034
|
+
if (!node || node.trashed) {
|
|
1035
|
+
if (node) await clearSchedule(request)
|
|
1036
|
+
await requests().setState(request.id, 'withdrawn')
|
|
1037
|
+
await requests().record(request.id, {
|
|
1038
|
+
kind: 'withdrawn',
|
|
1039
|
+
comment: node ? 'the page was moved to the recycle bin' : 'the page was deleted',
|
|
1040
|
+
})
|
|
1041
|
+
continue
|
|
1042
|
+
}
|
|
1043
|
+
const action = request.action === 'publish' ? 'Release' : 'Expire'
|
|
1044
|
+
const rows = await documents().schedules(request.nodeKey)
|
|
1045
|
+
const left = rows.some(
|
|
1046
|
+
(row) =>
|
|
1047
|
+
row.action === action &&
|
|
1048
|
+
request.schedule?.some(
|
|
1049
|
+
(e) => (e.culture?.toLowerCase() ?? null) === (row.culture?.toLowerCase() ?? null),
|
|
1050
|
+
),
|
|
1051
|
+
)
|
|
1052
|
+
if (left) continue
|
|
1053
|
+
// A row the job has claimed and is publishing is gone too: give it time to report.
|
|
1054
|
+
const due = (request.schedule ?? []).flatMap((e) => dueAt(request, e) ?? [])
|
|
1055
|
+
if (due.some((d) => d.getTime() <= now && d.getTime() > now - SWEEP_GRACE_MS)) continue
|
|
1056
|
+
await requests().setState(request.id, 'withdrawn')
|
|
1057
|
+
await requests().record(request.id, {
|
|
1058
|
+
kind: 'withdrawn',
|
|
1059
|
+
comment: 'the schedule was removed',
|
|
1060
|
+
})
|
|
1061
|
+
}
|
|
1062
|
+
},
|
|
1063
|
+
|
|
804
1064
|
async forPage(principal, key) {
|
|
805
1065
|
const facts = await page(key)
|
|
806
1066
|
if (!facts) throw new ApprovalRefused('The page could not be found.', 404)
|
|
807
1067
|
const workflow = await covering(facts)
|
|
808
1068
|
const all = await requests().forNode(key)
|
|
809
|
-
const waiting = all.find((r) => r.state === 'waiting')
|
|
1069
|
+
const waiting = all.find((r) => r.state === 'waiting' || r.state === 'scheduled')
|
|
810
1070
|
return {
|
|
811
1071
|
workflow,
|
|
812
1072
|
request: waiting ? await view(principal, waiting) : undefined,
|
|
@@ -826,7 +1086,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
|
|
|
826
1086
|
|
|
827
1087
|
async waitingFor(principal) {
|
|
828
1088
|
const out: RequestView[] = []
|
|
829
|
-
for (const request of await requests().
|
|
1089
|
+
for (const request of await requests().open()) {
|
|
830
1090
|
const v = await view(principal, request)
|
|
831
1091
|
if (v.can.approve.length > 0 || v.can.sendBack.length > 0) out.push(v)
|
|
832
1092
|
}
|
|
@@ -834,7 +1094,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
|
|
|
834
1094
|
},
|
|
835
1095
|
|
|
836
1096
|
async inFlight(principal) {
|
|
837
|
-
return Promise.all((await requests().
|
|
1097
|
+
return Promise.all((await requests().open()).map((r) => view(principal, r)))
|
|
838
1098
|
},
|
|
839
1099
|
|
|
840
1100
|
async finished(principal, skip, take) {
|
package/src/config.ts
CHANGED
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/member-auth.ts
CHANGED
|
@@ -26,6 +26,7 @@ import {
|
|
|
26
26
|
expireCookie,
|
|
27
27
|
hashPassword,
|
|
28
28
|
isNativeHash,
|
|
29
|
+
isSameOrigin,
|
|
29
30
|
memberCookieName,
|
|
30
31
|
passwordConfigJson,
|
|
31
32
|
readCookie,
|
|
@@ -125,30 +126,6 @@ async function readInput(request: Request): Promise<Record<string, string>> {
|
|
|
125
126
|
*/
|
|
126
127
|
const safeReturnUrl = (value: string | undefined): string | undefined => localReturnUrl(value)
|
|
127
128
|
|
|
128
|
-
/**
|
|
129
|
-
* Whether a POST came from this site, rather than a form on someone else's.
|
|
130
|
-
*
|
|
131
|
-
* These three endpoints take a plain form post and act on the member cookie, and
|
|
132
|
-
* `SameSite=Lax` does not cover a cross-site POST's effect here: an attacker's
|
|
133
|
-
* form can sign a visitor into an account the attacker controls, or out of their
|
|
134
|
-
* own. Umbraco's surface controllers carry an antiforgery token for this; with no
|
|
135
|
-
* token to hand, the fetch metadata a browser sends is what distinguishes them.
|
|
136
|
-
*
|
|
137
|
-
* A request with neither header is allowed: that is a non-browser client, which
|
|
138
|
-
* carries no ambient cookies to abuse.
|
|
139
|
-
*/
|
|
140
|
-
function fromThisSite(request: Request): boolean {
|
|
141
|
-
const site = request.headers.get('sec-fetch-site')
|
|
142
|
-
if (site) return site === 'same-origin' || site === 'none'
|
|
143
|
-
const origin = request.headers.get('origin')
|
|
144
|
-
if (!origin) return true
|
|
145
|
-
try {
|
|
146
|
-
return origin === new URL(request.url).origin
|
|
147
|
-
} catch {
|
|
148
|
-
return false
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
|
|
152
129
|
export function createMemberAuth(
|
|
153
130
|
db: Db,
|
|
154
131
|
config: CromboloConfig,
|
|
@@ -468,7 +445,8 @@ export function createMemberAuth(
|
|
|
468
445
|
})
|
|
469
446
|
}
|
|
470
447
|
if (request.method !== 'POST') return new Response(null, { status: 405 })
|
|
471
|
-
if (!
|
|
448
|
+
if (!isSameOrigin(request, config.applicationUrl || undefined))
|
|
449
|
+
return new Response('Forbidden', { status: 403 })
|
|
472
450
|
const input = await readInput(request)
|
|
473
451
|
switch (step) {
|
|
474
452
|
case 'setup': {
|
|
@@ -603,7 +581,10 @@ export function createMemberAuth(
|
|
|
603
581
|
if (action === '2fa' || action.startsWith('2fa/'))
|
|
604
582
|
return manageTwoFactor(request, action.slice(4))
|
|
605
583
|
if (request.method !== 'POST') return new Response(null, { status: 405 })
|
|
606
|
-
|
|
584
|
+
// SameSite=Lax still lets a sibling subdomain post here, signing a visitor
|
|
585
|
+
// into an account the attacker holds, or out of their own.
|
|
586
|
+
if (!isSameOrigin(request, config.applicationUrl || undefined))
|
|
587
|
+
return new Response('Forbidden', { status: 403 })
|
|
607
588
|
switch (action) {
|
|
608
589
|
case 'login':
|
|
609
590
|
return login(request)
|
package/src/ports.ts
CHANGED
|
@@ -699,7 +699,11 @@ function userTwoFactorPort(service: TwoFactorService): UserTwoFactorPort {
|
|
|
699
699
|
const enabled = await service.enable(userKey, provider, secret, code)
|
|
700
700
|
return enabled.ok
|
|
701
701
|
? { ok: true, recoveryCodes: enabled.value.recoveryCodes }
|
|
702
|
-
: {
|
|
702
|
+
: {
|
|
703
|
+
ok: false,
|
|
704
|
+
message: enabled.message,
|
|
705
|
+
alreadyEnabled: enabled.reason === 'alreadyEnabled',
|
|
706
|
+
}
|
|
703
707
|
},
|
|
704
708
|
async disable(userKey, code) {
|
|
705
709
|
const disabled = await service.disable(userKey, provider, code)
|
package/src/seo.ts
CHANGED
|
@@ -155,8 +155,8 @@ export interface SeoHostOptions {
|
|
|
155
155
|
cache: PublishedCache
|
|
156
156
|
/** Whether a visitor who is not signed in would be turned away from a page. */
|
|
157
157
|
isProtected(content: PublishedContent): Promise<boolean>
|
|
158
|
-
/** A document's latest saved version, as the preview renders it. */
|
|
159
|
-
draft(key: string, culture: string | null): Promise<DraftModel | undefined>
|
|
158
|
+
/** A document's latest saved version, as the preview renders it, if `principal` may read it. */
|
|
159
|
+
draft(key: string, culture: string | null, principal: Principal): Promise<DraftModel | undefined>
|
|
160
160
|
}
|
|
161
161
|
|
|
162
162
|
export interface SeoHost {
|
|
@@ -311,11 +311,11 @@ export function createSeoHost(options: SeoHostOptions): SeoHost {
|
|
|
311
311
|
return false
|
|
312
312
|
}
|
|
313
313
|
|
|
314
|
-
const preview = async (request: Request): Promise<Response> => {
|
|
314
|
+
const preview = async (request: Request, principal: Principal): Promise<Response> => {
|
|
315
315
|
const url = new URL(request.url)
|
|
316
316
|
const key = url.searchParams.get('document') ?? ''
|
|
317
317
|
if (!UUID.test(key)) return Response.json({ message: 'Choose a page.' }, { status: 400 })
|
|
318
|
-
const draft = await options.draft(key, url.searchParams.get('culture') || null)
|
|
318
|
+
const draft = await options.draft(key, url.searchParams.get('culture') || null, principal)
|
|
319
319
|
if (!draft) return Response.json({ message: 'That page could not be found.' }, { status: 404 })
|
|
320
320
|
const origin = originOf(request, config)
|
|
321
321
|
const snapshot = await cache.snapshot()
|
|
@@ -338,7 +338,7 @@ export function createSeoHost(options: SeoHostOptions): SeoHost {
|
|
|
338
338
|
}
|
|
339
339
|
|
|
340
340
|
const handle: SeoHost['handle'] = async (request, subpath, principal) => {
|
|
341
|
-
if (subpath === '/preview' && request.method === 'GET') return preview(request)
|
|
341
|
+
if (subpath === '/preview' && request.method === 'GET') return preview(request, principal)
|
|
342
342
|
if (subpath !== '/settings') return undefined
|
|
343
343
|
if (!hasSection(principal, 'settings')) return new Response('Forbidden', { status: 403 })
|
|
344
344
|
if (request.method === 'GET') return Response.json(await settings())
|
package/src/server.ts
CHANGED
|
@@ -11,6 +11,7 @@ import { join } from 'node:path'
|
|
|
11
11
|
import { createDeliveryApi, resolveDeliveryApiSettings } from '@crombolo/api-delivery'
|
|
12
12
|
import {
|
|
13
13
|
type ClientAddress,
|
|
14
|
+
canReadDocument,
|
|
14
15
|
createManagementApiRouter,
|
|
15
16
|
hasSection,
|
|
16
17
|
type Principal,
|
|
@@ -21,6 +22,8 @@ import {
|
|
|
21
22
|
cookieNames,
|
|
22
23
|
createAuthRoutes,
|
|
23
24
|
expireCookie,
|
|
25
|
+
isSafeMethod,
|
|
26
|
+
isSameOrigin,
|
|
24
27
|
REDACTED,
|
|
25
28
|
readCookie,
|
|
26
29
|
serializeCookie,
|
|
@@ -371,6 +374,8 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
|
|
|
371
374
|
backOfficePath: paths.backOfficePath,
|
|
372
375
|
service: auth,
|
|
373
376
|
cookies,
|
|
377
|
+
applicationUrl: config.applicationUrl || undefined,
|
|
378
|
+
allowLocalLogin: config.allowLocalLogin,
|
|
374
379
|
twoFactor: {
|
|
375
380
|
providersFor: (userKey) => twoFactor.providers(userKey),
|
|
376
381
|
verify: (userKey, provider, code) =>
|
|
@@ -448,8 +453,22 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
|
|
|
448
453
|
async function authenticate(request: Request): Promise<Principal | undefined> {
|
|
449
454
|
const header = request.headers.get('authorization')
|
|
450
455
|
const bearer = header?.toLowerCase().startsWith('bearer ') ? header.slice(7).trim() : undefined
|
|
451
|
-
const
|
|
456
|
+
const fromCookie = !bearer || bearer === REDACTED
|
|
457
|
+
const token = fromCookie ? readCookie(request, names.accessToken) : bearer
|
|
452
458
|
if (!token) return undefined
|
|
459
|
+
// The browser sends the cookie wherever the request came from, so a write
|
|
460
|
+
// that relies on it must come from this site; a real bearer token need not.
|
|
461
|
+
if (
|
|
462
|
+
fromCookie &&
|
|
463
|
+
!isSafeMethod(request.method) &&
|
|
464
|
+
!isSameOrigin(request, config.applicationUrl || undefined)
|
|
465
|
+
) {
|
|
466
|
+
log.warning('Refused a signed-in {method} {path} from another site', {
|
|
467
|
+
method: request.method,
|
|
468
|
+
path: new URL(request.url).pathname,
|
|
469
|
+
})
|
|
470
|
+
return undefined
|
|
471
|
+
}
|
|
453
472
|
|
|
454
473
|
const identity = await auth.resolveAccessToken(token)
|
|
455
474
|
if (!identity) return undefined
|
|
@@ -695,8 +714,14 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
|
|
|
695
714
|
search: (term, options) => new SiteSearch(db).query(term, options),
|
|
696
715
|
})
|
|
697
716
|
|
|
698
|
-
|
|
699
|
-
|
|
717
|
+
const nodeLookup = createNodeLookup(db)
|
|
718
|
+
|
|
719
|
+
/**
|
|
720
|
+
* A document's latest saved version, as preview shows it, in the published
|
|
721
|
+
* tree's context — or undefined when `principal` may not read it.
|
|
722
|
+
*/
|
|
723
|
+
async function draftModel(key: string, requested: string | null, principal: Principal) {
|
|
724
|
+
if (!(await canReadDocument(principal, key, nodeLookup))) return undefined
|
|
700
725
|
const draft = await loadDraftNode(db, key, {
|
|
701
726
|
nodeState: schema.nodeState,
|
|
702
727
|
nodeId: schema.nodeId,
|
|
@@ -803,7 +828,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
|
|
|
803
828
|
const api = createManagementApiRouter({
|
|
804
829
|
deps: managementDeps,
|
|
805
830
|
authenticate,
|
|
806
|
-
nodes:
|
|
831
|
+
nodes: nodeLookup,
|
|
807
832
|
allowLocalLogin: config.allowLocalLogin,
|
|
808
833
|
audit: createAuditSink(db),
|
|
809
834
|
clientAddress,
|
|
@@ -868,6 +893,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
|
|
|
868
893
|
const jobs = createBackgroundJobs({
|
|
869
894
|
db,
|
|
870
895
|
cache,
|
|
896
|
+
approvals: managementDeps.approvals as Approvals | undefined,
|
|
871
897
|
nodeState: schema.nodeState,
|
|
872
898
|
nodeId: schema.nodeId,
|
|
873
899
|
versionCleanup: config.versionCleanup,
|
|
@@ -1929,13 +1955,15 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
|
|
|
1929
1955
|
* draft of the page it resolves to.
|
|
1930
1956
|
*/
|
|
1931
1957
|
async function renderPreview(request: Request, pathname: string, host: string) {
|
|
1932
|
-
if (!readCookie(request, PREVIEW_COOKIE)
|
|
1958
|
+
if (!readCookie(request, PREVIEW_COOKIE)) return undefined
|
|
1959
|
+
const principal = await authenticate(request)
|
|
1960
|
+
if (!principal) return undefined
|
|
1933
1961
|
const byKey = /^\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/?$/i.exec(
|
|
1934
1962
|
pathname,
|
|
1935
1963
|
)
|
|
1936
1964
|
const key = byKey?.[1] ?? (await cache.resolve(host, pathname))?.content.key
|
|
1937
1965
|
if (!key) return undefined
|
|
1938
|
-
const draft = await draftModel(key, new URL(request.url).searchParams.get('culture'))
|
|
1966
|
+
const draft = await draftModel(key, new URL(request.url).searchParams.get('culture'), principal)
|
|
1939
1967
|
if (!draft) return undefined
|
|
1940
1968
|
return renderer.renderModel(draft.content, draft.culture, {
|
|
1941
1969
|
...(await pageRequest(request)),
|
package/src/two-factor.ts
CHANGED
|
@@ -25,7 +25,11 @@ export const MEMBER_TWO_FACTOR_PROVIDER = 'UmbracoMemberAppAuthenticator'
|
|
|
25
25
|
|
|
26
26
|
export type TwoFactorResult<T = undefined> =
|
|
27
27
|
| ({ ok: true } & (T extends undefined ? object : { value: T }))
|
|
28
|
-
| {
|
|
28
|
+
| {
|
|
29
|
+
ok: false
|
|
30
|
+
reason: 'unavailable' | 'invalidCode' | 'notEnabled' | 'alreadyEnabled'
|
|
31
|
+
message: string
|
|
32
|
+
}
|
|
29
33
|
|
|
30
34
|
export class TwoFactorService {
|
|
31
35
|
#repository: TwoFactorRepository
|
|
@@ -69,7 +73,12 @@ export class TwoFactorService {
|
|
|
69
73
|
return { ok: true, value: { secret, qrCodeSetupImageUrl: qrCodeDataUrl(uri), otpauthUri: uri } }
|
|
70
74
|
}
|
|
71
75
|
|
|
72
|
-
/**
|
|
76
|
+
/**
|
|
77
|
+
* Turns the provider on when `code` is right for `secret`; answers with the
|
|
78
|
+
* recovery codes, shown once. Refused while it is already on: replacing the
|
|
79
|
+
* authenticator means turning it off first, which asks for the current one, so
|
|
80
|
+
* a stolen session cannot swap in its own.
|
|
81
|
+
*/
|
|
73
82
|
async enable(
|
|
74
83
|
ownerKey: string,
|
|
75
84
|
provider: string,
|
|
@@ -77,6 +86,12 @@ export class TwoFactorService {
|
|
|
77
86
|
code: string,
|
|
78
87
|
): Promise<TwoFactorResult<{ recoveryCodes: string[] }>> {
|
|
79
88
|
if (!this.#key) return this.#unavailable()
|
|
89
|
+
if (await this.#repository.get(ownerKey, provider))
|
|
90
|
+
return {
|
|
91
|
+
ok: false,
|
|
92
|
+
reason: 'alreadyEnabled',
|
|
93
|
+
message: 'Two-factor sign-in is already on. Turn it off first to use another app.',
|
|
94
|
+
}
|
|
80
95
|
const step = verifyTotp(secret, code)
|
|
81
96
|
if (step === undefined)
|
|
82
97
|
return {
|