@crombolo/server 0.64.0 → 0.66.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 +15 -14
- package/src/access.ts +6 -2
- package/src/adapters/blueprints.ts +19 -5
- package/src/adapters/elements.ts +49 -36
- package/src/adapters/members.ts +37 -3
- package/src/adapters/users.ts +18 -0
- package/src/approvals.ts +44 -15
- package/src/atomic-write.ts +2 -2
- package/src/background-jobs.ts +170 -0
- package/src/bundle-admin.ts +39 -3
- package/src/bundle-reload.ts +2 -1
- package/src/bundles.ts +60 -25
- package/src/cli-tokens-api.ts +152 -0
- package/src/config.ts +52 -3
- package/src/content-events.ts +22 -0
- package/src/content-operations.ts +26 -1
- package/src/core.ts +357 -133
- package/src/extension-activity.ts +121 -0
- package/src/extension-components.ts +20 -4
- package/src/extension-discovery.ts +84 -65
- package/src/grant-trust.ts +6 -4
- package/src/index.ts +14 -0
- package/src/media-access.ts +30 -125
- package/src/media-library.ts +953 -0
- package/src/member-admin.ts +761 -0
- package/src/node-operations.ts +19 -2
- package/src/ports.ts +2 -0
- package/src/principal.ts +35 -0
- package/src/remote-background-jobs.ts +99 -0
- package/src/remote-credentials.ts +114 -6
- package/src/remote-extension-activity.ts +66 -0
- package/src/remote-media-library.ts +297 -0
- package/src/remote-media.ts +2 -2
- package/src/remote-members.ts +271 -0
- package/src/remote-undo.ts +234 -0
- package/src/remote-users.ts +229 -0
- package/src/remote.ts +141 -3
- package/src/routes.ts +22 -3
- package/src/seed/values.ts +82 -4
- package/src/seo.ts +81 -61
- package/src/server.ts +153 -92
- package/src/settings.ts +95 -6
- package/src/trusted-signers-admin.ts +39 -3
- package/src/undo.ts +358 -0
- package/src/user-admin.ts +581 -0
- package/src/view-as.ts +95 -0
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The site's background jobs as Settings → Background jobs shows them (story
|
|
3
|
+
* 187), shared by its dashboard, the command line and the remote protocol (story
|
|
4
|
+
* 359): a page of jobs, one job named by its id or a prefix of it, and a failed
|
|
5
|
+
* one run again, audited as the dashboard audits it.
|
|
6
|
+
*/
|
|
7
|
+
import {
|
|
8
|
+
type AuditSource,
|
|
9
|
+
type Db,
|
|
10
|
+
type JobProgress,
|
|
11
|
+
JobRepository,
|
|
12
|
+
type JobRow,
|
|
13
|
+
type JobState,
|
|
14
|
+
} from '@crombolo/data'
|
|
15
|
+
import { recordAudit } from './adapters/audit.ts'
|
|
16
|
+
|
|
17
|
+
export const JOB_STATES: readonly JobState[] = ['queued', 'running', 'succeeded', 'failed']
|
|
18
|
+
|
|
19
|
+
/** Each state as the dashboard words it. */
|
|
20
|
+
export const JOB_STATE_WORDS: Record<JobState, string> = {
|
|
21
|
+
queued: 'Waiting',
|
|
22
|
+
running: 'Running',
|
|
23
|
+
failed: 'Failed',
|
|
24
|
+
succeeded: 'Done',
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The shortest prefix of an id that names a job. */
|
|
28
|
+
export const JOB_PREFIX_LENGTH = 8
|
|
29
|
+
|
|
30
|
+
export interface BackgroundJob {
|
|
31
|
+
id: string
|
|
32
|
+
/** `site`, or the bundle's id. */
|
|
33
|
+
owner: string
|
|
34
|
+
name: string
|
|
35
|
+
state: JobState
|
|
36
|
+
attempts: number
|
|
37
|
+
maxAttempts: number
|
|
38
|
+
nextAttemptAt: string
|
|
39
|
+
progress: JobProgress | null
|
|
40
|
+
error: string | null
|
|
41
|
+
queuedBy: string | null
|
|
42
|
+
createdAt: string
|
|
43
|
+
finishedAt: string | null
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface JobPage {
|
|
47
|
+
total: number
|
|
48
|
+
items: BackgroundJob[]
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface JobQuery {
|
|
52
|
+
owner?: string
|
|
53
|
+
state?: JobState
|
|
54
|
+
skip?: number
|
|
55
|
+
take?: number
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export type BackgroundJobErrorKind = 'not_found' | 'usage' | 'conflict'
|
|
59
|
+
|
|
60
|
+
/** Why a job could not be found or run again, in words for a person. */
|
|
61
|
+
export class BackgroundJobError extends Error {
|
|
62
|
+
constructor(
|
|
63
|
+
readonly kind: BackgroundJobErrorKind,
|
|
64
|
+
message: string,
|
|
65
|
+
readonly hint?: string,
|
|
66
|
+
) {
|
|
67
|
+
super(message)
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Who runs a job again, for its audit entry. */
|
|
72
|
+
export interface JobRetrier {
|
|
73
|
+
key?: string | null
|
|
74
|
+
name: string
|
|
75
|
+
source: AuditSource
|
|
76
|
+
address?: { ipAddress?: string | null; forwardedFor?: string | null }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export const jobView = (job: JobRow): BackgroundJob => ({
|
|
80
|
+
id: job.id,
|
|
81
|
+
owner: job.owner,
|
|
82
|
+
name: job.name,
|
|
83
|
+
state: job.state,
|
|
84
|
+
attempts: job.attempts,
|
|
85
|
+
maxAttempts: job.maxAttempts,
|
|
86
|
+
nextAttemptAt: job.nextAttemptAt.toISOString(),
|
|
87
|
+
progress: job.progress,
|
|
88
|
+
error: job.lastError,
|
|
89
|
+
queuedBy: job.queuedBy,
|
|
90
|
+
createdAt: job.createdAt.toISOString(),
|
|
91
|
+
finishedAt: job.finishedAt?.toISOString() ?? null,
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
/** A list's query as a request gives it, read as the dashboard reads it. */
|
|
95
|
+
export function readJobQuery(params: URLSearchParams): JobQuery {
|
|
96
|
+
const state = params.get('state')
|
|
97
|
+
return {
|
|
98
|
+
owner: params.get('owner') || undefined,
|
|
99
|
+
state: JOB_STATES.includes(state as JobState) ? (state as JobState) : undefined,
|
|
100
|
+
skip: Math.max(0, Number(params.get('skip')) || 0),
|
|
101
|
+
take: Math.min(200, Math.max(1, Number(params.get('take')) || 50)),
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** A page of jobs, the newest first. */
|
|
106
|
+
export async function listJobs(db: Db, query: JobQuery = {}): Promise<JobPage> {
|
|
107
|
+
const listed = await new JobRepository(db).list(query)
|
|
108
|
+
return { total: listed.total, items: listed.items.map(jobView) }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function find(db: Db, named: string): Promise<JobRow> {
|
|
112
|
+
const wanted = named.trim().toLowerCase()
|
|
113
|
+
if (wanted.length < JOB_PREFIX_LENGTH || !/^[0-9a-f-]+$/.test(wanted))
|
|
114
|
+
throw new BackgroundJobError(
|
|
115
|
+
'usage',
|
|
116
|
+
`A job is named by its id, or at least the first ${JOB_PREFIX_LENGTH} characters of it.`,
|
|
117
|
+
'crombolo jobs list gives each one.',
|
|
118
|
+
)
|
|
119
|
+
const found = await new JobRepository(db).byPrefix(wanted)
|
|
120
|
+
if (found.length === 0) throw new BackgroundJobError('not_found', `There is no job ${named}.`)
|
|
121
|
+
const exact = found.find((job) => job.id === wanted)
|
|
122
|
+
if (exact) return exact
|
|
123
|
+
if (found.length > 1)
|
|
124
|
+
throw new BackgroundJobError(
|
|
125
|
+
'conflict',
|
|
126
|
+
`${named} names more than one job: ${found.map((job) => `${job.id} (${job.name})`).join(', ')}.`,
|
|
127
|
+
'Give more of its id.',
|
|
128
|
+
)
|
|
129
|
+
return found[0] as JobRow
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** One job, by its id or a prefix of it that names only it. */
|
|
133
|
+
export async function jobOf(db: Db, named: string): Promise<BackgroundJob> {
|
|
134
|
+
return jobView(await find(db, named))
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Runs a failed job again from its first attempt, and audits it as the dashboard does. */
|
|
138
|
+
export async function retryJob(
|
|
139
|
+
db: Db,
|
|
140
|
+
named: string,
|
|
141
|
+
by: JobRetrier,
|
|
142
|
+
): Promise<{ job: BackgroundJob; message: string }> {
|
|
143
|
+
const job = await find(db, named)
|
|
144
|
+
const queue = new JobRepository(db)
|
|
145
|
+
if (job.state !== 'failed' || !(await queue.retry(job.id))) {
|
|
146
|
+
const now = (await queue.get(job.id))?.state ?? job.state
|
|
147
|
+
throw new BackgroundJobError(
|
|
148
|
+
'conflict',
|
|
149
|
+
'Only a job that has failed can be run again.',
|
|
150
|
+
`${job.name} is ${JOB_STATE_WORDS[now].toLowerCase()}.`,
|
|
151
|
+
)
|
|
152
|
+
}
|
|
153
|
+
await recordAudit(db, {
|
|
154
|
+
category: 'system',
|
|
155
|
+
action: 'Retry',
|
|
156
|
+
entityType: 'Job',
|
|
157
|
+
entityName: `${job.owner}/${job.name}`,
|
|
158
|
+
detail: job.lastError ? `after: ${job.lastError.slice(0, 200)}` : null,
|
|
159
|
+
source: by.source,
|
|
160
|
+
userKey: by.key ?? null,
|
|
161
|
+
userName: by.name,
|
|
162
|
+
ipAddress: by.address?.ipAddress ?? null,
|
|
163
|
+
forwardedFor: by.address?.forwardedFor ?? null,
|
|
164
|
+
})
|
|
165
|
+
const retried = await queue.get(job.id)
|
|
166
|
+
return {
|
|
167
|
+
job: jobView(retried ?? job),
|
|
168
|
+
message: `${job.name} is queued to run again.`,
|
|
169
|
+
}
|
|
170
|
+
}
|
package/src/bundle-admin.ts
CHANGED
|
@@ -17,6 +17,7 @@ import {
|
|
|
17
17
|
USER_DELEGATE,
|
|
18
18
|
} from '@crombolo/backoffice-host/registry'
|
|
19
19
|
import {
|
|
20
|
+
appendCacheInstruction,
|
|
20
21
|
type Db,
|
|
21
22
|
ExtensionSettingRepository,
|
|
22
23
|
ownerTablesIn,
|
|
@@ -115,6 +116,8 @@ export interface SwitchOutcome {
|
|
|
115
116
|
ok: boolean
|
|
116
117
|
on?: boolean
|
|
117
118
|
message: string
|
|
119
|
+
/** It is granted and on, and its server half could not start, saying why (story 346). */
|
|
120
|
+
couldNotStart?: string
|
|
118
121
|
}
|
|
119
122
|
|
|
120
123
|
export interface BundleAdmin {
|
|
@@ -172,8 +175,33 @@ export function createBundleAdmin(options: {
|
|
|
172
175
|
failed?: () => readonly { id: string; reason: string }[]
|
|
173
176
|
/** Stops an extension's running process, where this node runs one (story 328). */
|
|
174
177
|
stopExtension?: (id: string) => Promise<void>
|
|
178
|
+
/**
|
|
179
|
+
* Brings an extension's server half to what its grant says now, on every node
|
|
180
|
+
* (story 346): started when granted and on, stopped when off, unmounted when
|
|
181
|
+
* removed. Answers whether it runs here, or why it could not start; nothing
|
|
182
|
+
* where no server runs here, as on the CLI.
|
|
183
|
+
*/
|
|
184
|
+
changed?: (id: string) => Promise<{ running: boolean; reason?: string } | undefined>
|
|
175
185
|
}): BundleAdmin {
|
|
176
186
|
const { db, config, marketplace, extensions, bundleGrants } = options
|
|
187
|
+
|
|
188
|
+
/** Started, stopped or unmounted to match its grant; an answer that says when it could not start. */
|
|
189
|
+
const afterSwitch = async (
|
|
190
|
+
pkg: { id: string; name: string; carries: { server?: boolean } },
|
|
191
|
+
outcome: SwitchOutcome,
|
|
192
|
+
): Promise<SwitchOutcome> => {
|
|
193
|
+
if (!outcome.ok || !pkg.carries.server) return outcome
|
|
194
|
+
const now = await options.changed?.(pkg.id).catch((error: unknown) => ({
|
|
195
|
+
running: false,
|
|
196
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
197
|
+
}))
|
|
198
|
+
if (!outcome.on || now?.running !== false || !now.reason) return outcome
|
|
199
|
+
return {
|
|
200
|
+
...outcome,
|
|
201
|
+
couldNotStart: now.reason,
|
|
202
|
+
message: `${outcome.message} It could not start: ${now.reason}`,
|
|
203
|
+
}
|
|
204
|
+
}
|
|
177
205
|
const options_ = options
|
|
178
206
|
/**
|
|
179
207
|
* The data removed extensions left (story 328): an owner the tables ledger
|
|
@@ -459,6 +487,8 @@ export function createBundleAdmin(options: {
|
|
|
459
487
|
.join(' '),
|
|
460
488
|
}
|
|
461
489
|
if (!before?.carries.server) return result
|
|
490
|
+
// One running in a process of its own is unmounted now; one the site's code imported waits.
|
|
491
|
+
if (id && (await options_.changed?.(id).catch(() => undefined))) return result
|
|
462
492
|
markRestartPending(config.siteDir, `${name} removed`)
|
|
463
493
|
return { ...result, restartPending: true }
|
|
464
494
|
},
|
|
@@ -531,12 +561,12 @@ export function createBundleAdmin(options: {
|
|
|
531
561
|
`granted ${LEVEL_WORDS[level].label}: ${asks.join(', ') || 'nothing'}${delegateKey ? `, acting for ${delegateKey} when nobody is using it` : ''}`,
|
|
532
562
|
)
|
|
533
563
|
const state = bundleGrants.state(pkg)
|
|
534
|
-
return {
|
|
564
|
+
return afterSwitch(pkg, {
|
|
535
565
|
status: 200,
|
|
536
566
|
ok: true,
|
|
537
567
|
on: state.on,
|
|
538
568
|
message: `${pkg.name} is granted what it asks for.`,
|
|
539
|
-
}
|
|
569
|
+
})
|
|
540
570
|
},
|
|
541
571
|
|
|
542
572
|
async setEnabled(actor, id, enabled) {
|
|
@@ -573,7 +603,7 @@ export function createBundleAdmin(options: {
|
|
|
573
603
|
`${pkg.packageName}@${pkg.version}`,
|
|
574
604
|
enabled ? 'enabled; it runs again' : 'disabled; it is off',
|
|
575
605
|
)
|
|
576
|
-
|
|
606
|
+
const outcome = {
|
|
577
607
|
status: 200,
|
|
578
608
|
ok: true,
|
|
579
609
|
on: state.on,
|
|
@@ -581,6 +611,7 @@ export function createBundleAdmin(options: {
|
|
|
581
611
|
? `${pkg.name} is turned on.`
|
|
582
612
|
: `${pkg.name} is turned off until it is enabled again.`,
|
|
583
613
|
}
|
|
614
|
+
return afterSwitch(pkg, outcome)
|
|
584
615
|
},
|
|
585
616
|
}
|
|
586
617
|
}
|
|
@@ -643,5 +674,10 @@ export async function localBundleAdmin(
|
|
|
643
674
|
marketplace,
|
|
644
675
|
extensions,
|
|
645
676
|
bundleGrants,
|
|
677
|
+
// A site running on this database starts or stops it when it hears (story 346).
|
|
678
|
+
changed: async (id) => {
|
|
679
|
+
await appendCacheInstruction(db, { kind: 'extensions', payload: { id } }).catch(() => null)
|
|
680
|
+
return undefined
|
|
681
|
+
},
|
|
646
682
|
})
|
|
647
683
|
}
|
package/src/bundle-reload.ts
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
* A host installs a site's bundles itself and tells each node (story 181):
|
|
3
3
|
* `reloadBundles()` reads the site's `package.json` and `node_modules` again,
|
|
4
4
|
* so the back office serves what is there now. It never mounts a server half:
|
|
5
|
-
* configured `bundles` are wired at boot only, and
|
|
5
|
+
* configured `bundles` are wired at boot only, and an installed extension starts
|
|
6
|
+
* when it is granted (story 346).
|
|
6
7
|
*/
|
|
7
8
|
import type { BundlePackage, ExtensionRegistry } from '@crombolo/backoffice-host'
|
|
8
9
|
|
package/src/bundles.ts
CHANGED
|
@@ -822,10 +822,20 @@ export interface ServerBundles {
|
|
|
822
822
|
principal: Principal,
|
|
823
823
|
invoke: RouteInvoker,
|
|
824
824
|
): Promise<Response | undefined>
|
|
825
|
-
/**
|
|
826
|
-
|
|
825
|
+
/**
|
|
826
|
+
* The bundles' site routes, for the server's route table, each given its
|
|
827
|
+
* bundle's capabilities; one bundle's when named.
|
|
828
|
+
*/
|
|
829
|
+
siteRoutes(bundleId?: string): DeclaredRoute[]
|
|
827
830
|
/** What a bundle's job is given: its capabilities for no caller, as on a public route (story 187). */
|
|
828
831
|
jobContext(bundleId: string): Pick<BundleHost, BundleCapability> | undefined
|
|
832
|
+
/**
|
|
833
|
+
* Mounts one more bundle while the server runs (story 346), checked as boot
|
|
834
|
+
* checks them; answers why it cannot be, and mounts nothing then.
|
|
835
|
+
*/
|
|
836
|
+
add(bundle: ServerBundle, pkg: BundlePackage): string[]
|
|
837
|
+
/** Unmounts a bundle: its routes answer nothing from now on. */
|
|
838
|
+
remove(bundleId: string): void
|
|
829
839
|
}
|
|
830
840
|
|
|
831
841
|
const JOB_CALLER: BundleCaller = Object.freeze({ kind: 'job' })
|
|
@@ -862,11 +872,12 @@ export function createServerBundles(options: ServerBundlesOptions): ServerBundle
|
|
|
862
872
|
throw new Error(`The configured bundles cannot be mounted:\n- ${problems.join('\n- ')}`)
|
|
863
873
|
|
|
864
874
|
const basePath = `${options.pluginApiPath}/${BUNDLE_API_SEGMENT}/`
|
|
865
|
-
const
|
|
866
|
-
const
|
|
875
|
+
const live = [...options.bundles]
|
|
876
|
+
const byId = new Map(live.map((bundle) => [bundle.id, bundle]))
|
|
877
|
+
const logs = new Map(live.map((bundle) => [bundle.id, options.log(bundle.id)]))
|
|
867
878
|
|
|
868
879
|
const owners = new Map(options.packages.map((pkg) => [pkg.id, pkg]))
|
|
869
|
-
const
|
|
880
|
+
const mountedOf = (bundle: ServerBundle): MountedBundle => {
|
|
870
881
|
const owner = owners.get(bundle.id) as BundlePackage
|
|
871
882
|
return {
|
|
872
883
|
id: bundle.id,
|
|
@@ -881,7 +892,8 @@ export function createServerBundles(options: ServerBundlesOptions): ServerBundle
|
|
|
881
892
|
audience: onSite(route) ? ('site' as const) : ('backoffice' as const),
|
|
882
893
|
})),
|
|
883
894
|
}
|
|
884
|
-
}
|
|
895
|
+
}
|
|
896
|
+
const mounted: MountedBundle[] = live.map(mountedOf)
|
|
885
897
|
|
|
886
898
|
// Made once per bundle, at its first request, each on its own tables alone.
|
|
887
899
|
const databases = new Map<string, TablesDatabase>()
|
|
@@ -1031,25 +1043,48 @@ export function createServerBundles(options: ServerBundlesOptions): ServerBundle
|
|
|
1031
1043
|
const bundle = byId.get(bundleId)
|
|
1032
1044
|
return bundle ? contextFor(bundle, JOB_CALLER) : undefined
|
|
1033
1045
|
},
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
)
|
|
1046
|
+
add(bundle, pkg) {
|
|
1047
|
+
const problems = byId.has(bundle.id)
|
|
1048
|
+
? [`Bundle "${bundle.id}" is already mounted.`]
|
|
1049
|
+
: validateServerBundles([bundle], [pkg], options.coreVersion)
|
|
1050
|
+
if (problems.length > 0) return problems
|
|
1051
|
+
owners.set(pkg.id, pkg)
|
|
1052
|
+
live.push(bundle)
|
|
1053
|
+
byId.set(bundle.id, bundle)
|
|
1054
|
+
logs.set(bundle.id, options.log(bundle.id))
|
|
1055
|
+
mounted.push(mountedOf(bundle))
|
|
1056
|
+
return []
|
|
1057
|
+
},
|
|
1058
|
+
remove(bundleId) {
|
|
1059
|
+
const at = live.findIndex((bundle) => bundle.id === bundleId)
|
|
1060
|
+
if (at >= 0) live.splice(at, 1)
|
|
1061
|
+
const shown = mounted.findIndex((bundle) => bundle.id === bundleId)
|
|
1062
|
+
if (shown >= 0) mounted.splice(shown, 1)
|
|
1063
|
+
byId.delete(bundleId)
|
|
1064
|
+
logs.delete(bundleId)
|
|
1065
|
+
databases.delete(bundleId)
|
|
1066
|
+
},
|
|
1067
|
+
siteRoutes(bundleId) {
|
|
1068
|
+
return live
|
|
1069
|
+
.filter((bundle) => bundleId === undefined || bundle.id === bundleId)
|
|
1070
|
+
.flatMap((bundle) =>
|
|
1071
|
+
(bundle.routes ?? []).filter(onSite).map(
|
|
1072
|
+
(route): DeclaredRoute => ({
|
|
1073
|
+
route: whileOn(bundle.id, route as SiteRoute),
|
|
1074
|
+
owner: `the bundle ${bundle.id}`,
|
|
1075
|
+
extra: ({ member, via }) => {
|
|
1076
|
+
const caller: BundleCaller = member
|
|
1077
|
+
? Object.freeze({
|
|
1078
|
+
kind: 'member',
|
|
1079
|
+
member: freezeMember(member as RequestMember),
|
|
1080
|
+
via,
|
|
1081
|
+
})
|
|
1082
|
+
: PUBLIC_CALLER
|
|
1083
|
+
return { bundle: contextFor(bundle, caller), caller }
|
|
1084
|
+
},
|
|
1085
|
+
}),
|
|
1086
|
+
),
|
|
1087
|
+
)
|
|
1053
1088
|
},
|
|
1054
1089
|
async handle(request, url, principal, invoke) {
|
|
1055
1090
|
const pathname = url.pathname
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Command-line tokens over HTTP (story 351), at `<plugin>/api/cli-tokens`:
|
|
3
|
+
* GET lists your own, or `?user=<key>` someone's for an administrator; POST
|
|
4
|
+
* `{ name, days }` makes one and answers it once; DELETE `/{key}` revokes your
|
|
5
|
+
* own, or anyone's for an administrator. While tokens are off, GET answers
|
|
6
|
+
* `{ enabled: false }` and the rest are refused. docs/operations.md,
|
|
7
|
+
* "Command-line tokens".
|
|
8
|
+
*/
|
|
9
|
+
import type { Principal } from '@crombolo/api-management/domain'
|
|
10
|
+
import {
|
|
11
|
+
CLI_TOKEN_REFUSALS,
|
|
12
|
+
type CliToken,
|
|
13
|
+
type CliTokenPerson,
|
|
14
|
+
type CliTokenRefusal,
|
|
15
|
+
type CliTokens,
|
|
16
|
+
DEFAULT_CLI_TOKEN_DAYS,
|
|
17
|
+
} from '@crombolo/auth'
|
|
18
|
+
import type { Db } from '@crombolo/data'
|
|
19
|
+
import { recordAudit } from './adapters/audit.ts'
|
|
20
|
+
|
|
21
|
+
export interface CliTokenView {
|
|
22
|
+
key: string
|
|
23
|
+
name: string
|
|
24
|
+
createdAt: string
|
|
25
|
+
expiresAt: string
|
|
26
|
+
lastUsedAt: string | null
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const cliTokenView = (token: CliToken): CliTokenView => ({
|
|
30
|
+
key: token.key,
|
|
31
|
+
name: token.name,
|
|
32
|
+
createdAt: token.createdAt.toISOString(),
|
|
33
|
+
expiresAt: token.expiresAt.toISOString(),
|
|
34
|
+
lastUsedAt: token.lastUsedAt?.toISOString() ?? null,
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
type Person = CliTokenPerson
|
|
38
|
+
|
|
39
|
+
type Client = { ipAddress: string | null; forwardedFor: string | null }
|
|
40
|
+
|
|
41
|
+
const json = (body: unknown, status = 200) => Response.json(body, { status })
|
|
42
|
+
const refused = (message: string, status = 403) => json({ message }, status)
|
|
43
|
+
|
|
44
|
+
/** A token's refusal, with its reason, for a client that sent one the site would not take. */
|
|
45
|
+
export const tokenRefusal = (reason: CliTokenRefusal): Response =>
|
|
46
|
+
json({ reason, message: CLI_TOKEN_REFUSALS[reason] }, 401)
|
|
47
|
+
|
|
48
|
+
export function createCliTokensApi(db: Db, tokens: CliTokens) {
|
|
49
|
+
const person = (who: string) => tokens.person(who)
|
|
50
|
+
const ownerOf = (token: CliToken) => tokens.ownerOf(token)
|
|
51
|
+
|
|
52
|
+
const audit = (by: Principal, action: string, whose: Person, detail: string, client: Client) =>
|
|
53
|
+
recordAudit(db, {
|
|
54
|
+
category: 'user',
|
|
55
|
+
action,
|
|
56
|
+
source: 'request',
|
|
57
|
+
userKey: by.id,
|
|
58
|
+
userName: by.name,
|
|
59
|
+
entityType: 'User',
|
|
60
|
+
entityKey: whose.key,
|
|
61
|
+
entityName: whose.name,
|
|
62
|
+
detail,
|
|
63
|
+
...client,
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
return {
|
|
67
|
+
async handle(
|
|
68
|
+
request: Request,
|
|
69
|
+
principal: Principal,
|
|
70
|
+
rest: string,
|
|
71
|
+
client: Client,
|
|
72
|
+
): Promise<Response> {
|
|
73
|
+
const { enabled, maxDays } = tokens.settings
|
|
74
|
+
const me = await person(principal.id)
|
|
75
|
+
if (!me) return new Response('Unauthorized', { status: 401 })
|
|
76
|
+
if (request.method === 'GET' && rest === '') {
|
|
77
|
+
if (!enabled) return json({ enabled: false })
|
|
78
|
+
const asked = new URL(request.url).searchParams.get('user')
|
|
79
|
+
let whose = me
|
|
80
|
+
if (asked) {
|
|
81
|
+
const found = await person(asked)
|
|
82
|
+
if (found?.key !== me.key) {
|
|
83
|
+
if (!principal.isAdmin)
|
|
84
|
+
return refused("Only an administrator can see other people's tokens.")
|
|
85
|
+
if (!found) return refused('There is no such user.', 404)
|
|
86
|
+
whose = found
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return json({
|
|
90
|
+
enabled: true,
|
|
91
|
+
mayCreate: whose.key === me.key && (await tokens.mayCreate(me.id)),
|
|
92
|
+
maxDays,
|
|
93
|
+
defaultDays: Math.min(DEFAULT_CLI_TOKEN_DAYS, maxDays),
|
|
94
|
+
items: (await tokens.list(whose.id)).map(cliTokenView),
|
|
95
|
+
})
|
|
96
|
+
}
|
|
97
|
+
if (!enabled) return refused(CLI_TOKEN_REFUSALS.off)
|
|
98
|
+
if (request.method === 'POST' && rest === '') {
|
|
99
|
+
const body = (await request.json().catch(() => ({}))) as { name?: unknown; days?: unknown }
|
|
100
|
+
const issued = await tokens.issue(
|
|
101
|
+
me.id,
|
|
102
|
+
typeof body.name === 'string' ? body.name : '',
|
|
103
|
+
body.days === undefined || body.days === null ? undefined : Number(body.days),
|
|
104
|
+
)
|
|
105
|
+
if (!issued.ok) return refused(issued.message, issued.refused === 'not-allowed' ? 403 : 400)
|
|
106
|
+
await audit(
|
|
107
|
+
principal,
|
|
108
|
+
'CreateToken',
|
|
109
|
+
me,
|
|
110
|
+
`"${issued.issued.name}", until ${issued.issued.expiresAt.toISOString().slice(0, 10)}`,
|
|
111
|
+
client,
|
|
112
|
+
)
|
|
113
|
+
return json({ ...cliTokenView(issued.issued), token: issued.token }, 201)
|
|
114
|
+
}
|
|
115
|
+
const key = /^\/([0-9a-fA-F-]{36})$/.exec(rest)?.[1]
|
|
116
|
+
if (request.method === 'DELETE' && key) {
|
|
117
|
+
const token = await tokens.byKey(key)
|
|
118
|
+
if (!token || token.revokedAt) return refused('There is no such token.', 404)
|
|
119
|
+
if (token.userId !== me.id && !principal.isAdmin)
|
|
120
|
+
return refused('There is no such token.', 404)
|
|
121
|
+
const owner = token.userId === me.id ? me : await ownerOf(token)
|
|
122
|
+
await tokens.revoke(token.key, me.key)
|
|
123
|
+
await audit(
|
|
124
|
+
principal,
|
|
125
|
+
'RevokeToken',
|
|
126
|
+
owner,
|
|
127
|
+
owner === me ? `"${token.name}"` : `"${token.name}", ${owner.name}'s`,
|
|
128
|
+
client,
|
|
129
|
+
)
|
|
130
|
+
return new Response(null, { status: 204 })
|
|
131
|
+
}
|
|
132
|
+
return new Response('Method Not Allowed', { status: 405 })
|
|
133
|
+
},
|
|
134
|
+
|
|
135
|
+
/** The first use of a token, audited under its person, before the request names the token. */
|
|
136
|
+
async firstUse(token: CliToken, client: Client): Promise<void> {
|
|
137
|
+
const owner = await ownerOf(token)
|
|
138
|
+
await recordAudit(db, {
|
|
139
|
+
category: 'user',
|
|
140
|
+
action: 'FirstUseOfToken',
|
|
141
|
+
source: 'request',
|
|
142
|
+
userKey: owner.key,
|
|
143
|
+
userName: owner.name,
|
|
144
|
+
entityType: 'User',
|
|
145
|
+
entityKey: owner.key,
|
|
146
|
+
entityName: owner.name,
|
|
147
|
+
detail: `"${token.name}"`,
|
|
148
|
+
...client,
|
|
149
|
+
})
|
|
150
|
+
},
|
|
151
|
+
}
|
|
152
|
+
}
|
package/src/config.ts
CHANGED
|
@@ -106,6 +106,33 @@ function contentModeSetting(): ContentMode {
|
|
|
106
106
|
return value
|
|
107
107
|
}
|
|
108
108
|
|
|
109
|
+
/**
|
|
110
|
+
* Whether the Delivery API is public, from `CROMBOLO_DELIVERY_API_PRIVATE` (story 348):
|
|
111
|
+
* unset, it serves what the site publishes. The switch it replaced is refused, since
|
|
112
|
+
* ignoring `CROMBOLO_DELIVERY_API_PUBLIC=false` would quietly open a private API.
|
|
113
|
+
*/
|
|
114
|
+
function deliveryApiPublic(): boolean | undefined {
|
|
115
|
+
// Read directly: it is no longer a setting, only a name to refuse.
|
|
116
|
+
if (Bun.env.CROMBOLO_DELIVERY_API_PUBLIC !== undefined)
|
|
117
|
+
throw new Error(
|
|
118
|
+
'CROMBOLO_DELIVERY_API_PUBLIC has gone: set CROMBOLO_DELIVERY_API_PRIVATE=true to keep the Delivery API private, every request needing its key, or leave both unset for it to serve what the site publishes (story 348).',
|
|
119
|
+
)
|
|
120
|
+
const isPrivate = envFlag(setting('CROMBOLO_DELIVERY_API_PRIVATE'))
|
|
121
|
+
return isPrivate === undefined ? undefined : !isPrivate
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Whether a command needs someone signed in (story 350): `open` lets it run as the command line. */
|
|
125
|
+
export type CliAccess = 'open' | 'sign-in'
|
|
126
|
+
|
|
127
|
+
/** `CROMBOLO_CLI_ACCESS`, or undefined for the default, which follows `development`. */
|
|
128
|
+
function cliAccessSetting(): CliAccess | undefined {
|
|
129
|
+
const value = setting('CROMBOLO_CLI_ACCESS')?.trim().toLowerCase()
|
|
130
|
+
if (!value) return undefined
|
|
131
|
+
if (value !== 'open' && value !== 'sign-in')
|
|
132
|
+
throw new Error(`CROMBOLO_CLI_ACCESS is "${value}": it is open or sign-in.`)
|
|
133
|
+
return value
|
|
134
|
+
}
|
|
135
|
+
|
|
109
136
|
/** Whether the back office must leave templates, stylesheets and scripts alone. */
|
|
110
137
|
export const contentFilesLocked = (config: Pick<CromboloConfig, 'contentMode'>) =>
|
|
111
138
|
config.contentMode === 'production'
|
|
@@ -366,6 +393,19 @@ export interface CromboloConfig {
|
|
|
366
393
|
* `development` unless set, in production too. `CROMBOLO_CONTENT_MODE`.
|
|
367
394
|
*/
|
|
368
395
|
contentMode: ContentMode
|
|
396
|
+
/**
|
|
397
|
+
* Whether a command that reads or changes the site needs a signed-in person
|
|
398
|
+
* (story 350): `sign-in` unless `development`, where it is `open`.
|
|
399
|
+
* `CROMBOLO_CLI_ACCESS`. docs/operations.md, "Signing in from the command line".
|
|
400
|
+
*/
|
|
401
|
+
cliAccess: CliAccess
|
|
402
|
+
/**
|
|
403
|
+
* Whether people may make command-line tokens, and any is taken (story 351).
|
|
404
|
+
* `CROMBOLO_CLI_TOKENS`, off unless set.
|
|
405
|
+
*/
|
|
406
|
+
cliTokens: boolean
|
|
407
|
+
/** The most days a command-line token may last. `CROMBOLO_CLI_TOKEN_MAX_DAYS`, 90. */
|
|
408
|
+
cliTokenMaxDays: number
|
|
369
409
|
/** Sync `schema/` at boot; a pipeline that runs `crombolo types sync` turns this off. */
|
|
370
410
|
syncSchemaAtBoot: boolean
|
|
371
411
|
/** Which database engine; from CROMBOLO_DB. */
|
|
@@ -517,7 +557,7 @@ export interface CromboloConfig {
|
|
|
517
557
|
/**
|
|
518
558
|
* Umbraco's Delivery API (`docs/delivery-api.md`): off unless enabled.
|
|
519
559
|
* `CROMBOLO_DELIVERY_API`, `CROMBOLO_DELIVERY_API_KEY`,
|
|
520
|
-
* `
|
|
560
|
+
* `CROMBOLO_DELIVERY_API_PRIVATE`, `CROMBOLO_DELIVERY_API_MEDIA`,
|
|
521
561
|
* `CROMBOLO_DELIVERY_API_CORS_ORIGINS`, `CROMBOLO_DELIVERY_API_PREVIEW_URL` and
|
|
522
562
|
* `CROMBOLO_DELIVERY_API_PREVIEW_TOKEN_MINUTES`; member
|
|
523
563
|
* sign-in is configured here, since its clients and secrets are a list.
|
|
@@ -924,6 +964,10 @@ export function loadConfig(
|
|
|
924
964
|
: setting('NODE_ENV') !== 'production',
|
|
925
965
|
syncSchemaAtBoot: setting('CROMBOLO_SYNC_SCHEMA_AT_BOOT') !== 'false',
|
|
926
966
|
contentMode: contentModeSetting(),
|
|
967
|
+
// Resolved again below, once it is known whether this is development.
|
|
968
|
+
cliAccess: cliAccessSetting() as CliAccess,
|
|
969
|
+
cliTokens: setting('CROMBOLO_CLI_TOKENS') === 'true',
|
|
970
|
+
cliTokenMaxDays: Math.floor(positiveNumber(setting('CROMBOLO_CLI_TOKEN_MAX_DAYS'), 90)),
|
|
927
971
|
dialect: setting('CROMBOLO_DB') === 'postgres' ? 'postgres' : 'sqlite',
|
|
928
972
|
pgDump: setting('CROMBOLO_PG_DUMP'),
|
|
929
973
|
upgradePolicy:
|
|
@@ -1028,7 +1072,7 @@ export function loadConfig(
|
|
|
1028
1072
|
deliveryApi: stripUndefined({
|
|
1029
1073
|
enabled: envFlag(setting('CROMBOLO_DELIVERY_API')),
|
|
1030
1074
|
apiKey: setting('CROMBOLO_DELIVERY_API_KEY') || undefined,
|
|
1031
|
-
publicAccess:
|
|
1075
|
+
publicAccess: deliveryApiPublic(),
|
|
1032
1076
|
media:
|
|
1033
1077
|
envFlag(setting('CROMBOLO_DELIVERY_API_MEDIA')) === undefined
|
|
1034
1078
|
? undefined
|
|
@@ -1081,6 +1125,11 @@ export function loadConfig(
|
|
|
1081
1125
|
throw new Error(
|
|
1082
1126
|
`contentMode is "${String(merged.contentMode)}" in crombolo.config.ts: it is development or production.`,
|
|
1083
1127
|
)
|
|
1128
|
+
merged.cliAccess ??= merged.development ? 'open' : 'sign-in'
|
|
1129
|
+
if (merged.cliAccess !== 'open' && merged.cliAccess !== 'sign-in')
|
|
1130
|
+
throw new Error(
|
|
1131
|
+
`cliAccess is "${String(merged.cliAccess)}" in crombolo.config.ts: it is open or sign-in.`,
|
|
1132
|
+
)
|
|
1084
1133
|
checkIdentityProviders(merged.memberIdentityProviders, 'member')
|
|
1085
1134
|
checkIdentityProviders(merged.backofficeIdentityProviders, 'backoffice')
|
|
1086
1135
|
// Field by field, so a site setting its title suffix keeps the environment's switches.
|
|
@@ -1224,7 +1273,7 @@ export function describeDatabase(
|
|
|
1224
1273
|
}
|
|
1225
1274
|
}
|
|
1226
1275
|
|
|
1227
|
-
export const VERSION = '0.
|
|
1276
|
+
export const VERSION = '0.66.0'
|
|
1228
1277
|
|
|
1229
1278
|
/** A whole number of seconds from the environment; undefined when unset or not one. */
|
|
1230
1279
|
/** A positive number from a setting, else the default. */
|
package/src/content-events.ts
CHANGED
|
@@ -12,7 +12,9 @@ import {
|
|
|
12
12
|
actorUserKey,
|
|
13
13
|
auditEntryFor,
|
|
14
14
|
type DocumentEvent,
|
|
15
|
+
type ElementEventSink,
|
|
15
16
|
type EventSink,
|
|
17
|
+
elementAuditEntryFor,
|
|
16
18
|
liveEventsFor,
|
|
17
19
|
type MediaActor,
|
|
18
20
|
type MediaEventSink,
|
|
@@ -153,3 +155,23 @@ export function createMediaEventSink(options: {
|
|
|
153
155
|
},
|
|
154
156
|
}
|
|
155
157
|
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Where Library operations record what they did (story 361): the audit entry, in
|
|
161
|
+
* the change's own transaction, as the back office has always written it.
|
|
162
|
+
*/
|
|
163
|
+
export function createElementEventSink(): ElementEventSink {
|
|
164
|
+
return {
|
|
165
|
+
async record(tx: Db, event, actor) {
|
|
166
|
+
const entry = elementAuditEntryFor(event, actor)
|
|
167
|
+
const audit = new AuditLog(tx)
|
|
168
|
+
const subject = await audit.describe(entry.entityType, entry.entityKey)
|
|
169
|
+
await audit.record({
|
|
170
|
+
...entry,
|
|
171
|
+
entityType: subject.entityType,
|
|
172
|
+
entityKey: subject.entityKey,
|
|
173
|
+
entityName: subject.entityName,
|
|
174
|
+
})
|
|
175
|
+
},
|
|
176
|
+
}
|
|
177
|
+
}
|