@crombolo/server 0.60.0 → 0.62.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 +14 -14
- package/src/adapters/audit.ts +24 -4
- package/src/approvals-api.ts +2 -2
- package/src/bundle-admin.ts +194 -25
- package/src/bundle-api.ts +67 -16
- package/src/bundle-code-install.ts +18 -1
- package/src/bundle-code.ts +93 -5
- package/src/bundle-grants.ts +78 -15
- package/src/bundles.ts +143 -4
- package/src/component-templates-api.ts +2 -2
- package/src/config.ts +58 -9
- package/src/core.ts +124 -42
- package/src/extension-activity.ts +237 -0
- package/src/extension-components.ts +17 -1
- package/src/extension-discovery.ts +37 -3
- package/src/extension-install.ts +631 -0
- package/src/extension-process.ts +170 -35
- package/src/extension-screens.ts +383 -0
- package/src/external-sign-in.ts +10 -0
- package/src/form-workflows.ts +110 -12
- package/src/grant-policy.ts +57 -0
- package/src/identity-provider-overrides.ts +186 -36
- package/src/identity-providers.ts +23 -0
- package/src/index.ts +16 -1
- package/src/jobs.ts +23 -0
- package/src/marketplace.ts +182 -313
- package/src/member-auth.ts +5 -1
- package/src/outbound-address.ts +1 -1
- package/src/ports.ts +1 -2
- package/src/remote.ts +12 -4
- package/src/server.ts +161 -16
- package/src/settings.ts +31 -0
- package/src/site-file.ts +5 -2
package/src/config.ts
CHANGED
|
@@ -23,8 +23,13 @@ import {
|
|
|
23
23
|
import type { ServerBundle } from './bundles.ts'
|
|
24
24
|
import type { EmailPort } from './email.ts'
|
|
25
25
|
import type { GitConfig } from './git-routes.ts'
|
|
26
|
+
import { type UnrestrictedFrom, unrestrictedFrom } from './grant-policy.ts'
|
|
26
27
|
import { checkHost, type HostConfig } from './host-token.ts'
|
|
27
|
-
import {
|
|
28
|
+
import {
|
|
29
|
+
checkIdentityProviders,
|
|
30
|
+
type IdentityProvider,
|
|
31
|
+
type LockedIdentityProviders,
|
|
32
|
+
} from './identity-providers.ts'
|
|
28
33
|
import type { MediaStore } from './media-store.ts'
|
|
29
34
|
import type { JobSchedule } from './owner-jobs.ts'
|
|
30
35
|
import type { ProvenancePolicy, SignaturePolicy } from './provenance.ts'
|
|
@@ -175,6 +180,18 @@ export interface CromboloConfig {
|
|
|
175
180
|
* except under `bun test`.
|
|
176
181
|
*/
|
|
177
182
|
liveReload: boolean
|
|
183
|
+
/**
|
|
184
|
+
* Whether webhooks, a form's send-to-URL workflow and an identity provider's
|
|
185
|
+
* test may reach loopback, private and link-local addresses (stories 301,
|
|
186
|
+
* 304). `CROMBOLO_ALLOW_PRIVATE_ADDRESSES`; on in development only.
|
|
187
|
+
*/
|
|
188
|
+
allowPrivateAddresses: boolean
|
|
189
|
+
/**
|
|
190
|
+
* Identity providers no change from the back office reaches (story 305), by
|
|
191
|
+
* id, or all of them: `CROMBOLO_LOCKED_IDENTITY_PROVIDERS`, so a host locks
|
|
192
|
+
* them without the site's code. A provider's own `locked: true` does too.
|
|
193
|
+
*/
|
|
194
|
+
lockedIdentityProviders: LockedIdentityProviders
|
|
178
195
|
/**
|
|
179
196
|
* Whether the cache-busted asset path may be cached immutably. Defaults to
|
|
180
197
|
* `!development`.
|
|
@@ -343,6 +360,11 @@ export interface CromboloConfig {
|
|
|
343
360
|
}
|
|
344
361
|
/** How many days the audit log keeps an entry; 0 keeps them forever. docs/audit-log.md. */
|
|
345
362
|
auditRetentionDays: number
|
|
363
|
+
/**
|
|
364
|
+
* How many days what each extension did is kept for its Activity view (story
|
|
365
|
+
* 327); 0 keeps none. `CROMBOLO_EXTENSION_ACTIVITY_DAYS`.
|
|
366
|
+
*/
|
|
367
|
+
extensionActivityDays: number
|
|
346
368
|
/**
|
|
347
369
|
* How many days delivered webhooks, their log and dispatched content events
|
|
348
370
|
* are kept; 0 keeps them forever. Failed work stays until retried. docs/webhooks.md.
|
|
@@ -537,12 +559,10 @@ export interface CromboloConfig {
|
|
|
537
559
|
*/
|
|
538
560
|
events?: Readonly<Record<string, SiteEventHandler>>
|
|
539
561
|
/**
|
|
540
|
-
*
|
|
541
|
-
* `
|
|
542
|
-
* go to loopback, private and link-local addresses: by default only on a
|
|
543
|
-
* development site. docs/webhooks.md.
|
|
562
|
+
* The server variables a webhook header's `env:NAME` may name besides
|
|
563
|
+
* `CROMBOLO_WEBHOOK_*` (story 301). docs/webhooks.md.
|
|
544
564
|
*/
|
|
545
|
-
webhooks?: { headerVariables?: readonly string[]
|
|
565
|
+
webhooks?: { headerVariables?: readonly string[] }
|
|
546
566
|
/**
|
|
547
567
|
* Installed extensions the site's code grants and sets (story 310), by bundle
|
|
548
568
|
* id: what it grants, as "Developer installed", and settings, which lock them
|
|
@@ -593,6 +613,13 @@ export interface CromboloConfig {
|
|
|
593
613
|
* `CROMBOLO_BUNDLE_SIGNATURES` and `CROMBOLO_BUNDLE_SOURCES`.
|
|
594
614
|
*/
|
|
595
615
|
bundlePolicy: ProvenancePolicy
|
|
616
|
+
/**
|
|
617
|
+
* Where an Unrestricted extension may be granted from (story 324): the back
|
|
618
|
+
* office, by an administrator, or only the site's config, so a commit someone
|
|
619
|
+
* reviews is the only way. `CROMBOLO_UNRESTRICTED_EXTENSIONS`, `backoffice`
|
|
620
|
+
* unless it says `config`.
|
|
621
|
+
*/
|
|
622
|
+
unrestrictedExtensions: UnrestrictedFrom
|
|
596
623
|
/**
|
|
597
624
|
* Where the Packages section's Marketplace sends someone browsing for
|
|
598
625
|
* extensions. Never framed — npm refuses to be framed — so the native view
|
|
@@ -623,8 +650,6 @@ export interface ExtensionEntry {
|
|
|
623
650
|
grant?: readonly string[]
|
|
624
651
|
/** The origins its `http.outbound` may reach, when it asks for any. */
|
|
625
652
|
origins?: readonly string[]
|
|
626
|
-
/** Whom `actAs` acts for: `caller`, or `user:<key>`. */
|
|
627
|
-
actAs?: string
|
|
628
653
|
/** Its settings' values, locked in the back office. */
|
|
629
654
|
settings?: Readonly<Record<string, unknown>>
|
|
630
655
|
/**
|
|
@@ -679,6 +704,7 @@ export const DEFAULTS = {
|
|
|
679
704
|
keepAllVersionsNewerThanDays: 7,
|
|
680
705
|
keepLatestVersionPerDayForDays: 90,
|
|
681
706
|
auditRetentionDays: 365,
|
|
707
|
+
extensionActivityDays: 14,
|
|
682
708
|
eventRetentionDays: 30,
|
|
683
709
|
memberRegistrationType: 'Member',
|
|
684
710
|
memberSessionMinutes: 60 * 24 * 14,
|
|
@@ -893,6 +919,10 @@ export function loadConfig(
|
|
|
893
919
|
setting('CROMBOLO_AUDIT_RETENTION_DAYS'),
|
|
894
920
|
DEFAULTS.auditRetentionDays,
|
|
895
921
|
),
|
|
922
|
+
extensionActivityDays: nonNegative(
|
|
923
|
+
setting('CROMBOLO_EXTENSION_ACTIVITY_DAYS'),
|
|
924
|
+
DEFAULTS.extensionActivityDays,
|
|
925
|
+
),
|
|
896
926
|
eventRetentionDays: nonNegative(
|
|
897
927
|
setting('CROMBOLO_EVENT_RETENTION_DAYS'),
|
|
898
928
|
DEFAULTS.eventRetentionDays,
|
|
@@ -951,6 +981,7 @@ export function loadConfig(
|
|
|
951
981
|
applyBundleContentOnInstall: setting('CROMBOLO_APPLY_BUNDLE_CONTENT') !== 'false',
|
|
952
982
|
// Resolved again below, once it is known whether a store was configured.
|
|
953
983
|
runtimeInstalls: setting('CROMBOLO_RUNTIME_INSTALLS') !== 'false',
|
|
984
|
+
unrestrictedExtensions: unrestrictedFrom(setting('CROMBOLO_UNRESTRICTED_EXTENSIONS')),
|
|
954
985
|
bundlePolicy: {
|
|
955
986
|
signatures: bundleSignatures(setting('CROMBOLO_BUNDLE_SIGNATURES')),
|
|
956
987
|
sources: (setting('CROMBOLO_BUNDLE_SOURCES') ?? '')
|
|
@@ -961,6 +992,8 @@ export function loadConfig(
|
|
|
961
992
|
// Resolved again below, once it is known whether this is development.
|
|
962
993
|
errors: { showDetails: envFlag(setting('CROMBOLO_SHOW_ERROR_DETAILS')) ?? false },
|
|
963
994
|
liveReload: envFlag(setting('CROMBOLO_LIVE_RELOAD')) ?? false,
|
|
995
|
+
allowPrivateAddresses: envFlag(setting('CROMBOLO_ALLOW_PRIVATE_ADDRESSES')) ?? false,
|
|
996
|
+
lockedIdentityProviders: lockedProviders(setting('CROMBOLO_LOCKED_IDENTITY_PROVIDERS')),
|
|
964
997
|
seo: stripUndefined({
|
|
965
998
|
sitemap: envFlag(setting('CROMBOLO_SITEMAP')),
|
|
966
999
|
indexable: envFlag(setting('CROMBOLO_INDEXABLE')),
|
|
@@ -1037,6 +1070,14 @@ export function loadConfig(
|
|
|
1037
1070
|
overrides.liveReload ??
|
|
1038
1071
|
envFlag(setting('CROMBOLO_LIVE_RELOAD')) ??
|
|
1039
1072
|
(merged.development && setting('NODE_ENV') !== 'test')
|
|
1073
|
+
merged.allowPrivateAddresses =
|
|
1074
|
+
overrides.allowPrivateAddresses ??
|
|
1075
|
+
envFlag(setting('CROMBOLO_ALLOW_PRIVATE_ADDRESSES')) ??
|
|
1076
|
+
merged.development
|
|
1077
|
+
if (overrides.webhooks && 'allowPrivateAddresses' in overrides.webhooks)
|
|
1078
|
+
throw new Error(
|
|
1079
|
+
'webhooks.allowPrivateAddresses is now CROMBOLO_ALLOW_PRIVATE_ADDRESSES (allowPrivateAddresses in the config), which covers forms and identity providers too (story 304).',
|
|
1080
|
+
)
|
|
1040
1081
|
checkApiClient(merged.apiClient)
|
|
1041
1082
|
checkHost(merged.host)
|
|
1042
1083
|
// The key itself is refused, so a config left over from before says so rather
|
|
@@ -1109,6 +1150,14 @@ function nonNegative(value: string | undefined, fallback: number): number {
|
|
|
1109
1150
|
return Number.isInteger(parsed) && parsed >= 0 ? parsed : fallback
|
|
1110
1151
|
}
|
|
1111
1152
|
|
|
1153
|
+
function lockedProviders(value: string | undefined): LockedIdentityProviders {
|
|
1154
|
+
const ids = (value ?? '')
|
|
1155
|
+
.split(',')
|
|
1156
|
+
.map((id) => id.trim())
|
|
1157
|
+
.filter(Boolean)
|
|
1158
|
+
return ids.includes('all') ? 'all' : ids
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1112
1161
|
function envFlag(value: string | undefined): boolean | undefined {
|
|
1113
1162
|
return value === undefined ? undefined : value !== 'false'
|
|
1114
1163
|
}
|
|
@@ -1144,7 +1193,7 @@ export function describeDatabase(
|
|
|
1144
1193
|
}
|
|
1145
1194
|
}
|
|
1146
1195
|
|
|
1147
|
-
export const VERSION = '0.
|
|
1196
|
+
export const VERSION = '0.62.0'
|
|
1148
1197
|
|
|
1149
1198
|
/** A whole number of seconds from the environment; undefined when unset or not one. */
|
|
1150
1199
|
/** A positive number from a setting, else the default. */
|
package/src/core.ts
CHANGED
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
BUNDLE_PERMISSIONS,
|
|
12
12
|
createBackOfficePaths,
|
|
13
13
|
createExtensionRegistry,
|
|
14
|
+
USER_DELEGATE,
|
|
14
15
|
} from '@crombolo/backoffice-host/registry'
|
|
15
16
|
import { mediaJobHandlers } from '@crombolo/content'
|
|
16
17
|
import { ObjectTypes } from '@crombolo/core'
|
|
@@ -39,11 +40,11 @@ import {
|
|
|
39
40
|
ViewSnapshots,
|
|
40
41
|
} from '@crombolo/render'
|
|
41
42
|
import type { SyncReport } from '@crombolo/schema'
|
|
42
|
-
import { recordAudit } from './adapters/audit.ts'
|
|
43
|
+
import { attributed, recordAudit } from './adapters/audit.ts'
|
|
43
44
|
import { createMediaSource, createPublishedContentSource } from './adapters/documents.ts'
|
|
44
45
|
import { backOfficeUrl, documentEditUrl } from './back-office-url.ts'
|
|
45
46
|
import { BACKOFFICE_EXTERNAL_PATH } from './backoffice-external.ts'
|
|
46
|
-
import {
|
|
47
|
+
import { createBundleApi, extensionPrincipal } from './bundle-api.ts'
|
|
47
48
|
import {
|
|
48
49
|
APPROVED_BY_CODE,
|
|
49
50
|
createBundleGrants,
|
|
@@ -66,6 +67,7 @@ import { databaseFor, openTables, siteTablesProblems, tablesChains } from './cus
|
|
|
66
67
|
import { attachDatabase, bootstrapDatabase } from './database.ts'
|
|
67
68
|
import { createDiagnostics } from './diagnostics.ts'
|
|
68
69
|
import { resolveEmailPort } from './email.ts'
|
|
70
|
+
import { createActivityRecorder, personOf, timed } from './extension-activity.ts'
|
|
69
71
|
import { createExtensionComponents } from './extension-components.ts'
|
|
70
72
|
import {
|
|
71
73
|
entryCovers,
|
|
@@ -195,11 +197,14 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
|
|
|
195
197
|
const entryProblems = extensionEntryProblems(config.extensions, bundlePackages)
|
|
196
198
|
if (entryProblems.length > 0)
|
|
197
199
|
throw new Error(`The installed extensions cannot be started:\n- ${entryProblems.join('\n- ')}`)
|
|
200
|
+
// Story 327: what each extension does, kept for the Activity view.
|
|
201
|
+
const activity = createActivityRecorder(() => db)
|
|
198
202
|
const extensionsStarted = await startExtensions(
|
|
199
203
|
config,
|
|
200
204
|
bundlePackages,
|
|
201
205
|
await readRecordedExtensions(config),
|
|
202
206
|
bundleLog,
|
|
207
|
+
activity,
|
|
203
208
|
)
|
|
204
209
|
const extensionProcesses = extensionsStarted.processes
|
|
205
210
|
const failedExtensions = extensionsStarted.failed
|
|
@@ -302,12 +307,7 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
|
|
|
302
307
|
)
|
|
303
308
|
const bundle = { id: pkg.id }
|
|
304
309
|
// Recorded where the database is written, and audited when it changes.
|
|
305
|
-
if (
|
|
306
|
-
owns &&
|
|
307
|
-
(await bundleGrants.grant(pkg, APPROVED_BY_CODE, {
|
|
308
|
-
actAs: entry?.actAs ? actAsChoice(entry.actAs) : undefined,
|
|
309
|
-
}))
|
|
310
|
-
)
|
|
310
|
+
if (owns && (await bundleGrants.grant(pkg, APPROVED_BY_CODE)))
|
|
311
311
|
await recordAudit(db, {
|
|
312
312
|
category: 'system',
|
|
313
313
|
action: 'Grant',
|
|
@@ -500,7 +500,7 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
|
|
|
500
500
|
// A development site's receivers are on this machine, as the Next.js template's is.
|
|
501
501
|
outbound: {
|
|
502
502
|
...config.webhooks,
|
|
503
|
-
allowPrivateAddresses: config.
|
|
503
|
+
allowPrivateAddresses: config.allowPrivateAddresses,
|
|
504
504
|
},
|
|
505
505
|
isBundleOn: (bundleId) => bundleGrants.isOn(bundleId),
|
|
506
506
|
bundleOrigins: (bundleId) => {
|
|
@@ -575,11 +575,66 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
|
|
|
575
575
|
* boot — see `createServerBundles`.
|
|
576
576
|
*/
|
|
577
577
|
// Story 198: media as the member, built at the first request.
|
|
578
|
+
/** The identity providers an extension edits (story 033), auditing each change when told how (305). */
|
|
579
|
+
const identityProvidersFor = (
|
|
580
|
+
audit?: Parameters<typeof createBundleIdentityProviders>[0]['audit'],
|
|
581
|
+
) =>
|
|
582
|
+
createBundleIdentityProviders({
|
|
583
|
+
audit,
|
|
584
|
+
overrides: new IdentityProviderOverrides(
|
|
585
|
+
db,
|
|
586
|
+
config.secretKey,
|
|
587
|
+
config.lockedIdentityProviders,
|
|
588
|
+
),
|
|
589
|
+
members: config.memberIdentityProviders,
|
|
590
|
+
backoffice: config.backofficeIdentityProviders,
|
|
591
|
+
memberCallbackPath: MEMBER_EXTERNAL_SIGN_IN_PATH,
|
|
592
|
+
backofficeCallbackPath: BACKOFFICE_EXTERNAL_PATH,
|
|
593
|
+
outbound: { allowPrivateAddresses: config.allowPrivateAddresses },
|
|
594
|
+
groups: async (audience) =>
|
|
595
|
+
audience === 'user'
|
|
596
|
+
? (await new UserGroupRepository(db).all()).map((g) => ({
|
|
597
|
+
value: g.alias,
|
|
598
|
+
name: g.name,
|
|
599
|
+
}))
|
|
600
|
+
: (
|
|
601
|
+
await db.q
|
|
602
|
+
.selectFrom('node')
|
|
603
|
+
.select('text')
|
|
604
|
+
.where('node_object_type', '=', ObjectTypes.MemberGroup)
|
|
605
|
+
.orderBy('text')
|
|
606
|
+
.execute()
|
|
607
|
+
).map((g) => ({ value: String(g.text), name: String(g.text) })),
|
|
608
|
+
})
|
|
609
|
+
// Story 305: said at boot, a provider that signs nobody in and a locked id that names none.
|
|
610
|
+
void (async () => {
|
|
611
|
+
const overrides = new IdentityProviderOverrides(
|
|
612
|
+
db,
|
|
613
|
+
config.secretKey,
|
|
614
|
+
config.lockedIdentityProviders,
|
|
615
|
+
)
|
|
616
|
+
const declared = [
|
|
617
|
+
...config.memberIdentityProviders.map((provider) => ['member', provider] as const),
|
|
618
|
+
...config.backofficeIdentityProviders.map((provider) => ['user', provider] as const),
|
|
619
|
+
]
|
|
620
|
+
for (const [audience, provider] of declared) {
|
|
621
|
+
const effective = await overrides.apply(audience, provider).catch(() => provider)
|
|
622
|
+
if (effective.unavailable) log.warning('{reason}', { reason: effective.unavailable })
|
|
623
|
+
}
|
|
624
|
+
if (Array.isArray(config.lockedIdentityProviders))
|
|
625
|
+
for (const id of config.lockedIdentityProviders)
|
|
626
|
+
if (!declared.some(([, provider]) => provider.oidc.id === id))
|
|
627
|
+
log.warning(
|
|
628
|
+
'CROMBOLO_LOCKED_IDENTITY_PROVIDERS names {id}, which the config declares no identity provider as.',
|
|
629
|
+
{ id },
|
|
630
|
+
)
|
|
631
|
+
})()
|
|
578
632
|
let bundleMedia: BundleMediaFactory | undefined
|
|
579
633
|
let bundleMediaFolders = new Map<string, ResolvedMediaFolder[]>()
|
|
580
634
|
const bundles =
|
|
581
635
|
config.bundles.length > 0
|
|
582
636
|
? createServerBundles({
|
|
637
|
+
activity,
|
|
583
638
|
bundles: config.bundles,
|
|
584
639
|
packages: bundlePackages,
|
|
585
640
|
coreVersion: VERSION,
|
|
@@ -600,36 +655,35 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
|
|
|
600
655
|
},
|
|
601
656
|
},
|
|
602
657
|
log: bundleLog('bundle'),
|
|
603
|
-
identityProviders:
|
|
604
|
-
overrides: new IdentityProviderOverrides(db, config.secretKey),
|
|
605
|
-
members: config.memberIdentityProviders,
|
|
606
|
-
backoffice: config.backofficeIdentityProviders,
|
|
607
|
-
memberCallbackPath: MEMBER_EXTERNAL_SIGN_IN_PATH,
|
|
608
|
-
backofficeCallbackPath: BACKOFFICE_EXTERNAL_PATH,
|
|
609
|
-
groups: async (audience) =>
|
|
610
|
-
audience === 'user'
|
|
611
|
-
? (await new UserGroupRepository(db).all()).map((g) => ({
|
|
612
|
-
value: g.alias,
|
|
613
|
-
name: g.name,
|
|
614
|
-
}))
|
|
615
|
-
: (
|
|
616
|
-
await db.q
|
|
617
|
-
.selectFrom('node')
|
|
618
|
-
.select('text')
|
|
619
|
-
.where('node_object_type', '=', ObjectTypes.MemberGroup)
|
|
620
|
-
.orderBy('text')
|
|
621
|
-
.execute()
|
|
622
|
-
).map((g) => ({ value: String(g.text), name: String(g.text) })),
|
|
623
|
-
}),
|
|
658
|
+
identityProviders: identityProvidersFor(),
|
|
624
659
|
},
|
|
625
660
|
log: (id) => bundleLog(id),
|
|
626
661
|
callerHost: {
|
|
627
|
-
// Story
|
|
662
|
+
// Story 305: each change audited as the person, by the extension.
|
|
663
|
+
identityProviders: (caller, bundle) =>
|
|
664
|
+
identityProvidersFor(async (action, provider, detail) => {
|
|
665
|
+
const person = personOf(caller)
|
|
666
|
+
const name = bundlePackages.find((pkg) => pkg.id === bundle.id)?.name ?? bundle.id
|
|
667
|
+
await recordAudit(db, {
|
|
668
|
+
category: 'settings',
|
|
669
|
+
action,
|
|
670
|
+
source: 'request',
|
|
671
|
+
userKey: person.personKey,
|
|
672
|
+
userName: person.personName,
|
|
673
|
+
entityType: 'IdentityProvider',
|
|
674
|
+
entityKey: `${provider.audience}:${provider.id}`,
|
|
675
|
+
entityName: provider.name,
|
|
676
|
+
detail: attributed(name, person.personName, detail),
|
|
677
|
+
})
|
|
678
|
+
}),
|
|
679
|
+
// Story 308: the site's areas, as the extension; story 325, or as the person using it.
|
|
628
680
|
api: (caller, bundle) => {
|
|
629
681
|
const pkg = bundlePackages.find((candidate) => candidate.id === bundle.id)
|
|
630
682
|
const granted = () => bundleGrants.granted(bundle.id)
|
|
631
683
|
return createBundleApi({
|
|
632
684
|
bundleId: bundle.id,
|
|
685
|
+
bundleName: pkg?.name ?? bundle.id,
|
|
686
|
+
activity: { recorder: activity, person: personOf(caller) },
|
|
633
687
|
origin: (config.applicationUrl || 'http://localhost').replace(/\/+$/, ''),
|
|
634
688
|
backOfficePath: config.backOfficePath,
|
|
635
689
|
granted,
|
|
@@ -639,12 +693,18 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
|
|
|
639
693
|
{ id: bundle.id, name: pkg?.name ?? bundle.id },
|
|
640
694
|
granted(),
|
|
641
695
|
)
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
696
|
+
if (!pkg || !granted().includes(USER_DELEGATE)) return itself
|
|
697
|
+
if (caller.kind === 'backoffice') return caller.principal
|
|
698
|
+
// A job or an event acts for whoever granted it; a visitor never borrows anyone.
|
|
699
|
+
const key =
|
|
700
|
+
caller.kind === 'job' ? bundleGrants.state(pkg).grant?.delegateKey : null
|
|
701
|
+
const installer = key ? await userPrincipalByKey(db, key) : undefined
|
|
702
|
+
if (key && !installer)
|
|
703
|
+
bundleLog(bundle.id).warn(
|
|
704
|
+
'It acts for whoever granted it, {key}, who is no longer a user: it acts as itself.',
|
|
705
|
+
{ key },
|
|
706
|
+
)
|
|
707
|
+
return installer ?? itself
|
|
648
708
|
},
|
|
649
709
|
})
|
|
650
710
|
},
|
|
@@ -654,14 +714,24 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
|
|
|
654
714
|
fetch: async (input, init) => {
|
|
655
715
|
const url = new URL(input instanceof Request ? input.url : String(input))
|
|
656
716
|
const origins = declaredOrigins(pkg)
|
|
657
|
-
|
|
717
|
+
const event = {
|
|
718
|
+
extensionId: bundle.id,
|
|
719
|
+
...personOf(_caller),
|
|
720
|
+
kind: 'request' as const,
|
|
721
|
+
area: url.host,
|
|
722
|
+
verb: (init?.method ?? 'GET').toUpperCase(),
|
|
723
|
+
}
|
|
724
|
+
if (!origins.includes(url.origin)) {
|
|
725
|
+
activity.record({ ...event, kind: 'refused', outcome: 'refused' })
|
|
658
726
|
throw new OutboundRefused(
|
|
659
727
|
`${bundle.id} may not reach ${url.origin}: its http.outbound names ${origins.join(', ') || 'nothing'}.`,
|
|
660
728
|
)
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
729
|
+
}
|
|
730
|
+
return timed(activity, event, () =>
|
|
731
|
+
pinnedFetch(input, init, {
|
|
732
|
+
allowPrivateAddresses: config.allowPrivateAddresses,
|
|
733
|
+
}),
|
|
734
|
+
)
|
|
665
735
|
},
|
|
666
736
|
}
|
|
667
737
|
},
|
|
@@ -818,6 +888,7 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
|
|
|
818
888
|
nodeId: schema.nodeId,
|
|
819
889
|
versionCleanup: config.versionCleanup,
|
|
820
890
|
auditRetentionDays: config.auditRetentionDays,
|
|
891
|
+
extensionActivityDays: config.extensionActivityDays,
|
|
821
892
|
mediaFiles,
|
|
822
893
|
// The workflow queue drains here rather than in the request: a submission is
|
|
823
894
|
// stored first, and an e-mail that cannot be sent yet must not cost it.
|
|
@@ -833,6 +904,8 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
|
|
|
833
904
|
resolveForm: (form) => cache.resolveForm(form),
|
|
834
905
|
operations: operations.documents,
|
|
835
906
|
bundleWorkflows: formTypes.workflows,
|
|
907
|
+
outbound: { allowPrivateAddresses: config.allowPrivateAddresses },
|
|
908
|
+
secretKey: config.secretKey,
|
|
836
909
|
renderEmail: (alias, props) => renderer.renderEmail(alias, props),
|
|
837
910
|
site: async () => ({
|
|
838
911
|
name: (await hooks.siteName?.()) || config.siteName,
|
|
@@ -854,6 +927,14 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
|
|
|
854
927
|
// Where jobs are left to a worker: whether one is running them (decision 4).
|
|
855
928
|
const workerWatch = createWorkerWatch({ db, config })
|
|
856
929
|
return {
|
|
930
|
+
/** What each extension does, recorded for the Activity view (story 327). */
|
|
931
|
+
activity,
|
|
932
|
+
/** Stops one extension's process on this node, as removing it does (story 328). */
|
|
933
|
+
async stopExtension(id: string) {
|
|
934
|
+
await Promise.all(
|
|
935
|
+
extensionProcesses.filter((process) => process.id === id).map((process) => process.stop()),
|
|
936
|
+
)
|
|
937
|
+
},
|
|
857
938
|
/** The server's own handler, which `api` calls through once the server is built (story 308). */
|
|
858
939
|
setBundleDispatch(dispatch: (request: Request) => Promise<Response>) {
|
|
859
940
|
bundleDispatch = dispatch
|
|
@@ -923,6 +1004,7 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
|
|
|
923
1004
|
await jobRunner.stop()
|
|
924
1005
|
await jobs.stop()
|
|
925
1006
|
await Promise.all(extensionProcesses.map((process) => process.stop()))
|
|
1007
|
+
await activity.stop()
|
|
926
1008
|
},
|
|
927
1009
|
/** The extensions that are granted but could not start, and why (story 311). */
|
|
928
1010
|
failedExtensions,
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The extension activity recorder (story 327): every place that already knows
|
|
3
|
+
* what an extension's call is records it here, and rows are written in
|
|
4
|
+
* batches, a second apart or two hundred at a time. Reads of one kind, for one
|
|
5
|
+
* person, in one minute, fold into one row. A crash loses at most a second of
|
|
6
|
+
* activity; the audit log still has every write the API made.
|
|
7
|
+
*/
|
|
8
|
+
import {
|
|
9
|
+
ACTIVITY_KINDS,
|
|
10
|
+
type ActivityFilter,
|
|
11
|
+
type ActivityInput,
|
|
12
|
+
type ActivityKind,
|
|
13
|
+
type ActivityOutcome,
|
|
14
|
+
type Db,
|
|
15
|
+
ExtensionActivityLog,
|
|
16
|
+
} from '@crombolo/data'
|
|
17
|
+
import type { BundleCaller } from './bundles.ts'
|
|
18
|
+
import { logger } from './logging.ts'
|
|
19
|
+
|
|
20
|
+
const log = logger('Activity')
|
|
21
|
+
|
|
22
|
+
/** Whom an extension acted for, as a row names them. */
|
|
23
|
+
export interface ActivityPerson {
|
|
24
|
+
personKey: string | null
|
|
25
|
+
personName: string | null
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** What one call was, as a recording point knows it. */
|
|
29
|
+
export interface ActivityEvent extends ActivityPerson {
|
|
30
|
+
extensionId: string
|
|
31
|
+
kind: ActivityKind
|
|
32
|
+
area: string | null
|
|
33
|
+
verb?: string | null
|
|
34
|
+
entityKey?: string | null
|
|
35
|
+
count?: number
|
|
36
|
+
outcome: ActivityOutcome
|
|
37
|
+
ms?: number | null
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface ActivityRecorder {
|
|
41
|
+
record(event: ActivityEvent): void
|
|
42
|
+
flush(): Promise<void>
|
|
43
|
+
stop(): Promise<void>
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The person a caller is: a back-office user, a member by name, or nobody. */
|
|
47
|
+
export function personOf(caller: BundleCaller | undefined): ActivityPerson {
|
|
48
|
+
if (caller?.kind === 'backoffice')
|
|
49
|
+
return { personKey: caller.principal.id, personName: caller.principal.name }
|
|
50
|
+
if (caller?.kind === 'member')
|
|
51
|
+
return { personKey: null, personName: `member ${caller.member.username}` }
|
|
52
|
+
return { personKey: null, personName: null }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Times a call and records it, whether it answers, throws, or answers a promise. */
|
|
56
|
+
export function timed<T>(
|
|
57
|
+
recorder: ActivityRecorder | undefined,
|
|
58
|
+
event: Omit<ActivityEvent, 'outcome' | 'ms'>,
|
|
59
|
+
call: () => T,
|
|
60
|
+
outcomeOf: (error: unknown) => ActivityOutcome = () => 'failed',
|
|
61
|
+
): T {
|
|
62
|
+
if (!recorder) return call()
|
|
63
|
+
const started = performance.now()
|
|
64
|
+
const done = (outcome: ActivityOutcome) =>
|
|
65
|
+
recorder.record({ ...event, outcome, ms: performance.now() - started })
|
|
66
|
+
try {
|
|
67
|
+
const result = call()
|
|
68
|
+
if (result instanceof Promise)
|
|
69
|
+
return result.then(
|
|
70
|
+
(value) => {
|
|
71
|
+
done('ok')
|
|
72
|
+
return value
|
|
73
|
+
},
|
|
74
|
+
(error: unknown) => {
|
|
75
|
+
done(outcomeOf(error))
|
|
76
|
+
throw error
|
|
77
|
+
},
|
|
78
|
+
) as T
|
|
79
|
+
done('ok')
|
|
80
|
+
return result
|
|
81
|
+
} catch (error) {
|
|
82
|
+
done(outcomeOf(error))
|
|
83
|
+
throw error
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function createActivityRecorder(
|
|
88
|
+
/** The database, or how to reach it once it is open: extensions start before it is. */
|
|
89
|
+
db: Db | (() => Db),
|
|
90
|
+
options: { flushMs?: number; batch?: number } = {},
|
|
91
|
+
): ActivityRecorder {
|
|
92
|
+
let opened: ExtensionActivityLog | undefined
|
|
93
|
+
const store = () => (opened ??= new ExtensionActivityLog(typeof db === 'function' ? db() : db))
|
|
94
|
+
const batch = options.batch ?? 200
|
|
95
|
+
let queued: ActivityInput[] = []
|
|
96
|
+
/** This minute's reads, by extension, person, area and verb. */
|
|
97
|
+
const reads = new Map<string, ActivityInput>()
|
|
98
|
+
let writing: Promise<void> = Promise.resolve()
|
|
99
|
+
|
|
100
|
+
const minute = (at: Date) => new Date(Math.floor(at.getTime() / 60_000) * 60_000)
|
|
101
|
+
|
|
102
|
+
const flush = async () => {
|
|
103
|
+
const rows = [...queued, ...reads.values()]
|
|
104
|
+
queued = []
|
|
105
|
+
reads.clear()
|
|
106
|
+
if (rows.length === 0) return writing
|
|
107
|
+
writing = writing
|
|
108
|
+
.then(() => store().record(rows))
|
|
109
|
+
.catch((error: unknown) => {
|
|
110
|
+
log.warning('Could not keep {count} rows of extension activity: {error}', {
|
|
111
|
+
count: rows.length,
|
|
112
|
+
error,
|
|
113
|
+
})
|
|
114
|
+
})
|
|
115
|
+
return writing
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const timer = setInterval(() => void flush(), options.flushMs ?? 1000)
|
|
119
|
+
;(timer as { unref?: () => void }).unref?.()
|
|
120
|
+
|
|
121
|
+
return {
|
|
122
|
+
record(event) {
|
|
123
|
+
const row: ActivityInput = {
|
|
124
|
+
extensionId: event.extensionId,
|
|
125
|
+
personKey: event.personKey,
|
|
126
|
+
personName: event.personName,
|
|
127
|
+
kind: event.kind,
|
|
128
|
+
area: event.area,
|
|
129
|
+
verb: event.verb ?? null,
|
|
130
|
+
entityKey: event.entityKey ?? null,
|
|
131
|
+
count: event.count ?? 1,
|
|
132
|
+
outcome: event.outcome,
|
|
133
|
+
ms: event.ms ?? null,
|
|
134
|
+
occurredAt: new Date(),
|
|
135
|
+
}
|
|
136
|
+
if (row.kind === 'read' && row.outcome === 'ok') {
|
|
137
|
+
const at = minute(row.occurredAt)
|
|
138
|
+
const key = [
|
|
139
|
+
row.extensionId,
|
|
140
|
+
row.personKey ?? '',
|
|
141
|
+
row.area ?? '',
|
|
142
|
+
row.verb ?? '',
|
|
143
|
+
at.getTime(),
|
|
144
|
+
].join('\u0000')
|
|
145
|
+
const held = reads.get(key)
|
|
146
|
+
if (held) {
|
|
147
|
+
held.count += row.count
|
|
148
|
+
held.ms = (held.ms ?? 0) + (row.ms ?? 0)
|
|
149
|
+
} else reads.set(key, { ...row, entityKey: null, occurredAt: at })
|
|
150
|
+
return
|
|
151
|
+
}
|
|
152
|
+
queued.push(row)
|
|
153
|
+
if (queued.length >= batch) void flush()
|
|
154
|
+
},
|
|
155
|
+
flush,
|
|
156
|
+
async stop() {
|
|
157
|
+
clearInterval(timer)
|
|
158
|
+
await flush()
|
|
159
|
+
},
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* A page of activity as the Activity view asks for it: `before` and `limit`
|
|
165
|
+
* (1–500, default 100), and the filters `kind`, `person`, `since` and `until`.
|
|
166
|
+
* Answers the reason when the query is not one.
|
|
167
|
+
*/
|
|
168
|
+
export function readActivityQuery(
|
|
169
|
+
search: URLSearchParams,
|
|
170
|
+
): { filter: ActivityFilter; cursor: { before?: number; limit: number } } | string {
|
|
171
|
+
const limit = Number(search.get('limit') ?? 100)
|
|
172
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 500)
|
|
173
|
+
return 'limit must be between 1 and 500.'
|
|
174
|
+
const raw = search.get('before')
|
|
175
|
+
const before = raw === null ? undefined : Number(raw)
|
|
176
|
+
if (before !== undefined && (!Number.isInteger(before) || before < 0))
|
|
177
|
+
return 'before must be an entry id.'
|
|
178
|
+
const kind = search.get('kind') ?? undefined
|
|
179
|
+
if (kind && !ACTIVITY_KINDS.includes(kind as ActivityKind)) return `There is no kind "${kind}".`
|
|
180
|
+
const date = (name: string) => {
|
|
181
|
+
const value = search.get(name)
|
|
182
|
+
if (!value) return undefined
|
|
183
|
+
const parsed = new Date(value)
|
|
184
|
+
return Number.isNaN(parsed.getTime()) ? null : parsed
|
|
185
|
+
}
|
|
186
|
+
const since = date('since')
|
|
187
|
+
const until = date('until')
|
|
188
|
+
if (since === null || until === null) return 'since and until must be dates.'
|
|
189
|
+
return {
|
|
190
|
+
filter: {
|
|
191
|
+
...(kind ? { kind: kind as ActivityKind } : {}),
|
|
192
|
+
...(search.get('person') ? { person: search.get('person') as string } : {}),
|
|
193
|
+
...(since ? { since } : {}),
|
|
194
|
+
...(until ? { until } : {}),
|
|
195
|
+
},
|
|
196
|
+
cursor: { ...(before !== undefined ? { before } : {}), limit },
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const csvCell = (value: unknown): string => {
|
|
201
|
+
const text = value === null || value === undefined ? '' : String(value)
|
|
202
|
+
// A cell a spreadsheet would read as a formula is kept as text.
|
|
203
|
+
const safe = /^[=+\-@\t\r]/.test(text) ? `'${text}` : text
|
|
204
|
+
return /[",\n]/.test(safe) ? `"${safe.replaceAll('"', '""')}"` : safe
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** All of an extension's activity the filter matches, as a CSV file, newest first. */
|
|
208
|
+
export async function activityCsv(
|
|
209
|
+
store: ExtensionActivityLog,
|
|
210
|
+
extensionId: string,
|
|
211
|
+
filter: ActivityFilter,
|
|
212
|
+
): Promise<string> {
|
|
213
|
+
const lines = ['when,person,kind,area,verb,item,count,outcome,ms']
|
|
214
|
+
let before: number | undefined
|
|
215
|
+
for (;;) {
|
|
216
|
+
const page = await store.page(extensionId, filter, { before, limit: 500 })
|
|
217
|
+
for (const row of page.items)
|
|
218
|
+
lines.push(
|
|
219
|
+
[
|
|
220
|
+
row.occurredAt.toISOString(),
|
|
221
|
+
row.personName ?? 'itself',
|
|
222
|
+
row.kind,
|
|
223
|
+
row.area,
|
|
224
|
+
row.verb,
|
|
225
|
+
row.entityKey,
|
|
226
|
+
row.count,
|
|
227
|
+
row.outcome,
|
|
228
|
+
row.ms,
|
|
229
|
+
]
|
|
230
|
+
.map(csvCell)
|
|
231
|
+
.join(','),
|
|
232
|
+
)
|
|
233
|
+
if (page.next === null) break
|
|
234
|
+
before = page.next
|
|
235
|
+
}
|
|
236
|
+
return `${lines.join('\n')}\n`
|
|
237
|
+
}
|