@crombolo/server 0.36.2 → 0.38.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.
Files changed (83) hide show
  1. package/package.json +15 -13
  2. package/src/access.ts +29 -27
  3. package/src/adapters/audit.ts +1 -1
  4. package/src/adapters/blueprints.ts +22 -13
  5. package/src/adapters/content.ts +1 -1
  6. package/src/adapters/dictionary.ts +1 -1
  7. package/src/adapters/documents.ts +17 -10
  8. package/src/adapters/elements.ts +47 -37
  9. package/src/adapters/file-system.ts +1 -1
  10. package/src/adapters/health.ts +33 -5
  11. package/src/adapters/media.ts +12 -8
  12. package/src/adapters/member-groups.ts +8 -6
  13. package/src/adapters/members.ts +6 -4
  14. package/src/adapters/public-access.ts +7 -5
  15. package/src/adapters/redirects.ts +1 -1
  16. package/src/adapters/references.ts +1 -1
  17. package/src/adapters/relations.ts +1 -1
  18. package/src/adapters/schema-files.ts +33 -1
  19. package/src/adapters/search-index.ts +1 -1
  20. package/src/adapters/template-files.ts +6 -1
  21. package/src/adapters/template-query.ts +1 -1
  22. package/src/adapters/users.ts +13 -13
  23. package/src/adapters/webhooks.ts +1 -1
  24. package/src/anonymise-rules.ts +83 -0
  25. package/src/approvals-api.ts +1 -1
  26. package/src/approvals.ts +75 -38
  27. package/src/back-office-url.ts +20 -0
  28. package/src/backup.ts +26 -2
  29. package/src/bundle-code.ts +1 -1
  30. package/src/bundle-grants.ts +265 -0
  31. package/src/bundle-install.ts +13 -2
  32. package/src/bundle-media.ts +12 -11
  33. package/src/bundles.ts +258 -444
  34. package/src/component-snippets.ts +1 -1
  35. package/src/components.ts +48 -7
  36. package/src/config.ts +141 -4
  37. package/src/content-notifications.ts +13 -9
  38. package/src/content-operations.ts +23 -65
  39. package/src/content-query.ts +1 -1
  40. package/src/core.ts +663 -0
  41. package/src/cron.ts +139 -0
  42. package/src/custom-tables.ts +274 -0
  43. package/src/database.ts +22 -14
  44. package/src/dictionary-transfer.ts +1 -1
  45. package/src/git-routes.ts +1 -1
  46. package/src/identity-provider-overrides.ts +18 -16
  47. package/src/imaging.ts +65 -15
  48. package/src/index.ts +14 -1
  49. package/src/islands.ts +197 -0
  50. package/src/job-wake.ts +23 -0
  51. package/src/live-reload.ts +195 -0
  52. package/src/log-viewer.ts +6 -1
  53. package/src/marketplace.ts +82 -10
  54. package/src/media-access.ts +12 -9
  55. package/src/member-auth.ts +6 -4
  56. package/src/middleware.ts +236 -0
  57. package/src/models-builder.ts +1 -1
  58. package/src/node-operations.ts +122 -0
  59. package/src/owner-jobs.ts +428 -0
  60. package/src/ports.ts +39 -154
  61. package/src/preview-tokens.ts +6 -12
  62. package/src/remote.ts +3 -1
  63. package/src/routes.ts +420 -0
  64. package/src/schema.ts +8 -3
  65. package/src/seed/compile.ts +7 -5
  66. package/src/seed/export.ts +6 -4
  67. package/src/seo.ts +2 -2
  68. package/src/server.ts +866 -483
  69. package/src/settings.ts +49 -2
  70. package/src/site-data.ts +195 -0
  71. package/src/site-file.ts +30 -4
  72. package/src/site-queries.ts +140 -0
  73. package/src/site-replace.ts +25 -19
  74. package/src/site-sections.ts +1 -1
  75. package/src/site-services.ts +116 -0
  76. package/src/status-pages.ts +142 -0
  77. package/src/status.ts +11 -9
  78. package/src/url-settings.ts +1 -2
  79. package/src/webhook-files.ts +18 -1
  80. package/src/webhooks.ts +83 -15
  81. package/src/worker-watch.ts +73 -0
  82. package/src/worker.ts +138 -0
  83. package/src/bundle-tables.ts +0 -161
