@crombolo/server 0.29.1 → 0.30.3

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/server",
3
- "version": "0.29.1",
3
+ "version": "0.30.3",
4
4
  "description": "The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -30,17 +30,17 @@
30
30
  "access": "public"
31
31
  },
32
32
  "dependencies": {
33
- "@crombolo/api-delivery": "0.29.1",
34
- "@crombolo/api-management": "0.29.1",
35
- "@crombolo/auth": "0.29.1",
36
- "@crombolo/backoffice-host": "0.29.1",
37
- "@crombolo/content": "0.29.1",
38
- "@crombolo/contracts": "0.29.1",
39
- "@crombolo/core": "0.29.1",
40
- "@crombolo/data": "0.29.1",
41
- "@crombolo/render": "0.29.1",
42
- "@crombolo/schema": "0.29.1",
43
- "@crombolo/transfer": "0.29.1",
33
+ "@crombolo/api-delivery": "0.30.3",
34
+ "@crombolo/api-management": "0.30.3",
35
+ "@crombolo/auth": "0.30.3",
36
+ "@crombolo/backoffice-host": "0.30.3",
37
+ "@crombolo/content": "0.30.3",
38
+ "@crombolo/contracts": "0.30.3",
39
+ "@crombolo/core": "0.30.3",
40
+ "@crombolo/data": "0.30.3",
41
+ "@crombolo/render": "0.30.3",
42
+ "@crombolo/schema": "0.30.3",
43
+ "@crombolo/transfer": "0.30.3",
44
44
  "@logtape/logtape": "^2.3.8",
45
45
  "jose": "^6.2.12"
46
46
  }
package/src/config.ts CHANGED
@@ -829,7 +829,7 @@ export function describeDatabase(
829
829
  }
830
830
  }
831
831
 
832
- export const VERSION = '0.29.1'
832
+ export const VERSION = '0.30.3'
833
833
 
834
834
  /** A whole number of seconds from the environment; undefined when unset or not one. */
