@crombolo/server 0.64.0 → 0.65.1
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 +14 -14
- package/src/access.ts +6 -2
- package/src/approvals.ts +29 -15
- package/src/bundle-admin.ts +39 -3
- package/src/bundle-reload.ts +2 -1
- package/src/bundles.ts +60 -25
- package/src/config.ts +18 -3
- package/src/core.ts +357 -133
- package/src/extension-components.ts +20 -4
- package/src/extension-discovery.ts +84 -65
- package/src/grant-trust.ts +6 -4
- package/src/routes.ts +22 -3
- package/src/server.ts +63 -5
- package/src/settings.ts +9 -6
- package/src/trusted-signers-admin.ts +39 -3
- package/src/view-as.ts +95 -0
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Installed extensions run once granted, with nothing imported by the site
|
|
3
|
-
* (story 310), each in a Deno process of its own (story 311). At boot,
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
3
|
+
* (story 310), each in a Deno process of its own (story 311). At boot, and as
|
|
4
|
+
* it is granted while the site runs (story 346), each dependency with a server
|
|
5
|
+
* half that the config's `extensions` entry grants, or that a recorded grant
|
|
6
|
+
* covers, is built, started with its settings, and mounted from what it
|
|
7
|
+
* describes. One that cannot start is left off, and the site runs without it.
|
|
8
|
+
* docs/bundles.md, "Extensions run once granted".
|
|
8
9
|
*/
|
|
9
10
|
import { join } from 'node:path'
|
|
10
11
|
import type { BundlePackage } from '@crombolo/backoffice-host'
|
|
@@ -125,6 +126,75 @@ export interface FailedExtension {
|
|
|
125
126
|
reason: string
|
|
126
127
|
}
|
|
127
128
|
|
|
129
|
+
/** How starting one extension went: running, refused or broken, or not granted. */
|
|
130
|
+
export type ExtensionStart =
|
|
131
|
+
| { status: 'started'; bundle: ServerBundle; process: ExtensionProcess }
|
|
132
|
+
| { status: 'failed'; reason: string }
|
|
133
|
+
| { status: 'not-granted' }
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Starts one installed server half, at boot or while the site runs (story 346):
|
|
137
|
+
* when the config's entry or its recorded grant covers it, built, started with
|
|
138
|
+
* its settings, checked that it can run apart, and given its stand-in.
|
|
139
|
+
*/
|
|
140
|
+
export async function startExtension(
|
|
141
|
+
config: CromboloConfig,
|
|
142
|
+
pkg: BundlePackage,
|
|
143
|
+
recorded: { grant?: BundleGrant; settings?: Record<string, unknown> },
|
|
144
|
+
log: BundleLog,
|
|
145
|
+
activity?: ActivityRecorder,
|
|
146
|
+
): Promise<ExtensionStart> {
|
|
147
|
+
// Story 326: an extension runs from a root of its own, never as a dependency of the site.
|
|
148
|
+
const refused =
|
|
149
|
+
pkg.linked && Bun.env.NODE_ENV === 'production'
|
|
150
|
+
? LINKED_IN_PRODUCTION
|
|
151
|
+
: pkg.dependency
|
|
152
|
+
? INSTALLED_AS_DEPENDENCY
|
|
153
|
+
: undefined
|
|
154
|
+
if (refused) {
|
|
155
|
+
log.error('{package} is not started: {reason}', { package: pkg.packageName, reason: refused })
|
|
156
|
+
return { status: 'failed', reason: refused }
|
|
157
|
+
}
|
|
158
|
+
const entry = config.extensions?.[pkg.id]
|
|
159
|
+
const { grant } = recorded
|
|
160
|
+
const byConfig = entryCovers(pkg, entry)
|
|
161
|
+
const granted =
|
|
162
|
+
byConfig || Boolean(grant?.recorded && !grant.disabledAt && grantGaps(pkg, grant).length === 0)
|
|
163
|
+
// Nothing of an extension that is not granted is built, let alone run.
|
|
164
|
+
if (!granted) return { status: 'not-granted' }
|
|
165
|
+
const process = new ExtensionProcess({
|
|
166
|
+
pkg,
|
|
167
|
+
siteDir: config.siteDir,
|
|
168
|
+
home: join(config.siteDir, '.crombolo', 'extensions', pkg.id),
|
|
169
|
+
settings: settingsOf(pkg, recorded.settings, entry, config.secretKey),
|
|
170
|
+
dialect: config.dialect,
|
|
171
|
+
origins: [
|
|
172
|
+
...((byConfig ? entry?.origins : grant?.origins) ?? []),
|
|
173
|
+
...(entry?.dev?.allowNet ?? []),
|
|
174
|
+
],
|
|
175
|
+
reads: entry?.dev?.allowRead,
|
|
176
|
+
timeoutMs: entry?.timeoutMs,
|
|
177
|
+
log,
|
|
178
|
+
activity,
|
|
179
|
+
})
|
|
180
|
+
try {
|
|
181
|
+
const description = await process.start()
|
|
182
|
+
const problems = isolationProblems(description)
|
|
183
|
+
if (description.id !== pkg.id)
|
|
184
|
+
problems.push(`it calls itself "${description.id}", where its package.json says "${pkg.id}"`)
|
|
185
|
+
if (problems.length > 0) throw new Error(`It cannot run: ${problems.join('; ')}.`)
|
|
186
|
+
return { status: 'started', bundle: isolatedBundle(process), process }
|
|
187
|
+
} catch (error) {
|
|
188
|
+
await process.stop()
|
|
189
|
+
const reason = error instanceof Error ? error.message : String(error)
|
|
190
|
+
log.error('{package} could not be started, and the site runs without it: {reason}', {
|
|
191
|
+
package: pkg.packageName,
|
|
192
|
+
reason,
|
|
193
|
+
})
|
|
194
|
+
return { status: 'failed', reason }
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
128
198
|
/**
|
|
129
199
|
* The installed server halves to start, each in its own process with its
|
|
130
200
|
* settings: those the config grants and those a recorded grant covers. Ones the
|
|
@@ -147,68 +217,17 @@ export async function startExtensions(
|
|
|
147
217
|
const failed: FailedExtension[] = []
|
|
148
218
|
for (const pkg of packages) {
|
|
149
219
|
if (!pkg.carries.server || wired.has(pkg.id)) continue
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
failed.push({ id: pkg.id, reason: LINKED_IN_PRODUCTION })
|
|
153
|
-
log(pkg.id).error('{package} is not started: {reason}', {
|
|
154
|
-
package: pkg.packageName,
|
|
155
|
-
reason: LINKED_IN_PRODUCTION,
|
|
156
|
-
})
|
|
157
|
-
continue
|
|
158
|
-
}
|
|
159
|
-
if (pkg.dependency) {
|
|
160
|
-
failed.push({ id: pkg.id, reason: INSTALLED_AS_DEPENDENCY })
|
|
161
|
-
log(pkg.id).error('{package} is not started: {reason}', {
|
|
162
|
-
package: pkg.packageName,
|
|
163
|
-
reason: INSTALLED_AS_DEPENDENCY,
|
|
164
|
-
})
|
|
165
|
-
continue
|
|
166
|
-
}
|
|
167
|
-
const entry = config.extensions?.[pkg.id]
|
|
168
|
-
const grant = recorded.grants.get(pkg.id)
|
|
169
|
-
const byConfig = entryCovers(pkg, entry)
|
|
170
|
-
const granted =
|
|
171
|
-
byConfig ||
|
|
172
|
-
Boolean(grant?.recorded && !grant.disabledAt && grantGaps(pkg, grant).length === 0)
|
|
173
|
-
// Nothing of an extension that is not granted is built, let alone run.
|
|
174
|
-
if (!granted) continue
|
|
175
|
-
const process = new ExtensionProcess({
|
|
220
|
+
const started = await startExtension(
|
|
221
|
+
config,
|
|
176
222
|
pkg,
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
settings: settingsOf(pkg, recorded.settings.get(pkg.id), entry, config.secretKey),
|
|
180
|
-
dialect: config.dialect,
|
|
181
|
-
origins: [
|
|
182
|
-
...((byConfig ? entry?.origins : grant?.origins) ?? []),
|
|
183
|
-
...(entry?.dev?.allowNet ?? []),
|
|
184
|
-
],
|
|
185
|
-
reads: entry?.dev?.allowRead,
|
|
186
|
-
timeoutMs: entry?.timeoutMs,
|
|
187
|
-
log: log(pkg.id),
|
|
223
|
+
{ grant: recorded.grants.get(pkg.id), settings: recorded.settings.get(pkg.id) },
|
|
224
|
+
log(pkg.id),
|
|
188
225
|
activity,
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
problems.push(
|
|
195
|
-
`it calls itself "${description.id}", where its package.json says "${pkg.id}"`,
|
|
196
|
-
)
|
|
197
|
-
if (problems.length > 0) throw new Error(`It cannot run: ${problems.join('; ')}.`)
|
|
198
|
-
bundles.push(isolatedBundle(process))
|
|
199
|
-
processes.push(process)
|
|
200
|
-
} catch (error) {
|
|
201
|
-
await process.stop()
|
|
202
|
-
const reason = error instanceof Error ? error.message : String(error)
|
|
203
|
-
failed.push({ id: pkg.id, reason })
|
|
204
|
-
log(pkg.id).error(
|
|
205
|
-
'{package} could not be started, and the site starts without it: {reason}',
|
|
206
|
-
{
|
|
207
|
-
package: pkg.packageName,
|
|
208
|
-
reason,
|
|
209
|
-
},
|
|
210
|
-
)
|
|
211
|
-
}
|
|
226
|
+
)
|
|
227
|
+
if (started.status === 'started') {
|
|
228
|
+
bundles.push(started.bundle)
|
|
229
|
+
processes.push(started.process)
|
|
230
|
+
} else if (started.status === 'failed') failed.push({ id: pkg.id, reason: started.reason })
|
|
212
231
|
}
|
|
213
232
|
return { bundles, processes, failed }
|
|
214
233
|
}
|
package/src/grant-trust.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Story 335: an extension granted Acts as you or Unrestricted keeps that only
|
|
3
3
|
* while someone this site trusts vouches for it. Checked at every start, before
|
|
4
|
-
* extensions run, so an upgrade
|
|
5
|
-
* off what
|
|
4
|
+
* extensions run, so an upgrade switches off what no longer qualifies; and as a
|
|
5
|
+
* signer is taken off Trusted signers, so what it vouched for stops at once.
|
|
6
6
|
*/
|
|
7
7
|
import { type ExtensionRegistry, isUpperLevel, levelOf } from '@crombolo/backoffice-host/registry'
|
|
8
8
|
import type { Db } from '@crombolo/data'
|
|
@@ -27,6 +27,8 @@ export async function switchOffUntrusted(
|
|
|
27
27
|
config: CromboloConfig,
|
|
28
28
|
extensions: ExtensionRegistry,
|
|
29
29
|
grants: Pick<BundleGrants, 'granted' | 'isOn' | 'state' | 'forget'>,
|
|
30
|
+
/** At start, or because a signer was just taken off the list. */
|
|
31
|
+
when: 'start' | 'untrusted' = 'start',
|
|
30
32
|
): Promise<string[]> {
|
|
31
33
|
const marketplace = createMarketplace({
|
|
32
34
|
registry: config.npmRegistry,
|
|
@@ -56,8 +58,8 @@ export async function switchOffUntrusted(
|
|
|
56
58
|
action: 'Disable',
|
|
57
59
|
entityType: 'Bundle',
|
|
58
60
|
entityName: `${pkg.packageName}@${pkg.version}`,
|
|
59
|
-
detail: `switched off at start: it acts as you or runs unrestricted, and is ${why}; it needs granting again`,
|
|
60
|
-
source: 'boot',
|
|
61
|
+
detail: `switched off ${when === 'start' ? 'at start' : 'as its signer was taken off Trusted signers'}: it acts as you or runs unrestricted, and is ${why}; it needs granting again`,
|
|
62
|
+
source: when === 'start' ? 'boot' : 'request',
|
|
61
63
|
userKey: null,
|
|
62
64
|
userName: SWITCHED_OFF_BY,
|
|
63
65
|
ipAddress: null,
|
package/src/routes.ts
CHANGED
|
@@ -130,10 +130,12 @@ export function createRoutes<Member extends RouteMember>(
|
|
|
130
130
|
declared: readonly DeclaredRoute[],
|
|
131
131
|
deps: RouteDeps<Member>,
|
|
132
132
|
) {
|
|
133
|
-
const
|
|
133
|
+
const compile = (entry: DeclaredRoute) => ({
|
|
134
134
|
...entry,
|
|
135
135
|
pattern: new URLPattern({ pathname: entry.route.path }),
|
|
136
|
-
})
|
|
136
|
+
})
|
|
137
|
+
const routes = [...declared]
|
|
138
|
+
const compiled = routes.map(compile)
|
|
137
139
|
const defaultLimiter =
|
|
138
140
|
deps.defaultPerMinute > 0
|
|
139
141
|
? new RateLimiter({ max: deps.defaultPerMinute, windowMs: MINUTE, now: deps.now })
|
|
@@ -433,9 +435,26 @@ export function createRoutes<Member extends RouteMember>(
|
|
|
433
435
|
}
|
|
434
436
|
|
|
435
437
|
return {
|
|
436
|
-
routes:
|
|
438
|
+
routes: routes as readonly DeclaredRoute[],
|
|
437
439
|
match,
|
|
438
440
|
invoke,
|
|
441
|
+
/**
|
|
442
|
+
* Adds routes while the server runs (story 346), checked against those
|
|
443
|
+
* already there; answers why they cannot be, and adds none then.
|
|
444
|
+
*/
|
|
445
|
+
add(entries: readonly DeclaredRoute[]): string[] {
|
|
446
|
+
const problems = siteRouteProblems([...routes, ...entries], deps.backOfficePath)
|
|
447
|
+
if (problems.length > 0) return problems
|
|
448
|
+
routes.push(...entries)
|
|
449
|
+
compiled.push(...entries.map(compile))
|
|
450
|
+
return []
|
|
451
|
+
},
|
|
452
|
+
/** Takes out every route one owner declared. */
|
|
453
|
+
remove(owner: string): void {
|
|
454
|
+
for (const list of [routes, compiled])
|
|
455
|
+
for (let at = list.length - 1; at >= 0; at--)
|
|
456
|
+
if (list[at]?.owner === owner) list.splice(at, 1)
|
|
457
|
+
},
|
|
439
458
|
/** A site request a route answers, or undefined for content finding to have it. */
|
|
440
459
|
async handle(request: Request, url: URL): Promise<Response | undefined> {
|
|
441
460
|
const found = match(url.pathname)
|
package/src/server.ts
CHANGED
|
@@ -43,6 +43,7 @@ import {
|
|
|
43
43
|
isSameOrigin,
|
|
44
44
|
memberCookieName,
|
|
45
45
|
REDACTED,
|
|
46
|
+
type ResolvedIdentity,
|
|
46
47
|
readCookie,
|
|
47
48
|
serializeCookie,
|
|
48
49
|
} from '@crombolo/auth'
|
|
@@ -78,6 +79,7 @@ import {
|
|
|
78
79
|
localReturnUrl,
|
|
79
80
|
MANAGEMENT_API_PREFIX,
|
|
80
81
|
managementApiPrefix,
|
|
82
|
+
normaliseUuid,
|
|
81
83
|
ObjectTypes,
|
|
82
84
|
PREVIEW_HUB_PATH,
|
|
83
85
|
RemotePermissions,
|
|
@@ -85,6 +87,7 @@ import {
|
|
|
85
87
|
} from '@crombolo/core'
|
|
86
88
|
import {
|
|
87
89
|
appendCacheInstruction,
|
|
90
|
+
currentAuditContext,
|
|
88
91
|
type Db,
|
|
89
92
|
ExtensionActivityLog,
|
|
90
93
|
ensureFormLibraryTypes,
|
|
@@ -106,6 +109,7 @@ import {
|
|
|
106
109
|
searchProvidersOf,
|
|
107
110
|
TransferRunRepository,
|
|
108
111
|
type WritesPaused,
|
|
112
|
+
withAuditContext,
|
|
109
113
|
} from '@crombolo/data'
|
|
110
114
|
import {
|
|
111
115
|
BUNDLE_SCRIPT,
|
|
@@ -311,6 +315,7 @@ import {
|
|
|
311
315
|
} from './status-pages.ts'
|
|
312
316
|
import { TwoFactorService, USER_TWO_FACTOR_PROVIDER } from './two-factor.ts'
|
|
313
317
|
import { summariseUpgrades } from './upgrade-summary.ts'
|
|
318
|
+
import { createViewAs } from './view-as.ts'
|
|
314
319
|
import { webhookStoreView } from './webhooks.ts'
|
|
315
320
|
|
|
316
321
|
export interface ServerHandle {
|
|
@@ -431,6 +436,12 @@ export async function createServer(
|
|
|
431
436
|
]),
|
|
432
437
|
streamMemberFile: (src, search) => streamMemberFile(src, search),
|
|
433
438
|
siteName: async () => (await seo.siteDefaults()).siteName,
|
|
439
|
+
onExtensionsChanged: () => {
|
|
440
|
+
// An instruction heard while this server is still being built has no hub to tell yet.
|
|
441
|
+
try {
|
|
442
|
+
events.broadcast('notify', [BUNDLES_CHANGED_EVENT])
|
|
443
|
+
} catch {}
|
|
444
|
+
},
|
|
434
445
|
})
|
|
435
446
|
const {
|
|
436
447
|
diagnostics,
|
|
@@ -659,6 +670,21 @@ export async function createServer(
|
|
|
659
670
|
// An extension's call through `api`, made in this process (story 308).
|
|
660
671
|
const acting = actingPrincipalOf(request)
|
|
661
672
|
if (acting) return acting
|
|
673
|
+
const identity = await identify(request)
|
|
674
|
+
if (!identity) return undefined
|
|
675
|
+
const principal = await principalFrom(identity)
|
|
676
|
+
// Story 314: what this session writes says whose groups it was seen as.
|
|
677
|
+
const context = currentAuditContext()
|
|
678
|
+
if (context && principal.viewingAs)
|
|
679
|
+
context.viewing = {
|
|
680
|
+
userKey: normaliseUuid(principal.id),
|
|
681
|
+
groups: principal.viewingAs.groups.map((g) => g.name).join(', '),
|
|
682
|
+
}
|
|
683
|
+
return principal
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/** The signed-in session a request carries, from its cookie or a bearer token. */
|
|
687
|
+
async function identify(request: Request): Promise<ResolvedIdentity | undefined> {
|
|
662
688
|
const header = request.headers.get('authorization')
|
|
663
689
|
const bearer = header?.toLowerCase().startsWith('bearer ') ? header.slice(7).trim() : undefined
|
|
664
690
|
const fromCookie = !bearer || bearer === REDACTED
|
|
@@ -678,8 +704,7 @@ export async function createServer(
|
|
|
678
704
|
return undefined
|
|
679
705
|
}
|
|
680
706
|
|
|
681
|
-
|
|
682
|
-
return identity && principalFrom(identity)
|
|
707
|
+
return auth.resolveAccessToken(token)
|
|
683
708
|
}
|
|
684
709
|
|
|
685
710
|
/** What a resolved user may do, as every check in the Management API reads it. */
|
|
@@ -698,7 +723,12 @@ export async function createServer(
|
|
|
698
723
|
permissions: identity.permissions,
|
|
699
724
|
groupKeys: identity.groupKeys,
|
|
700
725
|
hasAccessToAllLanguages: identity.hasAccessToAllLanguages,
|
|
701
|
-
...(await loadAccess(
|
|
726
|
+
...(await loadAccess(
|
|
727
|
+
db,
|
|
728
|
+
identity.user.id,
|
|
729
|
+
identity.viewingAs ? identity.groupKeys : undefined,
|
|
730
|
+
)),
|
|
731
|
+
...(identity.viewingAs ? { viewingAs: identity.viewingAs } : {}),
|
|
702
732
|
}
|
|
703
733
|
}
|
|
704
734
|
|
|
@@ -869,6 +899,7 @@ export async function createServer(
|
|
|
869
899
|
bundleGrants,
|
|
870
900
|
failed: () => [...core.failedExtensions, ...backOfficeBuilds.failed()],
|
|
871
901
|
stopExtension: (id) => core.stopExtension(id),
|
|
902
|
+
changed: (id) => core.extensionChanged(id),
|
|
872
903
|
})
|
|
873
904
|
const actorOf = (principal: Principal, request: Request): BundleActor => ({
|
|
874
905
|
id: principal.id,
|
|
@@ -1286,6 +1317,13 @@ export async function createServer(
|
|
|
1286
1317
|
showDetails: config.errors.showDetails,
|
|
1287
1318
|
cors: formCors,
|
|
1288
1319
|
})
|
|
1320
|
+
// Story 346: an extension started while the site runs adds its routes here, checked as these were.
|
|
1321
|
+
core.setRouteTable({
|
|
1322
|
+
problems: (entries) =>
|
|
1323
|
+
siteRouteProblems([...siteRoutes.routes, ...entries], config.backOfficePath),
|
|
1324
|
+
add: (entries) => siteRoutes.add(entries),
|
|
1325
|
+
remove: (owner) => siteRoutes.remove(owner),
|
|
1326
|
+
})
|
|
1289
1327
|
|
|
1290
1328
|
// Story 219: the site's server actions, a module at a time.
|
|
1291
1329
|
const { registry: actionList, problems: actionProblems } = actionRegistry(config.actions)
|
|
@@ -1308,6 +1346,7 @@ export async function createServer(
|
|
|
1308
1346
|
// Asked each time, as e-mail set up in Settings changes without a restart (story 340).
|
|
1309
1347
|
const canSendUserLinks = () => Boolean(resolveUserLinkSender(config, email))
|
|
1310
1348
|
const emailSettings = createEmailSettings(db, config, { port: () => email })
|
|
1349
|
+
const viewAs = createViewAs(db, auth)
|
|
1311
1350
|
const schemaTransfer = createSchemaTransfer(db, config, {
|
|
1312
1351
|
boot: schema,
|
|
1313
1352
|
afterApply: async (report) => {
|
|
@@ -1527,7 +1566,12 @@ export async function createServer(
|
|
|
1527
1566
|
const MEDIA_JOB_QUEUED_EVENT = { eventSource: 'Crombolo:MediaJob', eventType: 'Queued' } as const
|
|
1528
1567
|
const hostTokenPath = `${paths.pluginPath}/api/host-token`
|
|
1529
1568
|
const contentQueryPath = `${paths.pluginPath}/api/content-query`
|
|
1530
|
-
const
|
|
1569
|
+
const viewAsPath = `${paths.pluginPath}/api/view-as`
|
|
1570
|
+
const selfAudited = [
|
|
1571
|
+
`${paths.pluginPath}/api/email/`,
|
|
1572
|
+
`${paths.pluginPath}/api/schema-transfer/`,
|
|
1573
|
+
viewAsPath,
|
|
1574
|
+
]
|
|
1531
1575
|
const bundleInstallPaths = new Set(
|
|
1532
1576
|
['install', 'uninstall', 'disable', 'enable', 'grant', 'settings'].flatMap((action) => [
|
|
1533
1577
|
`${paths.pluginPath}/api/extensions/${action}`,
|
|
@@ -1564,6 +1608,11 @@ export async function createServer(
|
|
|
1564
1608
|
core.setBundleDispatch((request) => fetch(request))
|
|
1565
1609
|
|
|
1566
1610
|
async function fetch(request: Request): Promise<Response> {
|
|
1611
|
+
// A request dispatched from inside another (an extension's call) shares its audit context.
|
|
1612
|
+
return currentAuditContext() ? traced(request) : withAuditContext(() => traced(request))
|
|
1613
|
+
}
|
|
1614
|
+
|
|
1615
|
+
async function traced(request: Request): Promise<Response> {
|
|
1567
1616
|
// Story 262: every request a span, continuing a trace only from a trusted proxy.
|
|
1568
1617
|
const pathname = new URL(request.url).pathname
|
|
1569
1618
|
const route = routeOf(pathname, paths.backOfficePath)
|
|
@@ -2390,7 +2439,9 @@ export async function createServer(
|
|
|
2390
2439
|
{ ok: false, message: 'Only an administrator manages trusted signers.' },
|
|
2391
2440
|
{ status: 403 },
|
|
2392
2441
|
)
|
|
2393
|
-
const signers = createTrustedSignersAdmin(db, config
|
|
2442
|
+
const signers = createTrustedSignersAdmin(db, config, {
|
|
2443
|
+
checks: { extensions, grants: bundleGrants, changed: core.extensionChanged },
|
|
2444
|
+
})
|
|
2394
2445
|
const actor = { ...actorOf(principal, request), source: 'request' as const }
|
|
2395
2446
|
if (action === 'signers' && request.method === 'GET')
|
|
2396
2447
|
return Response.json({ items: await signers.list() })
|
|
@@ -2543,6 +2594,13 @@ export async function createServer(
|
|
|
2543
2594
|
: Response.json(outcome, { status: outcome.status })
|
|
2544
2595
|
}
|
|
2545
2596
|
|
|
2597
|
+
// Story 314: an administrator's session seen as user groups, and back.
|
|
2598
|
+
if (pathname === viewAsPath) {
|
|
2599
|
+
const identity = await identify(request)
|
|
2600
|
+
if (!identity) return new Response('Unauthorized', { status: 401 })
|
|
2601
|
+
return viewAs.handle(request, identity, clientAddress(request))
|
|
2602
|
+
}
|
|
2603
|
+
|
|
2546
2604
|
// Story 340: Settings → E-mail, administrators only.
|
|
2547
2605
|
const emailAction = /^\/api\/email\/(settings|test)$/.exec(
|
|
2548
2606
|
pathname.slice(paths.pluginPath.length),
|
package/src/settings.ts
CHANGED
|
@@ -838,9 +838,10 @@ const DECLARED = [
|
|
|
838
838
|
{
|
|
839
839
|
env: 'CROMBOLO_DELIVERY_API',
|
|
840
840
|
kind: 'boolean',
|
|
841
|
-
default: '
|
|
841
|
+
default: 'true',
|
|
842
842
|
section: 'Public site',
|
|
843
|
-
description:
|
|
843
|
+
description:
|
|
844
|
+
'The Delivery API, which serves the published pages anyone may see as JSON. false turns it off.',
|
|
844
845
|
},
|
|
845
846
|
{
|
|
846
847
|
env: 'CROMBOLO_DELIVERY_API_KEY',
|
|
@@ -851,11 +852,12 @@ const DECLARED = [
|
|
|
851
852
|
secret: true,
|
|
852
853
|
},
|
|
853
854
|
{
|
|
854
|
-
env: '
|
|
855
|
+
env: 'CROMBOLO_DELIVERY_API_PRIVATE',
|
|
855
856
|
kind: 'boolean',
|
|
856
|
-
default: '
|
|
857
|
+
default: 'false',
|
|
857
858
|
section: 'Public site',
|
|
858
|
-
description:
|
|
859
|
+
description:
|
|
860
|
+
'Makes the Delivery API private: every request needs the key. Unset, it serves what the site publishes.',
|
|
859
861
|
},
|
|
860
862
|
{
|
|
861
863
|
env: 'CROMBOLO_DELIVERY_API_MEDIA',
|
|
@@ -867,9 +869,10 @@ const DECLARED = [
|
|
|
867
869
|
{
|
|
868
870
|
env: 'CROMBOLO_DELIVERY_API_CORS_ORIGINS',
|
|
869
871
|
kind: 'list',
|
|
872
|
+
default: 'any site, while the API is public',
|
|
870
873
|
section: 'Public site',
|
|
871
874
|
description:
|
|
872
|
-
'
|
|
875
|
+
'Narrows which other sites may call the Delivery API from the browser, such as https://app.example.com, separated by commas.',
|
|
873
876
|
},
|
|
874
877
|
{
|
|
875
878
|
env: 'CROMBOLO_CACHE_MAX_AGE',
|
|
@@ -5,9 +5,12 @@
|
|
|
5
5
|
* site's own key, are shown and never removed here. Settings, the CLI and the
|
|
6
6
|
* back-office endpoint share it.
|
|
7
7
|
*/
|
|
8
|
+
import { createExtensionRegistry, type ExtensionRegistry } from '@crombolo/backoffice-host/registry'
|
|
8
9
|
import { type Db, TrustedSignerRepository } from '@crombolo/data'
|
|
9
10
|
import { recordAudit } from './adapters/audit.ts'
|
|
11
|
+
import { type BundleGrants, createBundleGrants } from './bundle-grants.ts'
|
|
10
12
|
import type { CromboloConfig } from './config.ts'
|
|
13
|
+
import { switchOffUntrusted } from './grant-trust.ts'
|
|
11
14
|
import { readPublicKey } from './signing-keys.ts'
|
|
12
15
|
import { type TrustEntry, trustedSigners } from './site-trust.ts'
|
|
13
16
|
|
|
@@ -21,14 +24,42 @@ export interface SignerActor {
|
|
|
21
24
|
}
|
|
22
25
|
|
|
23
26
|
export type SignerOutcome =
|
|
24
|
-
| {
|
|
27
|
+
| {
|
|
28
|
+
ok: true
|
|
29
|
+
entry?: TrustEntry
|
|
30
|
+
/** Extensions switched off as their signer was removed, by name (story 335). */
|
|
31
|
+
switchedOff?: string[]
|
|
32
|
+
}
|
|
25
33
|
| { ok: false; status: number; message: string }
|
|
26
34
|
|
|
35
|
+
/** What removing a signer re-checks: the server's own, or this site's, read here. */
|
|
36
|
+
export interface SignerChecks {
|
|
37
|
+
extensions: ExtensionRegistry
|
|
38
|
+
grants: Pick<BundleGrants, 'granted' | 'isOn' | 'state' | 'forget'>
|
|
39
|
+
/** Brings a switched-off extension's process to its grant, where a server runs here (story 346). */
|
|
40
|
+
changed?: (id: string) => Promise<unknown>
|
|
41
|
+
}
|
|
42
|
+
|
|
27
43
|
/** `org/repo`, `org/*`, or either `@` a ref pattern such as `v*`. */
|
|
28
44
|
const SOURCE = /^[A-Za-z0-9_.-]+\/(\*|[A-Za-z0-9_.-]+)(@[A-Za-z0-9_.*/-]+)?$/
|
|
29
45
|
|
|
30
|
-
export function createTrustedSignersAdmin(
|
|
46
|
+
export function createTrustedSignersAdmin(
|
|
47
|
+
db: Db,
|
|
48
|
+
config: CromboloConfig,
|
|
49
|
+
options: { checks?: SignerChecks } = {},
|
|
50
|
+
) {
|
|
31
51
|
const repo = new TrustedSignerRepository(db)
|
|
52
|
+
/** The running server's registry and grants, or this site's, read from its files and database. */
|
|
53
|
+
const checks = async (): Promise<SignerChecks> => {
|
|
54
|
+
if (options.checks) return options.checks
|
|
55
|
+
const extensions = createExtensionRegistry(config.siteDir, { cache: false })
|
|
56
|
+
const grants = createBundleGrants({
|
|
57
|
+
db,
|
|
58
|
+
packages: () => new Map(extensions.bundles().bundles.map((pkg) => [pkg.id, pkg])),
|
|
59
|
+
})
|
|
60
|
+
await grants.refresh()
|
|
61
|
+
return { extensions, grants }
|
|
62
|
+
}
|
|
32
63
|
const audit = (actor: SignerActor, action: string, name: string, detail: string | null) =>
|
|
33
64
|
recordAudit(db, {
|
|
34
65
|
category: 'system',
|
|
@@ -124,7 +155,12 @@ export function createTrustedSignersAdmin(db: Db, config: CromboloConfig) {
|
|
|
124
155
|
found.name,
|
|
125
156
|
found.fingerprint ? `${found.kind} key ${found.fingerprint}` : `builds of ${found.source}`,
|
|
126
157
|
)
|
|
127
|
-
|
|
158
|
+
// Story 335: what it vouched for loses its upper level now, not at the next start.
|
|
159
|
+
const { extensions, grants, changed } = await checks()
|
|
160
|
+
const ids = await switchOffUntrusted(db, config, extensions, grants, 'untrusted')
|
|
161
|
+
for (const switched of ids) await changed?.(switched)
|
|
162
|
+
const names = new Map(extensions.bundles().bundles.map((pkg) => [pkg.id, pkg.name]))
|
|
163
|
+
return { ok: true, switchedOff: ids.map((id) => names.get(id) ?? id) }
|
|
128
164
|
},
|
|
129
165
|
}
|
|
130
166
|
}
|
package/src/view-as.ts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An administrator's back-office session seen as user groups, for up to an hour
|
|
3
|
+
* (story 314). `<plugin>/api/view-as` says whether this session is (GET), starts
|
|
4
|
+
* it (POST `{ groups }`) and switches back (DELETE). docs/backoffice-hosting.md,
|
|
5
|
+
* "Viewing as a group".
|
|
6
|
+
*/
|
|
7
|
+
import type { AuthService, ResolvedIdentity, ViewingAs } from '@crombolo/auth'
|
|
8
|
+
import { currentAuditContext, type Db, UserGroupRepository } from '@crombolo/data'
|
|
9
|
+
import { recordAudit } from './adapters/audit.ts'
|
|
10
|
+
|
|
11
|
+
export interface ViewAsStatus {
|
|
12
|
+
/** What this session is viewing as, or null when it is its user's own. */
|
|
13
|
+
viewing: { groups: Array<{ key: string; name: string }>; until: string } | null
|
|
14
|
+
/** Whether this person may view as groups: an administrator in their own right. */
|
|
15
|
+
allowed: boolean
|
|
16
|
+
/** The groups to choose from, for one who may. */
|
|
17
|
+
groups: Array<{ key: string; name: string }>
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const named = (view: ViewingAs) => view.groups.map((g) => g.name).join(', ')
|
|
21
|
+
|
|
22
|
+
export function createViewAs(db: Db, auth: Pick<AuthService, 'startViewing' | 'stopViewing'>) {
|
|
23
|
+
const status = async (
|
|
24
|
+
identity: ResolvedIdentity,
|
|
25
|
+
viewing: ViewingAs | undefined,
|
|
26
|
+
): Promise<ViewAsStatus> => {
|
|
27
|
+
// Viewing as groups is only ever on for an administrator, whatever the groups are.
|
|
28
|
+
const allowed = identity.isAdmin || identity.viewingAs !== undefined
|
|
29
|
+
return {
|
|
30
|
+
viewing: viewing ? { groups: viewing.groups, until: viewing.until.toISOString() } : null,
|
|
31
|
+
allowed,
|
|
32
|
+
groups: allowed
|
|
33
|
+
? (await new UserGroupRepository(db).all()).map((g) => ({ key: g.key, name: g.name }))
|
|
34
|
+
: [],
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const audit = (
|
|
39
|
+
identity: ResolvedIdentity,
|
|
40
|
+
action: string,
|
|
41
|
+
detail: string,
|
|
42
|
+
client: { ipAddress: string | null; forwardedFor: string | null },
|
|
43
|
+
) => {
|
|
44
|
+
// The entry names the groups itself; the request's own view is not added to it.
|
|
45
|
+
const context = currentAuditContext()
|
|
46
|
+
if (context) context.viewing = undefined
|
|
47
|
+
return recordAudit(db, {
|
|
48
|
+
category: 'permission',
|
|
49
|
+
action,
|
|
50
|
+
source: 'request',
|
|
51
|
+
userKey: identity.user.key,
|
|
52
|
+
userName: identity.user.userName,
|
|
53
|
+
entityType: 'User',
|
|
54
|
+
entityKey: identity.user.key,
|
|
55
|
+
entityName: identity.user.userName,
|
|
56
|
+
detail,
|
|
57
|
+
...client,
|
|
58
|
+
})
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
return {
|
|
62
|
+
async handle(
|
|
63
|
+
request: Request,
|
|
64
|
+
identity: ResolvedIdentity,
|
|
65
|
+
client: { ipAddress: string | null; forwardedFor: string | null },
|
|
66
|
+
): Promise<Response> {
|
|
67
|
+
if (request.method === 'GET') return Response.json(await status(identity, identity.viewingAs))
|
|
68
|
+
if (request.method === 'DELETE') {
|
|
69
|
+
const was = await auth.stopViewing(identity.sessionId)
|
|
70
|
+
if (was) await audit(identity, 'Switched back', `from viewing as ${named(was)}`, client)
|
|
71
|
+
return Response.json(await status(identity, undefined))
|
|
72
|
+
}
|
|
73
|
+
if (request.method === 'POST') {
|
|
74
|
+
const body = (await request.json().catch(() => ({}))) as { groups?: unknown }
|
|
75
|
+
const keys = Array.isArray(body?.groups)
|
|
76
|
+
? body.groups.filter((k): k is string => typeof k === 'string')
|
|
77
|
+
: []
|
|
78
|
+
const started = await auth.startViewing(identity.sessionId, keys)
|
|
79
|
+
if (started === 'refused')
|
|
80
|
+
return Response.json(
|
|
81
|
+
{ message: 'Only an administrator can view the back office as a group.' },
|
|
82
|
+
{ status: 403 },
|
|
83
|
+
)
|
|
84
|
+
if (started === 'no-groups')
|
|
85
|
+
return Response.json({ message: 'Choose at least one group.' }, { status: 400 })
|
|
86
|
+
await audit(identity, 'Started viewing as', named(started), client)
|
|
87
|
+
return Response.json(await status(identity, started))
|
|
88
|
+
}
|
|
89
|
+
return new Response('Method Not Allowed', {
|
|
90
|
+
status: 405,
|
|
91
|
+
headers: { allow: 'GET, POST, DELETE' },
|
|
92
|
+
})
|
|
93
|
+
},
|
|
94
|
+
}
|
|
95
|
+
}
|