@@ -0,0 +1,265 @@
1
+ /**
2
+ * Bundles ask for permissions (story 222). A bundle's package declares what it
3
+ * may do with the site; an administrator grants the whole list, or the bundle
4
+ * stays off. Each capability serves only the permissions declared for it, and
5
+ * a bundle is on only while its grant covers everything it declares.
6
+ * docs/bundles.md, "Permissions".
7
+ */
8
+ import {
9
+ type BundlePackage,
10
+ type BundlePermission,
11
+ describePermissions,
12
+ discoverBundles,
13
+ } from '@crombolo/backoffice-host/registry'
14
+ import { type BundleGrant, BundleGrantRepository, type Db } from '@crombolo/data'
15
+
16
+ /** The permissions each capability serves; `log` needs none. */
17
+ export const CAPABILITY_PERMISSIONS: Record<string, readonly BundlePermission[]> = {
18
+ redirects: ['redirects.read', 'redirects.write'],
19
+ documents: ['documents.read'],
20
+ identityProviders: ['identityProviders.read', 'identityProviders.write'],
21
+ media: ['media.read', 'media.write', 'member.delegate'],
22
+ log: [],
23
+ }
24
+
25
+ /** The permission each capability method needs. */
26
+ const METHOD_PERMISSIONS: Record<string, Record<string, BundlePermission>> = {
27
+ redirects: {
28
+ list: 'redirects.read',
29
+ byKey: 'redirects.read',
30
+ save: 'redirects.write',
31
+ replace: 'redirects.write',
32
+ remove: 'redirects.write',
33
+ },
34
+ documents: { url: 'documents.read' },
35
+ identityProviders: {
36
+ list: 'identityProviders.read',
37
+ test: 'identityProviders.read',
38
+ groups: 'identityProviders.read',
39
+ update: 'identityProviders.write',
40
+ reset: 'identityProviders.write',
41
+ },
42
+ media: {
43
+ get: 'media.read',
44
+ list: 'media.read',
45
+ crop: 'media.read',
46
+ create: 'media.write',
47
+ update: 'media.write',
48
+ delete: 'media.write',
49
+ },
50
+ }
51
+
52
+ /** The permissions a package declares. */
53
+ export const declaredPermissions = (pkg: BundlePackage | undefined): string[] =>
54
+ Array.isArray(pkg?.field.permissions) ? [...(pkg?.field.permissions ?? [])] : []
55
+
56
+ /**
57
+ * Why a bundle's capabilities and its declared permissions disagree: a
58
+ * capability with none of its permissions, `media` without `member.delegate`
59
+ * (it always acts as the calling member), or a permission no capability uses.
60
+ */
61
+ export function permissionProblems(
62
+ label: string,
63
+ capabilities: readonly string[],
64
+ declared: readonly string[],
65
+ ): string[] {
66
+ const problems: string[] = []
67
+ const has = new Set(declared)
68
+ for (const capability of capabilities) {
69
+ const serves = CAPABILITY_PERMISSIONS[capability]
70
+ if (!serves || serves.length === 0) continue
71
+ const writes = serves.filter((p) => p !== 'member.delegate')
72
+ if (!writes.some((p) => has.has(p)))
73
+ problems.push(
74
+ `Bundle "${label}" uses "${capability}" but declares none of its permissions (${writes.join(', ')}) in "crombolo.permissions".`,
75
+ )
76
+ if (capability === 'media' && !has.has('member.delegate'))
77
+ problems.push(
78
+ `Bundle "${label}" uses "media", which acts as the calling member, and so needs "member.delegate" in "crombolo.permissions".`,
79
+ )
80
+ }
81
+ for (const permission of declared) {
82
+ const used = capabilities.some((c) => CAPABILITY_PERMISSIONS[c]?.includes(permission as never))
83
+ if (!used)
84
+ problems.push(
85
+ `Bundle "${label}" declares "${permission}", which none of its capabilities uses; take it out of "crombolo.permissions".`,
86
+ )
87
+ }
88
+ return problems
89
+ }
90
+
91
+ /** A capability call the bundle was not given the permission for. */
92
+ export class PermissionRefusedError extends Error {
93
+ constructor(
94
+ readonly bundle: string,
95
+ readonly permission: string,
96
+ ) {
97
+ super(`Bundle "${bundle}" may not do this: it does not declare "${permission}".`)
98
+ }
99
+ }
100
+
101
+ /**
102
+ * A capability with only the methods its declared permissions allow: the rest
103
+ * throw `PermissionRefusedError`, naming the permission.
104
+ */
105
+ export function gated<T extends object>(
106
+ bundle: string,
107
+ capability: string,
108
+ host: T,
109
+ declared: readonly string[],
110
+ ): T {
111
+ const methods = METHOD_PERMISSIONS[capability]
112
+ if (!methods) return host
113
+ const has = new Set(declared)
114
+ const out: Record<string, unknown> = {}
115
+ for (const [name, value] of Object.entries(host)) {
116
+ const needs = methods[name]
117
+ out[name] =
118
+ typeof value === 'function' && needs && !has.has(needs)
119
+ ? () => {
120
+ throw new PermissionRefusedError(bundle, needs)
121
+ }
122
+ : typeof value === 'function'
123
+ ? (value as (...args: unknown[]) => unknown).bind(host)
124
+ : value
125
+ }
126
+ return Object.freeze(out) as T
127
+ }
128
+
129
+ /** Where a bundle stands: on, or waiting for an administrator, and for what. */
130
+ export interface BundleGrantState {
131
+ bundleId: string
132
+ packageName: string
133
+ version: string
134
+ declared: { permission: string; allows: string }[]
135
+ /** On: nothing is declared, or the grant covers everything that is. */
136
+ on: boolean
137
+ grant: BundleGrant | undefined
138
+ /** What is declared and not granted. */
139
+ missing: string[]
140
+ }
141
+
142
+ /** What `on` answers for a bundle, and how grants are made and withdrawn. */
143
+ export interface BundleGrants {
144
+ /** Reads the grants again, as a grant on another node may have changed them. */
145
+ refresh(): Promise<void>
146
+ isOn(bundleId: string): boolean
147
+ state(pkg: BundlePackage): BundleGrantState
148
+ grant(pkg: BundlePackage, by: string | null): Promise<BundleGrantState>
149
+ withdraw(bundleId: string): Promise<boolean>
150
+ }
151
+
152
+ /** A bundle is on when its grant covers everything its package declares. */
153
+ export function grantCovers(declared: readonly string[], grant: BundleGrant | undefined): boolean {
154
+ if (declared.length === 0) return true
155
+ if (!grant) return false
156
+ const granted = new Set(grant.permissions)
157
+ return declared.every((permission) => granted.has(permission))
158
+ }
159
+
160
+ /**
161
+ * Grants as this node sees them: read at boot, read again at most every
162
+ * `refreshMs` (a grant or a withdrawal on another node), and at once after a
163
+ * grant made here.
164
+ */
165
+ export function createBundleGrants(options: {
166
+ db: Db
167
+ /** The wired bundles' packages, by bundle id. */
168
+ packages: () => ReadonlyMap<string, BundlePackage>
169
+ refreshMs?: number
170
+ }): BundleGrants {
171
+ const repository = new BundleGrantRepository(options.db)
172
+ let grants = new Map<string, BundleGrant>()
173
+ let readAt = 0
174
+ const refreshMs = options.refreshMs ?? 5_000
175
+
176
+ const read = async () => {
177
+ grants = new Map((await repository.all()).map((grant) => [grant.bundleId, grant]))
178
+ readAt = Date.now()
179
+ }
180
+ const stale = () => {
181
+ if (Date.now() - readAt > refreshMs) void read().catch(() => {})
182
+ }
183
+ const stateOf = (pkg: BundlePackage): BundleGrantState => {
184
+ const declared = declaredPermissions(pkg)
185
+ const grant = grants.get(pkg.id)
186
+ const granted = new Set(grant?.permissions ?? [])
187
+ return {
188
+ bundleId: pkg.id,
189
+ packageName: pkg.packageName,
190
+ version: pkg.version,
191
+ declared: describePermissions(declared),
192
+ on: grantCovers(declared, grant),
193
+ grant,
194
+ missing: declared.filter((permission) => !granted.has(permission)),
195
+ }
196
+ }
197
+
198
+ return {
199
+ refresh: read,
200
+ isOn(bundleId) {
201
+ stale()
202
+ const pkg = options.packages().get(bundleId)
203
+ return pkg ? grantCovers(declaredPermissions(pkg), grants.get(bundleId)) : false
204
+ },
205
+ state(pkg) {
206
+ stale()
207
+ return stateOf(pkg)
208
+ },
209
+ async grant(pkg, by) {
210
+ await repository.grant({
211
+ bundleId: pkg.id,
212
+ packageName: pkg.packageName,
213
+ version: pkg.version,
214
+ permissions: declaredPermissions(pkg),
215
+ grantedBy: by,
216
+ })
217
+ await read()
218
+ return stateOf(pkg)
219
+ },
220
+ async withdraw(bundleId) {
221
+ const had = await repository.withdraw(bundleId)
222
+ await read()
223
+ return had
224
+ },
225
+ }
226
+ }
227
+
228
+ /** What a route of a bundle that is off answers. */
229
+ export function waitingResponse(bundleId: string): Response {
230
+ return Response.json(
231
+ {
232
+ title: 'Not turned on yet',
233
+ detail: `The bundle "${bundleId}" is waiting for an administrator to approve what it may do with the site, in Packages → Installed.`,
234
+ status: 503,
235
+ },
236
+ { status: 503, headers: { 'content-type': 'application/problem+json', 'retry-after': '60' } },
237
+ )
238
+ }
239
+
240
+ /** The bundle a site depends on, by id, when it has a server half to grant. */
241
+ export function grantableBundle(siteDir: string, id: string): BundlePackage | string {
242
+ const pkg = discoverBundles(siteDir).bundles.find((candidate) => candidate.id === id)
243
+ if (!pkg)
244
+ return `No package this site depends on declares the bundle "${id}". Add it to package.json first.`
245
+ if (!pkg.carries.server)
246
+ return `The bundle "${id}" has no server half, so there is nothing to grant.`
247
+ return pkg
248
+ }
249
+
250
+ /** Grants a bundle the whole of what it declares, outside a running server. */
251
+ export async function grantBundle(
252
+ db: Db,
253
+ pkg: BundlePackage,
254
+ by: string | null,
255
+ ): Promise<string[]> {
256
+ const permissions = declaredPermissions(pkg)
257
+ await new BundleGrantRepository(db).grant({
258
+ bundleId: pkg.id,
259
+ packageName: pkg.packageName,
260
+ version: pkg.version,
261
+ permissions,
262
+ grantedBy: by,
263
+ })
264
+ return permissions
265
+ }
@@ -22,7 +22,7 @@ import {
22
22
  peerRangeProblem,
23
23
  readBundlePackage,
24
24
  readPackageJson,
25
- } from '@crombolo/backoffice-host'
25
+ } from '@crombolo/backoffice-host/registry'
26
26
  import { ObjectTypes } from '@crombolo/core'
