@crombolo/server 0.65.1 → 0.67.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/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,
@@ -108,6 +108,7 @@ import {
108
108
  readUrlOptions,
109
109
  searchProvidersOf,
110
110
  TransferRunRepository,
111
+ UserRepository,
111
112
  type WritesPaused,
112
113
  withAuditContext,
113
114
  } from '@crombolo/data'
@@ -159,7 +160,7 @@ import {
159
160
  import { loadSchemaDirectory, type SyncReport } from '@crombolo/schema'
160
161
  import { choicesFor } from '@crombolo/transfer'
161
162
  import type { Server } from 'bun'
162
- import { createNodeLookup, loadAccess } from './access.ts'
163
+ import { createNodeLookup } from './access.ts'
163
164
  import { ACTION_FLASH_COOKIE, actionRegistry, actionRoutes } from './actions.ts'
164
165
  import { createAuditHost, createAuditSink, pluginAuditPlan, recordAudit } from './adapters/audit.ts'
165
166
  import {
@@ -174,6 +175,7 @@ import {
174
175
  import { createPublishedContentSource, loadDraftNode } from './adapters/documents.ts'
175
176
  import type { Approvals } from './approvals.ts'
176
177
  import { handleApprovalsApi } from './approvals-api.ts'
178
+ import { BackgroundJobError, listJobs, readJobQuery, retryJob } from './background-jobs.ts'
177
179
  import { type BundleActor, createBundleAdmin, settingsIn } from './bundle-admin.ts'
178
180
  import { actingPrincipalOf } from './bundle-api.ts'
179
181
  import { type BundleGrants, declaredOrigins } from './bundle-grants.ts'
@@ -202,7 +204,7 @@ import { editorTypeLibs, siteJsxImportSource } from './editor-types.ts'
202
204
  import { emailAvailability, emailReady } from './email.ts'
203
205
  import { noticeAboutEmail } from './email-notice.ts'
204
206
  import { createEmailSettings, type EmailSettingsInput } from './email-settings.ts'
205
- import { activityCsv, readActivityQuery } from './extension-activity.ts'
207
+ import { activityPath, answerActivity } from './extension-activity.ts'
206
208
  import { createBackOfficeBuilds } from './extension-backoffice.ts'
207
209
  import { warnAboutAppPlugins } from './extensions-notice.ts'
208
210
  import { coerceForm, deleteForm, saveForm } from './form-files.ts'
@@ -243,8 +245,10 @@ import {
243
245
  readPreviewToken,
244
246
  signPreviewToken,
245
247
  } from './preview-tokens.ts'
248
+ import { principalOf } from './principal.ts'
246
249
  import { provenanceProblem } from './provenance.ts'
247
250
  import { createRemote, may, type RestartOutcome } from './remote.ts'
251
+ import { createPeopleExchange } from './remote-people.ts'
248
252
  import { createSchemaTransfer, UPLOAD_LIMITS } from './schema-transfer.ts'
249
253
  import { SiteAssets } from './site-assets.ts'
250
254
  import { unknownHostProvided } from './site-file.ts'
@@ -274,8 +278,10 @@ export const PREVIEW_MEMBER_COOKIE = 'crombolo-preview-member'
274
278
 
275
279
  import { ACTIONS_PATH, type SiteRoute } from '@crombolo/common'
276
280
  import { backofficeAudience } from './backoffice-external.ts'
281
+ import { createCliTokensApi, tokenRefusal } from './cli-tokens-api.ts'
277
282
  import { createExternalSignIn } from './external-sign-in.ts'
278
283
  import { IdentityProviderOverrides } from './identity-provider-overrides.ts'
284
+ import { exchangingProviders } from './identity-providers.ts'
279
285
  import {
280
286
  builtIslandFile,
281
287
  devServerIslandManifest,
@@ -671,10 +677,18 @@ export async function createServer(
671
677
  const acting = actingPrincipalOf(request)
672
678
  if (acting) return acting
673
679
  const identity = await identify(request)
674
- if (!identity) return undefined
680
+ if (!identity) return tokenPrincipal(request)
675
681
  const principal = await principalFrom(identity)
676
682
  // Story 314: what this session writes says whose groups it was seen as.
677
683
  const context = currentAuditContext()
684
+ // Story 364: and that it came by a token exchanged through a provider.
685
+ if (context && identity.exchangedThrough)
686
+ context.exchange = {
687
+ userKey: normaliseUuid(principal.id),
688
+ provider:
689
+ config.backofficeIdentityProviders.find((p) => p.oidc.id === identity.exchangedThrough)
690
+ ?.oidc.name ?? identity.exchangedThrough,
691
+ }
678
692
  if (context && principal.viewingAs)
679
693
  context.viewing = {
680
694
  userKey: normaliseUuid(principal.id),
@@ -683,6 +697,31 @@ export async function createServer(
683
697
  return principal
684
698
  }
685
699
 
700
+ /** A command-line token a request carries as its bearer, never from a cookie (story 351). */
701
+ const cliTokenOf = (request: Request): string | undefined => {
702
+ const header = request.headers.get('authorization')
703
+ const bearer = header?.toLowerCase().startsWith('bearer ') ? header.slice(7).trim() : undefined
704
+ return bearer && isCliToken(bearer) ? bearer : undefined
705
+ }
706
+
707
+ /** The person a command-line token acts as, with their permissions as they are now. */
708
+ async function tokenPrincipal(request: Request): Promise<Principal | undefined> {
709
+ const token = cliTokenOf(request)
710
+ if (!token) return undefined
711
+ const resolved = await cliTokens.resolve(token)
712
+ if (!resolved.ok) return undefined
713
+ const identity = await auth.identityOf(resolved.user.id)
714
+ if (!identity) return undefined
715
+ if (resolved.firstUse) await cliTokensApi.firstUse(resolved.token, clientAddress(request))
716
+ const principal = await principalOf(db, identity, {
717
+ key: resolved.token.key,
718
+ name: resolved.token.name,
719
+ })
720
+ const context = currentAuditContext()
721
+ if (context) context.token = { userKey: normaliseUuid(principal.id), name: resolved.token.name }
722
+ return principal
723
+ }
724
+
686
725
  /** The signed-in session a request carries, from its cookie or a bearer token. */
687
726
  async function identify(request: Request): Promise<ResolvedIdentity | undefined> {
688
727
  const header = request.headers.get('authorization')
@@ -708,28 +747,10 @@ export async function createServer(
708
747
  }
709
748
 
710
749
  /** What a resolved user may do, as every check in the Management API reads it. */
711
- async function principalFrom(
750
+ function principalFrom(
712
751
  identity: NonNullable<Awaited<ReturnType<typeof auth.identityOf>>>,
713
752
  ): 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
- }
753
+ return principalOf(db, identity)
733
754
  }
734
755
 
735
756
  // Every page as last saved, for previewing in an app (story 053). Built on the
@@ -909,12 +930,104 @@ export async function createServer(
909
930
  source: 'request',
910
931
  ...clientAddress(request),
911
932
  })
933
+ // Story 364: a back-office provider's token exchanged at the remote for a sign-in as the person.
934
+ const exchanging = exchangingProviders(
935
+ config.backofficeIdentityProviders,
936
+ config.remoteExchangeProviders,
937
+ )
938
+ for (const id of config.remoteExchangeProviders)
939
+ if (!config.backofficeIdentityProviders.some((p) => p.oidc.id === id))
940
+ log.warning(
941
+ 'CROMBOLO_REMOTE_EXCHANGE_PROVIDERS names {id}, which the config declares no back-office identity provider as.',
942
+ { id },
943
+ )
944
+ if (exchanging.length > 0)
945
+ log.info('The remote exchanges tokens from {providers}', {
946
+ providers: exchanging.map((p) => p.oidc.id).join(', '),
947
+ })
948
+ const people =
949
+ exchanging.length === 0
950
+ ? undefined
951
+ : (() => {
952
+ const users = new UserRepository(db)
953
+ const accounts = backofficeAudience(db, {
954
+ auth,
955
+ providers: exchanging,
956
+ backOfficePath: paths.backOfficePath,
957
+ sessionCookie: () => '',
958
+ })
959
+ const overrides = new IdentityProviderOverrides(
960
+ db,
961
+ config.secretKey,
962
+ config.lockedIdentityProviders,
963
+ )
964
+ return createPeopleExchange({
965
+ db,
966
+ providers: exchanging,
967
+ backoffice: config.backofficeIdentityProviders,
968
+ resolve: (provider) => overrides.apply('user', provider),
969
+ accounts: {
970
+ byKey: accounts.byKey,
971
+ byEmail: accounts.byEmail,
972
+ setGroups: accounts.setGroups,
973
+ refusal: async (key) => {
974
+ const user = await users.byKey(key)
975
+ if (!user) return 'the person no longer exists'
976
+ if (user.isLockedOut) return 'the person is locked out'
977
+ if (!user.isApproved) return 'the person is disabled or not yet approved'
978
+ const identity = await auth.identityOf(user.id)
979
+ return (identity?.allowedSections.length ?? 0) > 0
980
+ ? undefined
981
+ : 'the person has no access to the back office'
982
+ },
983
+ signIn: async (key, provider, seconds, ip) => {
984
+ const user = await users.byKey(key)
985
+ if (!user) return { refused: 'the person no longer exists' }
986
+ const result = await auth.signInByExchange(user.userName, provider, seconds, ip)
987
+ if (result.status === 'success') return { accessToken: result.accessToken }
988
+ return {
989
+ refused:
990
+ result.reason === 'lockedOut'
991
+ ? 'the person is locked out'
992
+ : 'the person is disabled or not yet approved',
993
+ }
994
+ },
995
+ },
996
+ onExchange: (outcome, request) =>
997
+ recordAudit(db, {
998
+ category: 'sign-in',
999
+ action: outcome.ok ? 'RemoteExchangeSignIn' : 'RemoteExchangeSignInRefused',
1000
+ source: 'request',
1001
+ userKey: outcome.ok ? outcome.account.key : null,
1002
+ userName: null,
1003
+ entityType: 'User',
1004
+ entityKey: outcome.ok ? outcome.account.key : null,
1005
+ entityName: outcome.ok ? outcome.account.email : null,
1006
+ detail: outcome.ok
1007
+ ? `Signed in through ${outcome.provider.oidc.name}, by exchange at the remote`
1008
+ : `Refused${outcome.provider ? ` through ${outcome.provider.oidc.name}` : ''}: ${outcome.reason}`,
1009
+ ...clientAddress(request),
1010
+ }),
1011
+ })
1012
+ })()
912
1013
  const remote = createRemote({
913
1014
  db,
914
1015
  config,
915
1016
  authenticate,
1017
+ people,
916
1018
  bundles: bundleAdmin,
1019
+ operations: core.operations,
1020
+ nodeState: schema.nodeState,
1021
+ // Read when a request comes, by which time the Management API's ports are made.
1022
+ userPorts: () => {
1023
+ const users = managementDeps.userManagement
1024
+ const groups = managementDeps.userGroups
1025
+ return users && groups ? { users, groups } : undefined
1026
+ },
917
1027
  restart: serverOptions.restart,
1028
+ jobsWaitingSince: () => core.workerWatch.status().waitingSince,
1029
+ activity: { flush: () => core.activity.flush(), days: config.extensionActivityDays },
1030
+ onMediaAccessChange: (key) => mediaCache.drop([key]),
918
1031
  onApplied: async () => {
919
1032
  cache.invalidate()
920
1033
  mediaCache.clear()
@@ -1347,6 +1460,11 @@ export async function createServer(
1347
1460
  const canSendUserLinks = () => Boolean(resolveUserLinkSender(config, email))
1348
1461
  const emailSettings = createEmailSettings(db, config, { port: () => email })
1349
1462
  const viewAs = createViewAs(db, auth)
1463
+ const cliTokens = new CliTokens(db, {
1464
+ enabled: config.cliTokens,
1465
+ maxDays: config.cliTokenMaxDays,
1466
+ })
1467
+ const cliTokensApi = createCliTokensApi(db, cliTokens)
1350
1468
  const schemaTransfer = createSchemaTransfer(db, config, {
1351
1469
  boot: schema,
1352
1470
  afterApply: async (report) => {
@@ -1554,6 +1672,10 @@ export async function createServer(
1554
1672
  if (config.setupCode && (await setup.pending()) === false)
1555
1673
  log.warning('CROMBOLO_SETUP_CODE is still set, but the site is set up. Remove the setting.')
1556
1674
  noticeAboutEmail(emailStatus, logger('email'), { development: config.development })
1675
+ if (!config.development && config.cliAccess === 'open')
1676
+ log.warning(
1677
+ 'CROMBOLO_CLI_ACCESS is open: commands run on this site without anyone signing in, and the audit log cannot say who ran them.',
1678
+ )
1557
1679
  const hubPath = SERVER_EVENT_HUB_PATH
1558
1680
  const previewHubPath = PREVIEW_HUB_PATH
1559
1681
 
@@ -1567,10 +1689,12 @@ export async function createServer(
1567
1689
  const hostTokenPath = `${paths.pluginPath}/api/host-token`
1568
1690
  const contentQueryPath = `${paths.pluginPath}/api/content-query`
1569
1691
  const viewAsPath = `${paths.pluginPath}/api/view-as`
1692
+ const cliTokensPath = `${paths.pluginPath}/api/cli-tokens`
1570
1693
  const selfAudited = [
1571
1694
  `${paths.pluginPath}/api/email/`,
1572
1695
  `${paths.pluginPath}/api/schema-transfer/`,
1573
1696
  viewAsPath,
1697
+ cliTokensPath,
1574
1698
  ]
1575
1699
  const bundleInstallPaths = new Set(
1576
1700
  ['install', 'uninstall', 'disable', 'enable', 'grant', 'settings'].flatMap((action) => [
@@ -2305,35 +2429,15 @@ export async function createServer(
2305
2429
  }
2306
2430
 
2307
2431
  // 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
- }
2432
+ const watching = activityPath(action)
2433
+ if (watching && request.method === 'GET')
2434
+ return answerActivity(
2435
+ db,
2436
+ { flush: () => core.activity.flush(), days: config.extensionActivityDays },
2437
+ watching.id,
2438
+ watching.part,
2439
+ url.searchParams,
2440
+ )
2337
2441
 
2338
2442
  // What this person may grant at each level here (story 324): the panel shows the button, the sentence or the snippet.
2339
2443
  const granting = mayGrant(principal.isAdmin, config.unrestrictedExtensions)
@@ -2594,10 +2698,30 @@ export async function createServer(
2594
2698
  : Response.json(outcome, { status: outcome.status })
2595
2699
  }
2596
2700
 
2701
+ // Story 351: a person's command-line tokens, and an administrator's view of anyone's.
2702
+ if (pathname === cliTokensPath || pathname.startsWith(`${cliTokensPath}/`)) {
2703
+ const principal = await authenticate(request)
2704
+ if (!principal) {
2705
+ const token = cliTokenOf(request)
2706
+ const why = token ? await cliTokens.resolve(token) : undefined
2707
+ return why && !why.ok
2708
+ ? tokenRefusal(why.reason)
2709
+ : new Response('Unauthorized', { status: 401 })
2710
+ }
2711
+ return cliTokensApi.handle(
2712
+ request,
2713
+ principal,
2714
+ pathname.slice(cliTokensPath.length),
2715
+ clientAddress(request),
2716
+ )
2717
+ }
2718
+
2597
2719
  // Story 314: an administrator's session seen as user groups, and back.
2598
2720
  if (pathname === viewAsPath) {
2599
2721
  const identity = await identify(request)
2600
2722
  if (!identity) return new Response('Unauthorized', { status: 401 })
2723
+ // Story 364: a token exchanged through a provider never sees as anyone else.
2724
+ if (identity.exchangedThrough) return new Response('Forbidden', { status: 403 })
2601
2725
  return viewAs.handle(request, identity, clientAddress(request))
2602
2726
  }
2603
2727
 
@@ -3098,59 +3222,32 @@ export async function createServer(
3098
3222
  const principal = await authenticate(request)
3099
3223
  if (!principal) return new Response('Unauthorized', { status: 401 })
3100
3224
  if (!hasSection(principal, 'settings')) return new Response('Forbidden', { status: 403 })
3101
- const queue = new JobRepository(db)
3102
3225
  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
- })
3226
+ const listed = await listJobs(db, readJobQuery(new URL(request.url).searchParams))
3113
3227
  return Response.json({
3114
3228
  total: listed.total,
3115
3229
  // Set while this node leaves its jobs to a worker and none is running.
3116
3230
  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
- })),
3231
+ items: listed.items,
3131
3232
  })
3132
3233
  }
3133
3234
  const retry = /^\/([0-9a-f-]{36})\/retry$/i.exec(pathname.slice(jobsPath.length))
3134
3235
  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)))
3236
+ try {
3237
+ const done = await retryJob(db, retry[1] as string, {
3238
+ key: principal.id,
3239
+ name: principal.name,
3240
+ source: 'request',
3241
+ address: clientAddress(request),
3242
+ })
3243
+ return Response.json({ ok: true, message: done.message })
3244
+ } catch (error) {
3245
+ if (!(error instanceof BackgroundJobError)) throw error
3138
3246
  return Response.json(
3139
3247
  { ok: false, message: 'Only a job that has failed can be run again.' },
3140
3248
  { status: 409 },
3141
3249
  )
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.` })
3250
+ }
3154
3251
  }
3155
3252
  return new Response('Not Found', { status: 404 })
3156
3253
  }