@crombolo/server 0.65.1 → 0.66.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,10 +11,17 @@ import {
11
11
  dateFromText,
12
12
  isBlockValue,
13
13
  normaliseUuid,
14
+ ObjectTypes,
14
15
  readBlocks,
15
16
  SINGLE_BLOCK_EDITOR_ALIAS,
16
17
  } from '@crombolo/core'
17
- import { ContentTypeRepository, DataTypeRepository, type Db, looksLikeKey } from '@crombolo/data'
18
+ import {
19
+ ContentTypeRepository,
20
+ DataTypeRepository,
21
+ type Db,
22
+ looksLikeKey,
23
+ resolveNodeRef,
24
+ } from '@crombolo/data'
18
25
  import { blockKey, pickKey } from './keys.ts'
19
26
 
20
27
  const isRecord = (value: unknown): value is Record<string, unknown> =>
@@ -33,27 +40,30 @@ export interface PropertyEditor {
33
40
  config: Record<string, unknown>
34
41
  }
35
42
 
43
+ type TypeKind = 'document' | 'media' | 'member'
44
+
36
45
  /** The site's types and their properties' editors, looked up once each. */
37
46
  export function schemaLookup(db: Db) {
38
47
  const repos = {
39
48
  document: new ContentTypeRepository(db),
40
49
  media: new ContentTypeRepository(db, { kind: 'media' }),
50
+ member: new ContentTypeRepository(db, { kind: 'member' }),
41
51
  }
42
52
  const dataTypes = new DataTypeRepository(db)
43
53
  const types = new Map<string, ContentTypeAggregate | undefined>()
44
54
  const editors = new Map<string, Map<string, PropertyEditor>>()
45
55
  return {
46
56
  repos,
47
- async typeOf(kind: 'document' | 'media', alias: string) {
57
+ async typeOf(kind: TypeKind, alias: string) {
48
58
  const key = `${kind}:${alias.toLowerCase()}`
49
59
  if (!types.has(key)) types.set(key, await repos[kind].byAlias(alias))
50
60
  return types.get(key)
51
61
  },
52
- async typeByKey(kind: 'document' | 'media', typeKey: string) {
62
+ async typeByKey(kind: TypeKind, typeKey: string) {
53
63
  return repos[kind].byKey(normaliseUuid(typeKey))
54
64
  },
55
65
  async editorsOf(
56
- kind: 'document' | 'media',
66
+ kind: TypeKind,
57
67
  type: Pick<ContentTypeAggregate, 'key'>,
58
68
  ): Promise<Map<string, PropertyEditor>> {
59
69
  const cached = editors.get(type.key)
@@ -91,6 +101,74 @@ export interface ValueRefs {
91
101
  linkedMedia(ref: string): Promise<string | undefined>
92
102
  }
93
103
 
104
+ const OBJECT_TYPES = {
105
+ content: ObjectTypes.Document,
106
+ library: ObjectTypes.Element,
107
+ media: ObjectTypes.Media,
108
+ } as const
109
+
110
+ /** What a value's paths name, in this site's database. */
111
+ export function siteValueRefs(db: Db): ValueRefs {
112
+ const keyOf = async (ref: string, kind: keyof typeof OBJECT_TYPES) => {
113
+ const resolved = await resolveNodeRef(db, [OBJECT_TYPES[kind]], ref)
114
+ return resolved.ok && resolved.node.objectType === OBJECT_TYPES[kind]
115
+ ? resolved.node.key
116
+ : undefined
117
+ }
118
+ return {
119
+ content: (ref) => keyOf(ref, 'content'),
120
+ library: (ref) => keyOf(ref, 'library'),
121
+ // A Library form by its path or key; anything else is a form's own alias, as before.
122
+ async form(ref) {
123
+ if (looksLikeKey(ref)) return normaliseUuid(ref)
124
+ const key = await keyOf(ref, 'library')
125
+ if (!key) return ref
126
+ const rows = await db.q
127
+ .selectFrom('node as n')
128
+ .innerJoin('content as c', 'c.node_id', 'n.id')
129
+ .innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
130
+ .select('ct.form_key')
131
+ .where('n.unique_id', '=', key)
132
+ .execute()
133
+ return rows[0]?.form_key ? key : undefined
134
+ },
135
+ linkedMedia: (ref) => keyOf(ref, 'media'),
136
+ async media(ref) {
137
+ const key = await keyOf(ref, 'media')
138
+ if (!key) return undefined
139
+ const rows = await db.q
140
+ .selectFrom('node as n')
141
+ .innerJoin('content as c', 'c.node_id', 'n.id')
142
+ .innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
143
+ .select('ct.alias')
144
+ .where('n.unique_id', '=', key)
145
+ .execute()
146
+ return { key, typeAlias: rows[0] ? String(rows[0].alias) : 'Image' }
147
+ },
148
+ }
149
+ }
150
+
151
+ const TEXTUAL = new Set([
152
+ 'Umbraco.TextBox',
153
+ 'Umbraco.TextArea',
154
+ 'Umbraco.RichText',
155
+ 'Umbraco.TinyMCE',
156
+ ])
157
+
158
+ /**
159
+ * A value as typed after `--set alias=`: text as it is for a text or rich text
160
+ * property, JSON where it reads as JSON for the rest (`true`, `3`,
161
+ * `["/a", "/b"]`), and the text itself otherwise, such as a path.
162
+ */
163
+ export function typedValue(editor: string, text: string): unknown {
164
+ if (TEXTUAL.has(editor)) return text
165
+ try {
166
+ return JSON.parse(text)
167
+ } catch {
168
+ return text
169
+ }
170
+ }
171
+
94
172
  /** The shorthand into each editor's stored shape. */
95
173
  export function valueWriter(lookup: SchemaLookup, refs: ValueRefs) {
96
174
  const trimPath = (ref: string) => ref.replace(/^\/+|\/+$/g, '')
package/src/seo.ts CHANGED
@@ -193,11 +193,7 @@ export interface SeoHostOptions {
193
193
  }
194
194
 
195
195
  export interface SeoHost {
196
- settings(): Promise<{
197
- effective: SeoSettings
198
- overrides: SeoSettingsOverrides
199
- sources: Record<keyof SeoSettings, SettingSource>
200
- }>
196
+ settings(): Promise<SeoSettingsState>
201
197
  siteDefaults(): Promise<SeoSiteDefaults>
202
198
  sitemap(request: Request, host: string): Promise<Response>
203
199
  robots(request: Request): Promise<Response>
@@ -224,23 +220,32 @@ export interface SeoHost {
224
220
  handle(request: Request, subpath: string, principal: Principal): Promise<Response | undefined>
225
221
  }
226
222
 
227
- export function createSeoHost(options: SeoHostOptions): SeoHost {
228
- const { db, config, cache } = options
229
- let memo: { at: number; overrides: SeoSettingsOverrides } | undefined
230
-
231
- const readOverrides = async (): Promise<SeoSettingsOverrides> => {
232
- if (memo && Date.now() - memo.at < SETTINGS_TTL_MS) return memo.overrides
233
- const raw = await readKeyValue(db, SEO_SETTINGS_KEY)
234
- let overrides: SeoSettingsOverrides = {}
235
- if (raw) {
236
- const parsed = parseSettingsBody(safeJson(raw))
237
- if (parsed.ok) overrides = parsed.overrides
238
- }
239
- memo = { at: Date.now(), overrides }
240
- return overrides
241
- }
223
+ /** The site-wide settings in force, what is saved, and where each value comes from. */
224
+ export interface SeoSettingsState {
225
+ effective: SeoSettings
226
+ overrides: SeoSettingsOverrides
227
+ sources: Record<keyof SeoSettings, SettingSource>
228
+ }
229
+
230
+ async function readOverrides(db: Db): Promise<SeoSettingsOverrides> {
231
+ const raw = await readKeyValue(db, SEO_SETTINGS_KEY)
232
+ if (!raw) return {}
233
+ const parsed = parseSettingsBody(safeJson(raw))
234
+ return parsed.ok ? parsed.overrides : {}
235
+ }
242
236
 
243
- const defaults = (): SeoSettings => ({
237
+ function resolveSettings(
238
+ config: Pick<CromboloConfig, 'siteName' | 'seo'>,
239
+ overrides: SeoSettingsOverrides,
240
+ ): SeoSettingsState {
241
+ const configured: Partial<SeoSettings> = {}
242
+ for (const field of FIELDS) {
243
+ const value = config.seo?.[field]
244
+ if (value === undefined) continue
245
+ if (field === 'notFoundPage') configured.notFoundPage = parseRules(value) ?? []
246
+ else (configured as Record<string, unknown>)[field] = value
247
+ }
248
+ const effective: SeoSettings = {
244
249
  sitemap: true,
245
250
  indexable: true,
246
251
  robotsTxt: DEFAULT_ROBOTS_TXT,
@@ -248,36 +253,60 @@ export function createSeoHost(options: SeoHostOptions): SeoHost {
248
253
  titleSuffix: '',
249
254
  defaultImage: '',
250
255
  notFoundPage: [],
251
- })
252
-
253
- const fromConfig = (): Partial<SeoSettings> => {
254
- const seo = config.seo ?? {}
255
- const out: Partial<SeoSettings> = {}
256
- for (const field of FIELDS) {
257
- const value = seo[field]
258
- if (value === undefined) continue
259
- if (field === 'notFoundPage') out.notFoundPage = parseRules(value) ?? []
260
- else (out as Record<string, unknown>)[field] = value
261
- }
262
- return out
263
256
  }
257
+ const sources = {} as Record<keyof SeoSettings, SettingSource>
258
+ for (const field of FIELDS) {
259
+ const own = overrides[field]
260
+ if (own !== undefined && own !== null) {
261
+ ;(effective as unknown as Record<string, unknown>)[field] = own
262
+ sources[field] = 'backoffice'
263
+ } else if (configured[field] !== undefined) {
264
+ ;(effective as unknown as Record<string, unknown>)[field] = configured[field]
265
+ sources[field] = 'config'
266
+ } else sources[field] = 'default'
267
+ }
268
+ return { effective, overrides, sources }
269
+ }
270
+
271
+ /** The site-wide settings: each a saved value, else the configuration's, else the default. */
272
+ export async function readSeoSettings(
273
+ db: Db,
274
+ config: Pick<CromboloConfig, 'siteName' | 'seo'>,
275
+ ): Promise<SeoSettingsState> {
276
+ return resolveSettings(config, await readOverrides(db))
277
+ }
278
+
279
+ /**
280
+ * Saves changes to the site-wide settings, a `null` removing a saved value so
281
+ * the configuration applies again; a malformed change is refused, saving nothing.
282
+ */
283
+ export async function saveSeoSettings(
284
+ db: Db,
285
+ config: Pick<CromboloConfig, 'siteName' | 'seo'>,
286
+ changes: unknown,
287
+ ): Promise<{ ok: true; settings: SeoSettingsState } | { ok: false; message: string }> {
288
+ const parsed = parseSettingsBody(changes)
289
+ if (!parsed.ok) return parsed
290
+ const merged: SeoSettingsOverrides = { ...(await readOverrides(db)) }
291
+ for (const field of FIELDS) {
292
+ if (!(field in parsed.overrides)) continue
293
+ const value = parsed.overrides[field]
294
+ if (value === null) delete merged[field]
295
+ else (merged as Record<string, unknown>)[field] = value
296
+ }
297
+ await writeKeyValue(db, SEO_SETTINGS_KEY, JSON.stringify(merged))
298
+ return { ok: true, settings: resolveSettings(config, merged) }
299
+ }
300
+
301
+ export function createSeoHost(options: SeoHostOptions): SeoHost {
302
+ const { db, config, cache } = options
303
+ let memo: { at: number; state: SeoSettingsState } | undefined
264
304
 
265
305
  const settings: SeoHost['settings'] = async () => {
266
- const overrides = await readOverrides()
267
- const configured = fromConfig()
268
- const effective = defaults()
269
- const sources = {} as Record<keyof SeoSettings, SettingSource>
270
- for (const field of FIELDS) {
271
- const own = overrides[field]
272
- if (own !== undefined && own !== null) {
273
- ;(effective as unknown as Record<string, unknown>)[field] = own
274
- sources[field] = 'backoffice'
275
- } else if (configured[field] !== undefined) {
276
- ;(effective as unknown as Record<string, unknown>)[field] = configured[field]
277
- sources[field] = 'config'
278
- } else sources[field] = 'default'
279
- }
280
- return { effective, overrides, sources }
306
+ if (memo && Date.now() - memo.at < SETTINGS_TTL_MS) return memo.state
307
+ const state = await readSeoSettings(db, config)
308
+ memo = { at: Date.now(), state }
309
+ return state
281
310
  }
282
311
 
283
312
  /** A media item's address when given its key, else the address as written. */
@@ -532,19 +561,10 @@ export function createSeoHost(options: SeoHostOptions): SeoHost {
532
561
  if (request.method === 'GET') return Response.json(await settings())
533
562
  if (request.method !== 'PUT')
534
563
  return new Response('Method Not Allowed', { status: 405, headers: { allow: 'GET, PUT' } })
535
- const parsed = parseSettingsBody(await request.json().catch(() => undefined))
536
- if (!parsed.ok) return Response.json({ message: parsed.message }, { status: 400 })
537
- memo = undefined
538
- const merged: SeoSettingsOverrides = { ...(await readOverrides()) }
539
- for (const field of FIELDS) {
540
- if (!(field in parsed.overrides)) continue
541
- const value = parsed.overrides[field]
542
- if (value === null) delete merged[field]
543
- else (merged as Record<string, unknown>)[field] = value
544
- }
545
- await writeKeyValue(db, SEO_SETTINGS_KEY, JSON.stringify(merged))
546
- memo = undefined
547
- return Response.json(await settings())
564
+ const saved = await saveSeoSettings(db, config, await request.json().catch(() => undefined))
565
+ if (!saved.ok) return Response.json({ message: saved.message }, { status: 400 })
566
+ memo = { at: Date.now(), state: saved.settings }
567
+ return Response.json(saved.settings)
548
568
  }
549
569
 
550
570
  return { settings, siteDefaults, sitemap, robots, notFound, details, sitemapItems, handle }
package/src/server.ts CHANGED
@@ -36,9 +36,11 @@ import {
36
36
  import {
37
37
  AuthService,
38
38
  AuthStore,
39
+ CliTokens,
39
40
  cookieNames,
40
41
  createAuthRoutes,
41
42
  expireCookie,
43
+ isCliToken,
42
44
  isSafeMethod,
43
45
  isSameOrigin,
44
46
  memberCookieName,
@@ -89,14 +91,12 @@ import {
89
91
  appendCacheInstruction,
90
92
  currentAuditContext,
91
93
  type Db,
92
- ExtensionActivityLog,
93
94
  ensureFormLibraryTypes,
94
95
  ensureKeyValue,
95
96
  FormEntryRepository,
96
97
  FormWorkflowRepository,
97
98
  FormWorkflowSecretRepository,
98
99
  JobRepository,
99
- type JobState,
100
100
  latestContentVersionId,
101
101
  listLibraryForms,
102
102
  MediaAccessRepository,
@@ -159,7 +159,7 @@ import {
159
159
  import { loadSchemaDirectory, type SyncReport } from '@crombolo/schema'
160
160
  import { choicesFor } from '@crombolo/transfer'
161
161
  import type { Server } from 'bun'
162
- import { createNodeLookup, loadAccess } from './access.ts'
162
+ import { createNodeLookup } from './access.ts'
163
163
  import { ACTION_FLASH_COOKIE, actionRegistry, actionRoutes } from './actions.ts'
164
164
  import { createAuditHost, createAuditSink, pluginAuditPlan, recordAudit } from './adapters/audit.ts'
165
165
  import {
@@ -174,6 +174,7 @@ import {
174
174
  import { createPublishedContentSource, loadDraftNode } from './adapters/documents.ts'
175
175
  import type { Approvals } from './approvals.ts'
176
176
  import { handleApprovalsApi } from './approvals-api.ts'
177
+ import { BackgroundJobError, listJobs, readJobQuery, retryJob } from './background-jobs.ts'
177
178
  import { type BundleActor, createBundleAdmin, settingsIn } from './bundle-admin.ts'
178
179
  import { actingPrincipalOf } from './bundle-api.ts'
179
180
  import { type BundleGrants, declaredOrigins } from './bundle-grants.ts'
@@ -202,7 +203,7 @@ import { editorTypeLibs, siteJsxImportSource } from './editor-types.ts'
202
203
  import { emailAvailability, emailReady } from './email.ts'
203
204
  import { noticeAboutEmail } from './email-notice.ts'
204
205
  import { createEmailSettings, type EmailSettingsInput } from './email-settings.ts'
205
- import { activityCsv, readActivityQuery } from './extension-activity.ts'
206
+ import { activityPath, answerActivity } from './extension-activity.ts'
206
207
  import { createBackOfficeBuilds } from './extension-backoffice.ts'
207
208
  import { warnAboutAppPlugins } from './extensions-notice.ts'
208
209
  import { coerceForm, deleteForm, saveForm } from './form-files.ts'
@@ -243,6 +244,7 @@ import {
243
244
  readPreviewToken,
244
245
  signPreviewToken,
245
246
  } from './preview-tokens.ts'
247
+ import { principalOf } from './principal.ts'
246
248
  import { provenanceProblem } from './provenance.ts'
247
249
  import { createRemote, may, type RestartOutcome } from './remote.ts'
248
250
  import { createSchemaTransfer, UPLOAD_LIMITS } from './schema-transfer.ts'
@@ -274,6 +276,7 @@ export const PREVIEW_MEMBER_COOKIE = 'crombolo-preview-member'
274
276
 
275
277
  import { ACTIONS_PATH, type SiteRoute } from '@crombolo/common'
276
278
  import { backofficeAudience } from './backoffice-external.ts'
279
+ import { createCliTokensApi, tokenRefusal } from './cli-tokens-api.ts'
277
280
  import { createExternalSignIn } from './external-sign-in.ts'
278
281
  import { IdentityProviderOverrides } from './identity-provider-overrides.ts'
279
282
  import {
@@ -671,7 +674,7 @@ export async function createServer(
671
674
  const acting = actingPrincipalOf(request)
672
675
  if (acting) return acting
673
676
  const identity = await identify(request)
674
- if (!identity) return undefined
677
+ if (!identity) return tokenPrincipal(request)
675
678
  const principal = await principalFrom(identity)
676
679
  // Story 314: what this session writes says whose groups it was seen as.
677
680
  const context = currentAuditContext()
@@ -683,6 +686,31 @@ export async function createServer(
683
686
  return principal
684
687
  }
685
688
 
689
+ /** A command-line token a request carries as its bearer, never from a cookie (story 351). */
690
+ const cliTokenOf = (request: Request): string | undefined => {
691
+ const header = request.headers.get('authorization')
692
+ const bearer = header?.toLowerCase().startsWith('bearer ') ? header.slice(7).trim() : undefined
693
+ return bearer && isCliToken(bearer) ? bearer : undefined
694
+ }
695
+
696
+ /** The person a command-line token acts as, with their permissions as they are now. */
697
+ async function tokenPrincipal(request: Request): Promise<Principal | undefined> {
698
+ const token = cliTokenOf(request)
699
+ if (!token) return undefined
700
+ const resolved = await cliTokens.resolve(token)
701
+ if (!resolved.ok) return undefined
702
+ const identity = await auth.identityOf(resolved.user.id)
703
+ if (!identity) return undefined
704
+ if (resolved.firstUse) await cliTokensApi.firstUse(resolved.token, clientAddress(request))
705
+ const principal = await principalOf(db, identity, {
706
+ key: resolved.token.key,
707
+ name: resolved.token.name,
708
+ })
709
+ const context = currentAuditContext()
710
+ if (context) context.token = { userKey: normaliseUuid(principal.id), name: resolved.token.name }
711
+ return principal
712
+ }
713
+
686
714
  /** The signed-in session a request carries, from its cookie or a bearer token. */
687
715
  async function identify(request: Request): Promise<ResolvedIdentity | undefined> {
688
716
  const header = request.headers.get('authorization')
@@ -708,28 +736,10 @@ export async function createServer(
708
736
  }
709
737
 
710
738
  /** What a resolved user may do, as every check in the Management API reads it. */
711
- async function principalFrom(
739
+ function principalFrom(
712
740
  identity: NonNullable<Awaited<ReturnType<typeof auth.identityOf>>>,
713
741
  ): Promise<Principal> {
714
- return {
715
- id: identity.user.key,
716
- userName: identity.user.login,
717
- name: identity.user.userName,
718
- email: identity.user.email,
719
- isAdmin: identity.isAdmin,
720
- languageIsoCode: identity.user.language ?? undefined,
721
- avatarUrls: identity.user.avatar ? [identity.user.avatar] : [],
722
- allowedSections: identity.allowedSections,
723
- permissions: identity.permissions,
724
- groupKeys: identity.groupKeys,
725
- hasAccessToAllLanguages: identity.hasAccessToAllLanguages,
726
- ...(await loadAccess(
727
- db,
728
- identity.user.id,
729
- identity.viewingAs ? identity.groupKeys : undefined,
730
- )),
731
- ...(identity.viewingAs ? { viewingAs: identity.viewingAs } : {}),
732
- }
742
+ return principalOf(db, identity)
733
743
  }
734
744
 
735
745
  // Every page as last saved, for previewing in an app (story 053). Built on the
@@ -914,7 +924,18 @@ export async function createServer(
914
924
  config,
915
925
  authenticate,
916
926
  bundles: bundleAdmin,
927
+ operations: core.operations,
928
+ nodeState: schema.nodeState,
929
+ // Read when a request comes, by which time the Management API's ports are made.
930
+ userPorts: () => {
931
+ const users = managementDeps.userManagement
932
+ const groups = managementDeps.userGroups
933
+ return users && groups ? { users, groups } : undefined
934
+ },
917
935
  restart: serverOptions.restart,
936
+ jobsWaitingSince: () => core.workerWatch.status().waitingSince,
937
+ activity: { flush: () => core.activity.flush(), days: config.extensionActivityDays },
938
+ onMediaAccessChange: (key) => mediaCache.drop([key]),
918
939
  onApplied: async () => {
919
940
  cache.invalidate()
920
941
  mediaCache.clear()
@@ -1347,6 +1368,11 @@ export async function createServer(
1347
1368
  const canSendUserLinks = () => Boolean(resolveUserLinkSender(config, email))
1348
1369
  const emailSettings = createEmailSettings(db, config, { port: () => email })
1349
1370
  const viewAs = createViewAs(db, auth)
1371
+ const cliTokens = new CliTokens(db, {
1372
+ enabled: config.cliTokens,
1373
+ maxDays: config.cliTokenMaxDays,
1374
+ })
1375
+ const cliTokensApi = createCliTokensApi(db, cliTokens)
1350
1376
  const schemaTransfer = createSchemaTransfer(db, config, {
1351
1377
  boot: schema,
1352
1378
  afterApply: async (report) => {
@@ -1554,6 +1580,10 @@ export async function createServer(
1554
1580
  if (config.setupCode && (await setup.pending()) === false)
1555
1581
  log.warning('CROMBOLO_SETUP_CODE is still set, but the site is set up. Remove the setting.')
1556
1582
  noticeAboutEmail(emailStatus, logger('email'), { development: config.development })
1583
+ if (!config.development && config.cliAccess === 'open')
1584
+ log.warning(
1585
+ 'CROMBOLO_CLI_ACCESS is open: commands run on this site without anyone signing in, and the audit log cannot say who ran them.',
1586
+ )
1557
1587
  const hubPath = SERVER_EVENT_HUB_PATH
1558
1588
  const previewHubPath = PREVIEW_HUB_PATH
1559
1589
 
@@ -1567,10 +1597,12 @@ export async function createServer(
1567
1597
  const hostTokenPath = `${paths.pluginPath}/api/host-token`
1568
1598
  const contentQueryPath = `${paths.pluginPath}/api/content-query`
1569
1599
  const viewAsPath = `${paths.pluginPath}/api/view-as`
1600
+ const cliTokensPath = `${paths.pluginPath}/api/cli-tokens`
1570
1601
  const selfAudited = [
1571
1602
  `${paths.pluginPath}/api/email/`,
1572
1603
  `${paths.pluginPath}/api/schema-transfer/`,
1573
1604
  viewAsPath,
1605
+ cliTokensPath,
1574
1606
  ]
1575
1607
  const bundleInstallPaths = new Set(
1576
1608
  ['install', 'uninstall', 'disable', 'enable', 'grant', 'settings'].flatMap((action) => [
@@ -2305,35 +2337,15 @@ export async function createServer(
2305
2337
  }
2306
2338
 
2307
2339
  // Story 327: what one extension did, newest first, its counts, and the same as a file.
2308
- const watching = /^installed\/([a-z0-9][a-z0-9-]*)\/activity(\/summary|\.csv)?$/.exec(action)
2309
- if (watching && request.method === 'GET') {
2310
- const [, id, part] = watching as unknown as [string, string, string | undefined]
2311
- const read = readActivityQuery(url.searchParams)
2312
- if (typeof read === 'string')
2313
- return Response.json(
2314
- { title: 'Invalid request', status: 400, detail: read },
2315
- { status: 400 },
2316
- )
2317
- await core.activity.flush()
2318
- const store = new ExtensionActivityLog(db)
2319
- if (part === '/summary')
2320
- return Response.json({
2321
- counts: await store.counts(
2322
- id,
2323
- new Date(Date.now() - config.extensionActivityDays * 86_400_000),
2324
- ),
2325
- people: await store.people(id),
2326
- days: config.extensionActivityDays,
2327
- })
2328
- if (part === '.csv')
2329
- return new Response(await activityCsv(store, id, read.filter), {
2330
- headers: {
2331
- 'content-type': 'text/csv; charset=utf-8',
2332
- 'content-disposition': `attachment; filename="${id}-activity.csv"`,
2333
- },
2334
- })
2335
- return Response.json(await store.page(id, read.filter, read.cursor))
2336
- }
2340
+ const watching = activityPath(action)
2341
+ if (watching && request.method === 'GET')
2342
+ return answerActivity(
2343
+ db,
2344
+ { flush: () => core.activity.flush(), days: config.extensionActivityDays },
2345
+ watching.id,
2346
+ watching.part,
2347
+ url.searchParams,
2348
+ )
2337
2349
 
2338
2350
  // What this person may grant at each level here (story 324): the panel shows the button, the sentence or the snippet.
2339
2351
  const granting = mayGrant(principal.isAdmin, config.unrestrictedExtensions)
@@ -2594,6 +2606,24 @@ export async function createServer(
2594
2606
  : Response.json(outcome, { status: outcome.status })
2595
2607
  }
2596
2608
 
2609
+ // Story 351: a person's command-line tokens, and an administrator's view of anyone's.
2610
+ if (pathname === cliTokensPath || pathname.startsWith(`${cliTokensPath}/`)) {
2611
+ const principal = await authenticate(request)
2612
+ if (!principal) {
2613
+ const token = cliTokenOf(request)
2614
+ const why = token ? await cliTokens.resolve(token) : undefined
2615
+ return why && !why.ok
2616
+ ? tokenRefusal(why.reason)
2617
+ : new Response('Unauthorized', { status: 401 })
2618
+ }
2619
+ return cliTokensApi.handle(
2620
+ request,
2621
+ principal,
2622
+ pathname.slice(cliTokensPath.length),
2623
+ clientAddress(request),
2624
+ )
2625
+ }
2626
+
2597
2627
  // Story 314: an administrator's session seen as user groups, and back.
2598
2628
  if (pathname === viewAsPath) {
2599
2629
  const identity = await identify(request)
@@ -3098,59 +3128,32 @@ export async function createServer(
3098
3128
  const principal = await authenticate(request)
3099
3129
  if (!principal) return new Response('Unauthorized', { status: 401 })
3100
3130
  if (!hasSection(principal, 'settings')) return new Response('Forbidden', { status: 403 })
3101
- const queue = new JobRepository(db)
3102
3131
  if (pathname === jobsPath && request.method === 'GET') {
3103
- const url = new URL(request.url)
3104
- const state = url.searchParams.get('state')
3105
- const listed = await queue.list({
3106
- owner: url.searchParams.get('owner') || undefined,
3107
- state: ['queued', 'running', 'succeeded', 'failed'].includes(state ?? '')
3108
- ? (state as JobState)
3109
- : undefined,
3110
- skip: Math.max(0, Number(url.searchParams.get('skip')) || 0),
3111
- take: Math.min(200, Math.max(1, Number(url.searchParams.get('take')) || 50)),
3112
- })
3132
+ const listed = await listJobs(db, readJobQuery(new URL(request.url).searchParams))
3113
3133
  return Response.json({
3114
3134
  total: listed.total,
3115
3135
  // Set while this node leaves its jobs to a worker and none is running.
3116
3136
  waitingSince: core.workerWatch.status().waitingSince,
3117
- items: listed.items.map((job) => ({
3118
- id: job.id,
3119
- owner: job.owner,
3120
- name: job.name,
3121
- state: job.state,
3122
- attempts: job.attempts,
3123
- maxAttempts: job.maxAttempts,
3124
- nextAttemptAt: job.nextAttemptAt.toISOString(),
3125
- progress: job.progress,
3126
- error: job.lastError,
3127
- queuedBy: job.queuedBy,
3128
- createdAt: job.createdAt.toISOString(),
3129
- finishedAt: job.finishedAt?.toISOString() ?? null,
3130
- })),
3137
+ items: listed.items,
3131
3138
  })
3132
3139
  }
3133
3140
  const retry = /^\/([0-9a-f-]{36})\/retry$/i.exec(pathname.slice(jobsPath.length))
3134
3141
  if (retry && request.method === 'POST') {
3135
- const id = retry[1] as string
3136
- const job = await queue.get(id)
3137
- if (!job || !(await queue.retry(id)))
3142
+ try {
3143
+ const done = await retryJob(db, retry[1] as string, {
3144
+ key: principal.id,
3145
+ name: principal.name,
3146
+ source: 'request',
3147
+ address: clientAddress(request),
3148
+ })
3149
+ return Response.json({ ok: true, message: done.message })
3150
+ } catch (error) {
3151
+ if (!(error instanceof BackgroundJobError)) throw error
3138
3152
  return Response.json(
3139
3153
  { ok: false, message: 'Only a job that has failed can be run again.' },
3140
3154
  { status: 409 },
3141
3155
  )
3142
- await recordAudit(db, {
3143
- category: 'system',
3144
- action: 'Retry',
3145
- entityType: 'Job',
3146
- entityName: `${job.owner}/${job.name}`,
3147
- detail: job.lastError ? `after: ${job.lastError.slice(0, 200)}` : null,
3148
- source: 'request',
3149
- userKey: principal.id,
3150
- userName: principal.name,
3151
- ...clientAddress(request),
3152
- })
3153
- return Response.json({ ok: true, message: `${job.name} is queued to run again.` })
3156
+ }
3154
3157
  }
3155
3158
  return new Response('Not Found', { status: 404 })
3156
3159
  }