27
27
  import {
28
28
  answersByNode,
@@ -84,6 +84,7 @@ import { syncDomainsFile } from './domains.ts'
84
84
  import { mediaStoreFor, placeBlobs } from './media-files.ts'
85
85
  import { componentAliasesIn, syncSchemaDirectory } from './schema.ts'
86
86
  import { publishSchema } from './schema-store.ts'
87
+ import { applySiteData, type SiteDataApplied } from './site-data.ts'
87
88
  import {
88
89
  carriesAdministrator,
89
90
  prunePeople,
@@ -204,6 +205,7 @@ export function readBundle(
204
205
  let opened: ReturnType<typeof openBundle> = {
205
206
  set: loaded.set,
206
207
  people: undefined,
208
+ siteData: undefined,
207
209
  openBlob: (_key, bytes) => bytes,
208
210
  }
209
211
  const peopleOnly = options.withoutPeople && loaded.set.manifest.content !== 'sealed'
@@ -432,6 +434,8 @@ export interface ContentImportResult {
432
434
  published: number
433
435
  publishFailures: { key: string; reason: string }[]
434
436
  problems: string[]
437
+ /** What the file's site data did here, when it carried any (story 189). */
438
+ siteData?: SiteDataApplied
435
439
  }
436
440
 
437
441
  /**
@@ -697,6 +701,9 @@ export async function installBundleContent(
697
701
  await publishSchema(config.schemaStore, config.schemaDir)
698
702
  }
699
703
  const kept = promoteStaged(config, runDir, runId)
704
+ // On the owners' own connections, so after crombolo's transaction rather than
705
+ // in it: each owner is replaced in a transaction of its own.
706
+ const siteData = set.siteData ? await applySiteData(db, config, set.siteData) : undefined
700
707
  // Domains belong to where the site runs, never to the file: rebound by the
701
708
  // site's own `domains.toml` onto the pages now in its tree.
702
709
  if (replace) await syncDomainsFile(db, config.siteDir)
@@ -717,7 +724,11 @@ export async function installBundleContent(
717
724
  blobs: placed,
718
725
  published: result.published.length,
719
726
  publishFailures: result.publishFailures,
720
- problems: prepared.problems,
727
+ problems: [
728
+ ...prepared.problems,
729
+ ...(siteData?.failed ?? []).map((failure) => `site data not written for ${failure}`),
730
+ ],
731
+ ...(siteData ? { siteData } : {}),
721
732
  sections: staged
722
733
  ? {
723
734
  written: staged.written,
@@ -15,7 +15,7 @@
15
15
  * list, and its size, counted as it is read. An image is turned upright and
16
16
  * stored without its metadata, and what that metadata said is returned.
17
17
  */
18
- import { hasSection } from '@crombolo/api-management'
18
+ import { hasSection } from '@crombolo/api-management/domain'
19
19
  import { type MediaActor, type MediaOperations, memberActor, userActor } from '@crombolo/content'
20
20
  import {
21
21
  checkMemberUpload,
@@ -314,20 +314,21 @@ export function createBundleMedia(deps: BundleMediaDeps) {
314
314
  return { at, missing: [] as string[] }
315
315
  }
316
316
  const childFolder = async (parentId: number, name: string) => {
317
- const rows = await db.query<{ id: number; unique_id: string; path: string; text: string }>(
318
- 'SELECT id, unique_id, path, text FROM node WHERE parent_id = ? AND node_object_type = ? AND trashed = ? AND LOWER(text) = ?',
319
- [parentId, ObjectTypes.Media, db.dialect.boolValue(false), lower(name)],
320
- )
317
+ const siblings = () =>
318
+ db.q
319
+ .selectFrom('node')
320
+ .select(['id', 'unique_id', 'path', 'text'])
321
+ .where('parent_id', '=', parentId)
322
+ .where('node_object_type', '=', ObjectTypes.Media)
323
+ .where('trashed', '=', db.dialect.boolValue(false) as boolean)
324
+ const rows = await siblings()
325
+ .where((eb) => eb(eb.fn('lower', ['text']), '=', lower(name)))
326
+ .execute()
321
327
  const row =
322
328
  rows[0] ??
323
329
  // SQLite lowers only ASCII.
324
330
  (/[^ -~]/.test(name)
325
- ? (
326
- await db.query<{ id: number; unique_id: string; path: string; text: string }>(
327
- 'SELECT id, unique_id, path, text FROM node WHERE parent_id = ? AND node_object_type = ? AND trashed = ?',
328
- [parentId, ObjectTypes.Media, db.dialect.boolValue(false)],
329
- )
330
- ).find((r) => lower(String(r.text)) === lower(name))
331
+ ? (await siblings().execute()).find((r) => lower(String(r.text)) === lower(name))
331
332
  : undefined)
332
333
  return row
333
334
  ? { id: Number(row.id), key: normaliseUuid(String(row.unique_id)), path: String(row.path) }