835
835
  function numberSetting(name: Parameters<typeof setting>[0]): number | undefined {
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The content query endpoint (story 183): who is asking becomes the query's
3
+ * scope. Start nodes narrow the statement, Browse is checked per page only when
4
+ * some group could withhold it, and a property the user cannot read may not be
5
+ * filtered or sorted on.
6
+ */
7
+ import type { Principal } from '@crombolo/api-management'
8
+ import {
9
+ DocumentPermissions,
10
+ type GroupGrant,
11
+ permissionsForPath,
12
+ propertyValuePermissions,
13
+ ROOT_ACCESS,
14
+ } from '@crombolo/core'
15
+ import {
16
+ ContentQueryRefused,
17
+ type Db,
18
+ parseContentQuery,
19
+ type QueryScope,
20
+ queryDocuments,
21
+ } from '@crombolo/data'
22
+
23
+ /** Whether every group the user is in can browse every page. */
24
+ const browsesEverything = (groups: readonly GroupGrant[]) =>
25
+ groups.some(
26
+ (group) =>
27
+ group.defaults.includes(DocumentPermissions.Read) &&
28
+ [...group.granular.values()].every((verbs) => verbs.includes(DocumentPermissions.Read)),
29
+ )
30
+
31
+ /** The scope a signed-in back-office user queries within. */
32
+ export function contentQueryScope(principal: Principal): QueryScope {
33
+ const groups = principal.groups
34
+ return {
35
+ start: principal.startNodes.document,
36
+ browses:
37
+ principal.isAdmin || browsesEverything(groups)
38
+ ? undefined
39
+ : (chain) => permissionsForPath(groups, chain).has(DocumentPermissions.Read),
40
+ readsProperty: (key) =>
41
+ principal.isAdmin ||
42
+ propertyValuePermissions(groups, key).has(DocumentPermissions.PropertyValueRead),
43
+ }
44
+ }
45
+
46
+ /** Everything, for an operator at the command line on the site's own database. */
47
+ export const OPERATOR_SCOPE: QueryScope = { start: ROOT_ACCESS, readsProperty: () => true }
48
+
49
+ /** A 400 the back office and the remote protocol both read: a title, and every problem. */
50
+ const badQuery = (problems: string[]) =>
51
+ Response.json(
52
+ { code: 'bad-query', title: problems[0] ?? 'The query cannot be run.', problems },
53
+ { status: 400 },
54
+ )
55
+
56
+ /** A request body to a response: 400 with each problem named, else the matches. */
57
+ export async function answerContentQuery(
58
+ db: Db,
59
+ scope: QueryScope,
60
+ body: unknown,
61
+ ): Promise<Response> {
62
+ const parsed = parseContentQuery(body)
63
+ if (!parsed.ok) return badQuery(parsed.problems)
64
+ try {
65
+ return Response.json(await queryDocuments(db, parsed.query, scope))
66
+ } catch (error) {
67
+ if (error instanceof ContentQueryRefused) return badQuery([error.message])
68
+ throw error
69
+ }
70
+ }
package/src/index.ts CHANGED
@@ -31,6 +31,7 @@ export * from './content-dispatch.ts'
31
31
  export * from './content-events.ts'
32
32
  export * from './content-notifications.ts'
33
33
  export * from './content-operations.ts'
34
+ export * from './content-query.ts'
34
35
  export * from './content-type-udt.ts'
35
36
  export * from './database.ts'
36
37
  export * from './diagnostics.ts'
package/src/jobs.ts CHANGED
@@ -107,7 +107,11 @@ export interface BackgroundJobs {
107
107
  /** Runs whether or not the hourly job is enabled; the policy decides what goes. */
108
108
  runVersionCleanup(now?: Date): Promise<{ nodes: number; versionsDeleted: number }>
109
109
  start(): void
110
- stop(): void
110
+ /**
111
+ * Disarms the timers, then waits for a run already going to finish, so a
112
+ * server closing next never takes the database from under it.
113
+ */
114
+ stop(): Promise<void>
111
115
  /** Whether the timers are armed; false on a node whose role is not to run them. */
112
116
  started(): boolean
113
117
  }
@@ -121,6 +125,13 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
121
125
  const search = new SearchIndex(options.db)
122
126
  let indexing: Promise<number> | undefined
123
127
  let kicked: ReturnType<typeof setTimeout> | undefined
128
+ /** Runs the timers started and have not finished, for `stop` to wait on. */
129
+ const inFlight = new Set<Promise<unknown>>()
130
+ const tracked = <T>(run: Promise<T>): Promise<T> => {
131
+ inFlight.add(run)
132
+ void run.finally(() => inFlight.delete(run)).catch(() => {})
133
+ return run
134
+ }
124
135
 
125
136
  async function runScheduledPublishing(now = new Date()): Promise<ScheduledRun> {
126
137
  const run: ScheduledRun = { published: [], unpublished: [], failed: [] }
@@ -233,7 +244,7 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
233
244
  }
234
245
 
235
246
  const indexQuietly = () =>
236
- runSearchIndexing().catch((error: unknown) => {
247
+ tracked(runSearchIndexing()).catch((error: unknown) => {
237
248
  logger('jobs').error('Search indexing failed', { error })
238
249
  })
239
250
 
@@ -245,7 +256,7 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
245
256
  if (running) return
246
257
  running = true
247
258
  try {
248
- await job()
259
+ await tracked(job())
249
260
  } catch (error) {
250
261
  logger('jobs').error('A background job failed', { error })
251
262
  } finally {
@@ -304,10 +315,11 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
304
315
  const files = options.mediaFiles
305
316
  if (files) every(60 * 60_000, () => files.cleanupExpired())
306
317
  },
307
- stop() {
318
+ async stop() {
308
319
  for (const timer of timers.splice(0)) clearInterval(timer)
309
320
  if (kicked) clearTimeout(kicked)
310
321
  kicked = undefined
322
+ await Promise.allSettled([...inFlight])
311
323
  },
312
324
  started() {
313
325
  return timers.length > 0
package/src/remote.ts CHANGED
@@ -23,6 +23,7 @@ import type { ContentSet } from '@crombolo/transfer'
23
23
  import { readAuditPageQuery, recordAudit } from './adapters/audit.ts'
24
24
  import { installBundleContent } from './bundle-install.ts'
25
25
  import type { CromboloConfig } from './config.ts'
26
+ import { answerContentQuery, contentQueryScope } from './content-query.ts'
26
27
  import { mediaStoreFor } from './media-files.ts'
27
28
  import { type MediaStore, streamOf } from './media-store.ts'
28
29
  import { openSecret, sealSecret, usableSecretKey } from './secrets.ts'
@@ -138,6 +139,7 @@ export function createRemote(options: RemoteOptions): Remote {
138
139
  'media-fetch',
139
140
  'push-check',
140
141
  'audit',
142
+ 'content-query',
141
143
  ...(settings.approvals ? ['approvals'] : []),
142
144
  ],
143
145
  environments: [environment()],
@@ -776,6 +778,16 @@ export function createRemote(options: RemoteOptions): Remote {
776
778
  })
777
779
 
778
780
  if (what === 'audit' && request.method === 'GET') return readAudit(url, principal)
781
+ // Finding pages by their facts (story 183), as the signed-in user, as in the back office.
782
+ if (what === 'content/query' && request.method === 'POST') {
783
+ if (!hasSection(principal, 'content'))
784
+ return problem(403, { code: 'forbidden', title: 'You may not search content here' })
785
+ return answerContentQuery(
786
+ db,
787
+ contentQueryScope(principal),
788
+ await request.json().catch(() => undefined),
789
+ )
790
+ }
779
791
  if (what === 'pulls' && request.method === 'POST') return startPull(request, url, principal)
780
792
  if (what === 'pushes' && request.method === 'PUT') return startPush(request, url, principal)
781
793
  if (what === 'pushes/check' && request.method === 'POST') {
package/src/server.ts CHANGED
@@ -137,6 +137,7 @@ import {
137
137
  import { createContentDispatcher } from './content-dispatch.ts'
138
138
  import { createContentEventSink } from './content-events.ts'
139
139
  import { createContentNotificationRunner, createContentNotifier } from './content-notifications.ts'
140
+ import { answerContentQuery, contentQueryScope } from './content-query.ts'
140
141
  import { attachDatabase, bootstrapDatabase } from './database.ts'
141
142
  import { createDeliveryMemberSecurity } from './delivery-members.ts'
142
143
  import { createDiagnostics } from './diagnostics.ts'
@@ -1171,6 +1172,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1171
1172
  // credentials anywhere near it.
1172
1173
  const auditPath = `${paths.pluginPath}/api/audit`
1173
1174
  const hostTokenPath = `${paths.pluginPath}/api/host-token`
1175
+ const contentQueryPath = `${paths.pluginPath}/api/content-query`
1174
1176
  /** Per node: ten a minute for each person, three hundred in all. */
1175
1177
  const hostTokens = new AttemptLimiter({ max: 10, maxAll: 300, windowMs: 60_000 })
1176
1178
  const auditHost = createAuditHost(db, config.auditRetentionDays)
@@ -1304,6 +1306,8 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1304
1306
  if (!pathname.startsWith(prefix)) return
1305
1307
  // A host token changes nothing here: each one is a log line, not an entry.
1306
1308
  if (pathname === hostTokenPath) return
1309
+ // A content query is a POST that reads.
1310
+ if (pathname === contentQueryPath) return
1307
1311
  const principal = await authenticate(request)
1308
1312
  if (!principal) return
1309
1313
  const plan = pluginAuditPlan(request.method, pathname.slice(prefix.length))
@@ -1850,6 +1854,16 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1850
1854
  }
1851
1855
 
1852
1856
  // Non-contract, Settings: how page addresses are built (story 110).
1857
+ // Non-contract: finding pages by their facts (story 183), as the signed-in user.
1858
+ if (pathname === contentQueryPath) {
1859
+ const principal = await authenticate(request)
1860
+ if (!principal) return new Response('Unauthorized', { status: 401 })
1861
+ if (!hasSection(principal, 'content')) return new Response('Forbidden', { status: 403 })
1862
+ if (request.method !== 'POST') return new Response('Method Not Allowed', { status: 405 })
1863
+ const body = await request.json().catch(() => undefined)
1864
+ return answerContentQuery(db, contentQueryScope(principal), body)
1865
+ }
1866
+
1853
1867
  if (pathname === `${paths.pluginPath}/api/url-options`) {
1854
1868
  const principal = await authenticate(request)
1855
1869
  if (!principal) return new Response('Unauthorized', { status: 401 })
@@ -2215,6 +2229,8 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2215
2229
  return renderer.renderModel(draft.content, draft.culture, {
2216
2230
  ...(await pageRequest(request)),
2217
2231
  search: siteSearchFor(db, cache, undefined),
2232
+ // Blocks with no component say so here, and only here (story 184).
2233
+ preview: true,
2218
2234
  })
2219
2235
  }
2220
2236
 
@@ -2546,7 +2562,9 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
2546
2562
  },
2547
2563
  async close() {
2548
2564
  diagnostics.stop()
2549
- jobs.stop()
2565
+ // A run already going finishes first: closing the database under a job
2566
+ // left its locks behind for whatever used the database next.
2567
+ await jobs.stop()
2550
2568
  // A dispatch a commit started finishes before the connection goes.
2551
2569
  await dispatcher.settled().catch(() => {})
2552
2570
  events.stop()