@crombolo/server 0.64.0 → 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.
Files changed (46) hide show
  1. package/package.json +15 -14
  2. package/src/access.ts +6 -2
  3. package/src/adapters/blueprints.ts +19 -5
  4. package/src/adapters/elements.ts +49 -36
  5. package/src/adapters/members.ts +37 -3
  6. package/src/adapters/users.ts +18 -0
  7. package/src/approvals.ts +44 -15
  8. package/src/atomic-write.ts +2 -2
  9. package/src/background-jobs.ts +170 -0
  10. package/src/bundle-admin.ts +39 -3
  11. package/src/bundle-reload.ts +2 -1
  12. package/src/bundles.ts +60 -25
  13. package/src/cli-tokens-api.ts +152 -0
  14. package/src/config.ts +52 -3
  15. package/src/content-events.ts +22 -0
  16. package/src/content-operations.ts +26 -1
  17. package/src/core.ts +357 -133
  18. package/src/extension-activity.ts +121 -0
  19. package/src/extension-components.ts +20 -4
  20. package/src/extension-discovery.ts +84 -65
  21. package/src/grant-trust.ts +6 -4
  22. package/src/index.ts +14 -0
  23. package/src/media-access.ts +30 -125
  24. package/src/media-library.ts +953 -0
  25. package/src/member-admin.ts +761 -0
  26. package/src/node-operations.ts +19 -2
  27. package/src/ports.ts +2 -0
  28. package/src/principal.ts +35 -0
  29. package/src/remote-background-jobs.ts +99 -0
  30. package/src/remote-credentials.ts +114 -6
  31. package/src/remote-extension-activity.ts +66 -0
  32. package/src/remote-media-library.ts +297 -0
  33. package/src/remote-media.ts +2 -2
  34. package/src/remote-members.ts +271 -0
  35. package/src/remote-undo.ts +234 -0
  36. package/src/remote-users.ts +229 -0
  37. package/src/remote.ts +141 -3
  38. package/src/routes.ts +22 -3
  39. package/src/seed/values.ts +82 -4
  40. package/src/seo.ts +81 -61
  41. package/src/server.ts +153 -92
  42. package/src/settings.ts +95 -6
  43. package/src/trusted-signers-admin.ts +39 -3
  44. package/src/undo.ts +358 -0
  45. package/src/user-admin.ts +581 -0
  46. package/src/view-as.ts +95 -0
@@ -6,8 +6,10 @@
6
6
  */
7
7
  import {
8
8
  createDocumentOperations,
9
+ createElementOperations,
9
10
  createMediaOperations,
10
11
  type DocumentOperations,
12
+ type ElementOperations,
11
13
  type EventSink,
12
14
  type MediaOperations,
13
15
  SILENT,
@@ -19,9 +21,10 @@ import {
19
21
  RedirectRepository,
20
22
  } from '@crombolo/data'
21
23
  import type { PublishedCache } from '@crombolo/render'
24
+ import { createElementPort } from './adapters/elements.ts'
22
25
  import { type Approvals, approvalsGate, createApprovals } from './approvals.ts'
23
26
  import type { CromboloConfig } from './config.ts'
24
- import { createMediaEventSink } from './content-events.ts'
27
+ import { createElementEventSink, createMediaEventSink } from './content-events.ts'
25
28
  import type { ContentNotifier } from './content-notifications.ts'
26
29
  import { writeDomainsFor } from './domains.ts'
27
30
  import type { EmailPort } from './email.ts'
@@ -36,6 +39,8 @@ export interface NodeOperations {
36
39
  approvals: Approvals
37
40
  documents: DocumentOperations
38
41
  media: MediaOperations
42
+ /** Every Library write (story 361). */
43
+ elements: ElementOperations
39
44
  }
40
45
 
41
46
  export interface NodeOperationsOptions {
@@ -121,5 +126,17 @@ export function createNodeOperations(options: NodeOperationsOptions): NodeOperat
121
126
  refusalReason,
122
127
  background: options.background,
123
128
  })
124
- return { valueIntake: repository.valueIntake, tracker, approvals, documents, media }
129
+ const elements = createElementOperations({
130
+ db,
131
+ store: (tx) =>
132
+ createElementPort(tx, {
133
+ nodeState: options.nodeState,
134
+ nodeId: options.nodeId,
135
+ instructedBy: options.instructedBy,
136
+ valueIntake: repository.valueIntake,
137
+ }),
138
+ events: createElementEventSink(),
139
+ onChange: () => cache?.invalidate(),
140
+ })
141
+ return { valueIntake: repository.valueIntake, tracker, approvals, documents, media, elements }
125
142
  }
package/src/ports.ts CHANGED
@@ -618,6 +618,8 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
618
618
  valueIntake,
619
619
  onChange: () => options.cache?.invalidate(),
620
620
  })
621
+ // Every Library write, whoever starts it (story 361).
622
+ deps.elementOperations = operations?.elements
621
623
  deps.references = createReferencePort(options.db)
622
624
  deps.relations = createRelationPort(options.db)
623
625
  deps.webhooks = createWebhookPort(
@@ -0,0 +1,35 @@
1
+ /**
2
+ * What a signed-in person may do, as every check in the Management API reads
3
+ * it: built the one way for the server and for the command line (story 350).
4
+ */
5
+ import type { Principal } from '@crombolo/api-management/domain'
6
+ import type { ResolvedIdentity } from '@crombolo/auth'
7
+ import type { Db } from '@crombolo/data'
8
+ import { loadAccess } from './access.ts'
9
+
10
+ export async function principalOf(
11
+ db: Db,
12
+ identity: Omit<ResolvedIdentity, 'sessionId'>,
13
+ viaToken?: Principal['viaToken'],
14
+ ): Promise<Principal> {
15
+ return {
16
+ id: identity.user.key,
17
+ userName: identity.user.login,
18
+ name: identity.user.userName,
19
+ email: identity.user.email,
20
+ isAdmin: identity.isAdmin,
21
+ languageIsoCode: identity.user.language ?? undefined,
22
+ avatarUrls: identity.user.avatar ? [identity.user.avatar] : [],
23
+ allowedSections: identity.allowedSections,
24
+ permissions: identity.permissions,
25
+ groupKeys: identity.groupKeys,
26
+ hasAccessToAllLanguages: identity.hasAccessToAllLanguages,
27
+ ...(await loadAccess(
28
+ db,
29
+ identity.user.id,
30
+ identity.viewingAs ? identity.groupKeys : undefined,
31
+ )),
32
+ ...(identity.viewingAs ? { viewingAs: identity.viewingAs } : {}),
33
+ ...(viaToken ? { viaToken } : {}),
34
+ }
35
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * The remote protocol's routes for background jobs (story 359): a page of the
3
+ * site's jobs, one of them, and a failed one run again, as Settings →
4
+ * Background jobs does, through the core the command line uses. They need the
5
+ * Settings section; CI is refused, since these act for a person.
6
+ */
7
+ import { hasSection, type Principal } from '@crombolo/api-management/domain'
8
+ import type { Db } from '@crombolo/data'
9
+ import { BackgroundJobError, jobOf, listJobs, readJobQuery, retryJob } from './background-jobs.ts'
10
+
11
+ interface Problem {
12
+ code: string
13
+ title: string
14
+ detail?: string
15
+ }
16
+
17
+ export interface BackgroundJobRouteOptions {
18
+ db: Db
19
+ problem(status: number, body: Problem): Response
20
+ /** A refusal when the site's remote access level takes no changes. */
21
+ levelRefusal(): Response | undefined
22
+ /** When this node began waiting for a worker that is not running, or null. */
23
+ waitingSince?: () => string | null
24
+ }
25
+
26
+ const STATUS: Record<BackgroundJobError['kind'], [number, string]> = {
27
+ not_found: [404, 'not-found'],
28
+ usage: [400, 'bad-request'],
29
+ conflict: [409, 'conflict'],
30
+ }
31
+
32
+ export function createBackgroundJobRoutes(options: BackgroundJobRouteOptions) {
33
+ const { db, problem } = options
34
+ const refused = (error: unknown): Response => {
35
+ if (!(error instanceof BackgroundJobError)) throw error
36
+ const [status, code] = STATUS[error.kind]
37
+ return problem(status, {
38
+ code,
39
+ title: error.message,
40
+ ...(error.hint ? { detail: error.hint } : {}),
41
+ })
42
+ }
43
+
44
+ return {
45
+ /** The capability these routes add to discovery. */
46
+ capabilities: ['background-jobs'],
47
+
48
+ /** Whether a principal may see and retry jobs: the Settings section, as the dashboard. */
49
+ may: (principal: Principal) => !principal.ci && hasSection(principal, 'settings'),
50
+
51
+ /** Answers one of these routes, or undefined when `what` is none of them. */
52
+ async handle(
53
+ request: Request,
54
+ url: URL,
55
+ principal: Principal,
56
+ what: string,
57
+ ): Promise<Response | undefined> {
58
+ const route = /^background-jobs(?:\/([^/]+)(?:\/(retry))?)?$/.exec(what)
59
+ if (!route) return undefined
60
+ if (principal.ci)
61
+ return problem(403, {
62
+ code: 'ci-cannot-manage-jobs',
63
+ title: 'Background jobs need a person',
64
+ detail: 'Sign in as yourself: CI cannot do this.',
65
+ })
66
+ if (!hasSection(principal, 'settings'))
67
+ return problem(403, { code: 'forbidden', title: 'You may not see background jobs here' })
68
+ const [, named, retry] = route
69
+ try {
70
+ if (!named) {
71
+ if (request.method !== 'GET') return new Response(null, { status: 405 })
72
+ const listed = await listJobs(db, readJobQuery(url.searchParams))
73
+ return Response.json({
74
+ total: listed.total,
75
+ waitingSince: options.waitingSince?.() ?? null,
76
+ items: listed.items,
77
+ })
78
+ }
79
+ const id = decodeURIComponent(named)
80
+ if (!retry) {
81
+ if (request.method !== 'GET') return new Response(null, { status: 405 })
82
+ return Response.json(await jobOf(db, id))
83
+ }
84
+ if (request.method !== 'POST') return new Response(null, { status: 405 })
85
+ const level = options.levelRefusal()
86
+ if (level) return level
87
+ const done = await retryJob(db, id, {
88
+ key: principal.id,
89
+ name: principal.name,
90
+ source: 'request',
91
+ address: { forwardedFor: request.headers.get('x-forwarded-for') },
92
+ })
93
+ return Response.json({ ok: true, ...done })
94
+ } catch (error) {
95
+ return refused(error)
96
+ }
97
+ },
98
+ }
99
+ }
@@ -1,12 +1,21 @@
1
1
  /**
2
- * A developer's sign-ins to remotes (story 108): kept in the operating system's
3
- * keychain (macOS Keychain, Windows Credential Manager, libsecret) through
4
- * `Bun.secrets`, keyed by the remote's origin, never in the site's folder.
5
- * Shared by the CLI's commands and a lazily-fetching local media store.
2
+ * A developer's sign-ins to hosted sites (stories 108, 352): kept in the
3
+ * operating system's keychain (macOS Keychain, Windows Credential Manager,
4
+ * libsecret) through `Bun.secrets`, or on a machine with none in
5
+ * `~/.crombolo/credentials`, readable only by its owner. Keyed by the site's
6
+ * origin, never in a site's folder. Shared by the CLI's commands and a
7
+ * lazily-fetching local media store.
6
8
  */
9
+ import { existsSync, mkdirSync, readFileSync } from 'node:fs'
10
+ import { homedir } from 'node:os'
11
+ import { dirname, join } from 'node:path'
12
+ import { writeFileAtomic } from './atomic-write.ts'
13
+ import { setting } from './settings.ts'
7
14
 
8
15
  export const KEYCHAIN_SERVICE = 'crombolo-remote'
9
16
 
17
+ const keyOf = (origin: string) => new URL(origin).origin
18
+
10
19
  export interface Keychain {
11
20
  get(name: string): Promise<string | null>
12
21
  set(name: string, value: string): Promise<void>
@@ -24,6 +33,107 @@ export function osKeychain(): Keychain {
24
33
  }
25
34
  }
26
35
 
36
+ /** Where sign-ins go on a machine with no keychain: CROMBOLO_CREDENTIALS_FILE, else ~/.crombolo/credentials. */
37
+ export const credentialsFile = (): string =>
38
+ setting('CROMBOLO_CREDENTIALS_FILE') || join(homedir(), '.crombolo', 'credentials')
39
+
40
+ /** Sign-ins in a file only its owner can read: JSON, by origin. */
41
+ export function fileKeychain(file: string = credentialsFile()): Keychain {
42
+ const read = (): Record<string, unknown> => {
43
+ if (!existsSync(file)) return {}
44
+ try {
45
+ return JSON.parse(readFileSync(file, 'utf8')) as Record<string, unknown>
46
+ } catch {
47
+ return {}
48
+ }
49
+ }
50
+ const write = (values: Record<string, unknown>) => {
51
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
52
+ writeFileAtomic(file, `${JSON.stringify(values, null, 2)}\n`, 0o600)
53
+ }
54
+ return {
55
+ get: async (name) => {
56
+ const value = read()[name]
57
+ if (value === undefined) return null
58
+ return typeof value === 'string' ? value : JSON.stringify(value)
59
+ },
60
+ set: async (name, value) => {
61
+ let parsed: unknown = value
62
+ try {
63
+ parsed = JSON.parse(value)
64
+ } catch {
65
+ // Kept as it was given.
66
+ }
67
+ write({ ...read(), [name]: parsed })
68
+ },
69
+ delete: async (name) => {
70
+ const values = read()
71
+ if (!(name in values)) return
72
+ delete values[name]
73
+ write(values)
74
+ },
75
+ }
76
+ }
77
+
78
+ export type KeptIn = 'keychain' | 'file'
79
+
80
+ /** The person's own sign-ins: the keychain, or the credentials file where there is none. */
81
+ export interface UserKeychain extends Keychain {
82
+ /** Where a sign-in saved now is kept. */
83
+ keptIn(): Promise<KeptIn>
84
+ /** Where the sign-in for an origin is kept, when there is one. */
85
+ find(origin: string): Promise<KeptIn | undefined>
86
+ }
87
+
88
+ const PROBE = 'crombolo-keychain-check'
89
+
90
+ /**
91
+ * The keychain when it can be reached, else the credentials file (story 352).
92
+ * CROMBOLO_CREDENTIALS=keychain or file chooses one. A sign-in saved to the
93
+ * file while there was no keychain is still found once there is one.
94
+ */
95
+ export function userKeychain(
96
+ options: { os?: Keychain; file?: string; choice?: string } = {},
97
+ ): UserKeychain {
98
+ const os = options.os ?? osKeychain()
99
+ const file = fileKeychain(options.file)
100
+ const choice = options.choice ?? setting('CROMBOLO_CREDENTIALS')
101
+ if (choice !== undefined && choice !== 'keychain' && choice !== 'file')
102
+ throw new Error(`CROMBOLO_CREDENTIALS is "${choice}": it is keychain or file.`)
103
+ let reachable: Promise<boolean> | undefined
104
+ const osWorks = () =>
105
+ (reachable ??= os.get(PROBE).then(
106
+ () => true,
107
+ () => false,
108
+ ))
109
+ const keptIn = async (): Promise<KeptIn> =>
110
+ choice === 'file' || (choice === undefined && !(await osWorks())) ? 'file' : 'keychain'
111
+ const fromOs = async (name: string) =>
112
+ choice === 'file' || (choice === undefined && !(await osWorks())) ? null : os.get(name)
113
+ return {
114
+ keptIn,
115
+ async find(origin) {
116
+ const name = keyOf(origin)
117
+ if ((await fromOs(name)) !== null) return 'keychain'
118
+ if (choice !== 'keychain' && (await file.get(name)) !== null) return 'file'
119
+ return undefined
120
+ },
121
+ async get(name) {
122
+ const found = await fromOs(name)
123
+ if (found !== null || choice === 'keychain') return found
124
+ return file.get(name)
125
+ },
126
+ async set(name, value) {
127
+ if ((await keptIn()) === 'keychain') await os.set(name, value)
128
+ else await file.set(name, value)
129
+ },
130
+ async delete(name) {
131
+ if (choice !== 'file' && (choice === 'keychain' || (await osWorks()))) await os.delete(name)
132
+ if (choice !== 'keychain') await file.delete(name)
133
+ },
134
+ }
135
+ }
136
+
27
137
  /** A keychain in memory, for tests and machines without one. */
28
138
  export function memoryKeychain(): Keychain {
29
139
  const values = new Map<string, string>()
@@ -49,8 +159,6 @@ export interface RemoteSignIn {
49
159
  user?: string
50
160
  }
51
161
 
52
- const keyOf = (origin: string) => new URL(origin).origin
53
-
54
162
  export async function readSignIn(
55
163
  keychain: Keychain,
56
164
  origin: string,
@@ -0,0 +1,66 @@
1
+ /**
2
+ * The remote protocol's routes for what an extension did (story 362): a page of
3
+ * its activity, the counts and the people it acted for, and the same as a CSV
4
+ * file, as Installed's Activity view reads them, through the core the command
5
+ * line uses. They need the Settings section; CI is refused, since these show
6
+ * who did what.
7
+ */
8
+ import { hasSection, type Principal } from '@crombolo/api-management/domain'
9
+ import type { Db } from '@crombolo/data'
10
+ import { type ActivitySource, activityPath, answerActivity } from './extension-activity.ts'
11
+
12
+ interface Problem {
13
+ code: string
14
+ title: string
15
+ detail?: string
16
+ }
17
+
18
+ export interface ExtensionActivityRouteOptions {
19
+ db: Db
20
+ problem(status: number, body: Problem): Response
21
+ /** How to flush the recorder, and how many days the counts cover. */
22
+ activity: ActivitySource
23
+ }
24
+
25
+ export function createExtensionActivityRoutes(options: ExtensionActivityRouteOptions) {
26
+ const { db, problem } = options
27
+ return {
28
+ /** The capability these routes add to discovery. */
29
+ capabilities: ['extension-activity'],
30
+
31
+ /** Whether a principal may read it: the Settings section, as the Activity view. */
32
+ may: (principal: Principal) => !principal.ci && hasSection(principal, 'settings'),
33
+
34
+ /** Answers one of these routes, or undefined when `what` is none of them. */
35
+ async handle(
36
+ request: Request,
37
+ url: URL,
38
+ principal: Principal,
39
+ what: string,
40
+ ): Promise<Response | undefined> {
41
+ const route = activityPath(what)
42
+ if (!route) return undefined
43
+ if (request.method !== 'GET') return new Response(null, { status: 405 })
44
+ if (principal.ci)
45
+ return problem(403, {
46
+ code: 'ci-cannot-read-activity',
47
+ title: 'Reading what an extension did needs a person',
48
+ detail: 'Sign in as yourself: CI cannot do this.',
49
+ })
50
+ if (!hasSection(principal, 'settings'))
51
+ return problem(403, {
52
+ code: 'forbidden',
53
+ title: 'You may not see what extensions did here',
54
+ })
55
+ return answerActivity(
56
+ db,
57
+ options.activity,
58
+ route.id,
59
+ route.part,
60
+ url.searchParams,
61
+ (status, title) =>
62
+ problem(status, { code: status === 404 ? 'not-found' : 'bad-request', title }),
63
+ )
64
+ },
65
+ }
66
+ }