@crombolo/server 0.55.0 → 0.57.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 (48) hide show
  1. package/package.json +16 -13
  2. package/src/actions.ts +6 -1
  3. package/src/adapters/bundles.ts +72 -6
  4. package/src/adapters/health.ts +30 -1
  5. package/src/bundle-admin.ts +246 -23
  6. package/src/bundle-api.ts +299 -0
  7. package/src/bundle-build.ts +4 -3
  8. package/src/bundle-grants.ts +133 -18
  9. package/src/bundle-install.ts +140 -11
  10. package/src/bundle-sections.ts +49 -4
  11. package/src/bundles.ts +87 -7
  12. package/src/component-templates-api.ts +27 -6
  13. package/src/components.ts +7 -0
  14. package/src/config.ts +56 -3
  15. package/src/content-events.ts +17 -1
  16. package/src/core.ts +219 -15
  17. package/src/created-extension.ts +101 -0
  18. package/src/extension-components.ts +157 -0
  19. package/src/extension-discovery.ts +180 -0
  20. package/src/extension-process.ts +854 -0
  21. package/src/extension-sql.ts +85 -0
  22. package/src/index.ts +21 -0
  23. package/src/marketplace.ts +182 -54
  24. package/src/outbound-address.ts +182 -0
  25. package/src/owner-jobs.ts +7 -1
  26. package/src/ports.ts +8 -0
  27. package/src/provenance.ts +181 -15
  28. package/src/remote.ts +62 -10
  29. package/src/routes.ts +13 -1
  30. package/src/schema.ts +37 -6
  31. package/src/seed/compile.ts +4 -2
  32. package/src/seed/export.ts +1 -1
  33. package/src/seed/values.ts +3 -3
  34. package/src/seo.ts +13 -5
  35. package/src/server.ts +192 -45
  36. package/src/settings.ts +12 -4
  37. package/src/signing-keys.ts +155 -0
  38. package/src/site-content-values.ts +97 -0
  39. package/src/site-content.ts +292 -0
  40. package/src/site-events.ts +65 -0
  41. package/src/site-file.ts +20 -6
  42. package/src/site-public.ts +1 -1
  43. package/src/site-sections.ts +1 -1
  44. package/src/site-services.ts +4 -0
  45. package/src/site-trust.ts +238 -0
  46. package/src/transfer-dashboard.ts +6 -0
  47. package/src/trusted-signers-admin.ts +132 -0
  48. package/src/webhooks.ts +182 -17
@@ -0,0 +1,299 @@
1
+ /**
2
+ * An extension's way to the site's areas (story 308): the Management API, and
3
+ * the CMS's own back-office API, called in this process as the extension.
4
+ *
5
+ * Each permission it was granted allows a set of paths and methods, checked
6
+ * before the call. The API's own validation, permissions, approval workflows and
7
+ * audit then apply. Acting as itself, an extension holds nothing but what its
8
+ * grant gives (least privilege): never an administrator, so its publishes always
9
+ * meet the approval workflows. docs/bundles.md, "Permissions".
10
+ */
11
+ import { AsyncLocalStorage } from 'node:async_hooks'
12
+ import type { Principal } from '@crombolo/api-management'
13
+ import {
14
+ DocumentPermissions,
15
+ FormPermissions,
16
+ MediaPermissions,
17
+ ROOT_ACCESS,
18
+ SECTION_ALIASES,
19
+ } from '@crombolo/core'
20
+
21
+ /** A permission's reach: the paths, under the back office, its methods may call. */
22
+ interface Reach {
23
+ /** `read` is GET and HEAD; `write` is POST, PUT, PATCH and DELETE. */
24
+ methods: 'read' | 'write'
25
+ /** Prefixes of the path after the back office, without a leading slash. */
26
+ paths: readonly string[]
27
+ /** Prefixes inside those that it does not reach. */
28
+ except?: readonly string[]
29
+ }
30
+
31
+ const MANAGEMENT = 'management/api/v1/'
32
+ const PLUGIN = 'crombolo/api/'
33
+
34
+ const management = (...areas: string[]) =>
35
+ areas.flatMap((area) => [
36
+ `${MANAGEMENT}${area}`,
37
+ `${MANAGEMENT}tree/${area}`,
38
+ `${MANAGEMENT}item/${area}`,
39
+ `${MANAGEMENT}collection/${area}`,
40
+ `${MANAGEMENT}filter/${area}`,
41
+ ])
42
+
43
+ const read = (paths: string[], except?: string[]): Reach => ({ methods: 'read', paths, except })
44
+ const write = (paths: string[], except?: string[]): Reach => ({ methods: 'write', paths, except })
45
+
46
+ const CONTENT = [
47
+ ...management('document', 'document-version'),
48
+ `${MANAGEMENT}recycle-bin/document`,
49
+ `${MANAGEMENT}language`,
50
+ ]
51
+ const MEDIA = [
52
+ ...management('media'),
53
+ `${MANAGEMENT}recycle-bin/media`,
54
+ `${MANAGEMENT}imaging`,
55
+ `${MANAGEMENT}temporary-file`,
56
+ ]
57
+ const MEMBERS = management('member', 'member-group')
58
+ const USERS = management('user', 'user-group')
59
+ const FORM_ENTRIES = [`${PLUGIN}forms/entries`]
60
+ const FORMS = [`${PLUGIN}forms`]
61
+ const DICTIONARY = [...management('dictionary'), `${PLUGIN}dictionary`]
62
+ const CONTENT_TYPES = [
63
+ ...management('document-type', 'media-type', 'member-type', 'data-type'),
64
+ `${MANAGEMENT}property-type`,
65
+ ]
66
+ const WEBHOOKS = [...management('webhook'), `${PLUGIN}webhooks`]
67
+ const WORKFLOWS = [`${PLUGIN}approvals`]
68
+ const REDIRECTS = [`${MANAGEMENT}redirect-management`]
69
+
70
+ /** What each permission reaches through `api`; a permission absent here reaches nothing through it. */
71
+ export const API_PERMISSIONS: Readonly<Record<string, readonly Reach[]>> = {
72
+ 'content.read': [read(CONTENT)],
73
+ 'content.write': [write(CONTENT, [`${MANAGEMENT}document/${'public-access'}`])],
74
+ 'media.read': [read(MEDIA)],
75
+ 'media.write': [write(MEDIA)],
76
+ 'members.read': [read(MEMBERS)],
77
+ 'members.write': [write(MEMBERS)],
78
+ 'users.read': [read(USERS, [`${MANAGEMENT}user/current`])],
79
+ 'forms.read': [read(FORMS, FORM_ENTRIES)],
80
+ 'forms.write': [write(FORMS, FORM_ENTRIES)],
81
+ 'formEntries.read': [read(FORM_ENTRIES)],
82
+ 'formEntries.write': [write(FORM_ENTRIES)],
83
+ 'dictionary.read': [read(DICTIONARY)],
84
+ 'dictionary.write': [write(DICTIONARY)],
85
+ 'contentTypes.read': [read(CONTENT_TYPES)],
86
+ 'contentTypes.write': [write(CONTENT_TYPES)],
87
+ 'webhooks.read': [read(WEBHOOKS)],
88
+ 'webhooks.write': [write(WEBHOOKS)],
89
+ 'workflows.read': [read(WORKFLOWS)],
90
+ 'workflows.write': [write(WORKFLOWS)],
91
+ 'redirects.read': [read(REDIRECTS)],
92
+ 'redirects.write': [write(REDIRECTS)],
93
+ }
94
+
95
+ const READING = new Set(['GET', 'HEAD'])
96
+
97
+ /** Whether a path is a prefix's own, or below it: `document` is not `document-type`. */
98
+ const under = (path: string, prefix: string) =>
99
+ path === prefix || path.startsWith(`${prefix}/`) || path.startsWith(`${prefix}?`)
100
+
101
+ /** The permissions that would let `method` reach `path` (after the back office). Pure. */
102
+ export function permissionsFor(method: string, path: string): string[] {
103
+ const kind = READING.has(method.toUpperCase()) ? 'read' : 'write'
104
+ const clean = path.replace(/^\/+/, '')
105
+ return Object.entries(API_PERMISSIONS)
106
+ .filter(([, reaches]) =>
107
+ reaches.some(
108
+ (reach) =>
109
+ reach.methods === kind &&
110
+ reach.paths.some((prefix) => under(clean, prefix)) &&
111
+ !(reach.except ?? []).some((prefix) => under(clean, prefix)),
112
+ ),
113
+ )
114
+ .map(([permission]) => permission)
115
+ }
116
+
117
+ /** The sections a set of permissions needs, for the API's own section checks. */
118
+ const SECTIONS: Readonly<Record<string, string>> = {
119
+ content: SECTION_ALIASES.content,
120
+ media: SECTION_ALIASES.media,
121
+ members: SECTION_ALIASES.members,
122
+ users: SECTION_ALIASES.users,
123
+ forms: SECTION_ALIASES.forms,
124
+ formEntries: SECTION_ALIASES.forms,
125
+ dictionary: SECTION_ALIASES.translation,
126
+ contentTypes: SECTION_ALIASES.settings,
127
+ webhooks: SECTION_ALIASES.settings,
128
+ workflows: SECTION_ALIASES.workflow,
129
+ redirects: SECTION_ALIASES.content,
130
+ }
131
+
132
+ /** The verbs a set of permissions needs, for the API's own permission checks. */
133
+ function verbsOf(granted: ReadonlySet<string>): string[] {
134
+ const verbs = new Set<string>()
135
+ if (granted.has('content.read'))
136
+ for (const verb of [DocumentPermissions.Read, DocumentPermissions.PropertyValueRead])
137
+ verbs.add(verb)
138
+ if (granted.has('content.write'))
139
+ for (const verb of Object.values(DocumentPermissions)) {
140
+ if (verb === DocumentPermissions.Permissions || verb === DocumentPermissions.PublicAccess)
141
+ continue
142
+ verbs.add(verb)
143
+ }
144
+ if (granted.has('media.read')) verbs.add(MediaPermissions.Read)
145
+ if (granted.has('media.write'))
146
+ for (const verb of Object.values(MediaPermissions)) verbs.add(verb)
147
+ if (granted.has('forms.read')) verbs.add(FormPermissions.View)
148
+ if (granted.has('forms.write')) verbs.add(FormPermissions.Manage)
149
+ if (granted.has('formEntries.read')) verbs.add(FormPermissions.EntriesView)
150
+ if (granted.has('formEntries.write')) verbs.add(FormPermissions.EntriesManage)
151
+ return [...verbs]
152
+ }
153
+
154
+ /**
155
+ * The extension acting as itself: what its grant gives and nothing else, never
156
+ * an administrator, on the whole tree and every language. Its id is its own, so
157
+ * the audit names it.
158
+ */
159
+ export function extensionPrincipal(
160
+ bundle: { id: string; name: string },
161
+ granted: readonly string[],
162
+ ): Principal {
163
+ const set = new Set(granted)
164
+ const sections = new Set<string>()
165
+ for (const permission of set) {
166
+ const section = SECTIONS[permission.split('.')[0] as string]
167
+ if (section) sections.add(section)
168
+ }
169
+ const verbs = verbsOf(set)
170
+ return {
171
+ id: `extension:${bundle.id}`,
172
+ userName: `extension:${bundle.id}`,
173
+ name: `Extension ${bundle.name}`,
174
+ email: '',
175
+ isAdmin: false,
176
+ languageIsoCode: undefined,
177
+ avatarUrls: [],
178
+ allowedSections: [...sections],
179
+ permissions: verbs,
180
+ groupKeys: [],
181
+ hasAccessToAllLanguages: true,
182
+ languages: [],
183
+ startNodes: { document: ROOT_ACCESS, media: ROOT_ACCESS, element: ROOT_ACCESS },
184
+ groups: [
185
+ {
186
+ key: `extension:${bundle.id}`,
187
+ alias: `extension-${bundle.id}`,
188
+ defaults: verbs,
189
+ granular: new Map(),
190
+ },
191
+ ],
192
+ }
193
+ }
194
+
195
+ /** A call refused before it was made, naming what would have allowed it. */
196
+ export class ApiRefusedError extends Error {
197
+ override readonly name = 'ApiRefusedError'
198
+ }
199
+
200
+ export interface BundleApi {
201
+ /** Any method, on a path after the back office: `management/api/v1/document/<id>`. */
202
+ request(method: string, path: string, body?: unknown): Promise<Response>
203
+ get(path: string): Promise<Response>
204
+ post(path: string, body?: unknown): Promise<Response>
205
+ put(path: string, body?: unknown): Promise<Response>
206
+ delete(path: string): Promise<Response>
207
+ }
208
+
209
+ /**
210
+ * Who a request made through `api` is, for the length of the call. The request
211
+ * carries a header naming the call with a secret only this process holds, so it
212
+ * survives the request being copied on its way, and no request from outside
213
+ * can claim one.
214
+ */
215
+ const ACTING_HEADER = 'x-crombolo-acting'
216
+ const SECRET = crypto.randomUUID()
217
+ const acting = new Map<string, Principal>()
218
+
219
+ /** The principal an in-process request from an extension carries; undefined for any other request. */
220
+ export function actingPrincipalOf(request: Request): Principal | undefined {
221
+ const value = request.headers.get(ACTING_HEADER)
222
+ if (!value) return undefined
223
+ const [secret, call] = value.split('.')
224
+ return secret === SECRET && call ? acting.get(call) : undefined
225
+ }
226
+
227
+ const calling = new AsyncLocalStorage<string>()
228
+
229
+ /** The extension whose call to `api` is being answered, while it is. */
230
+ export const callingExtension = (): string | undefined => calling.getStore()
231
+
232
+ /**
233
+ * `api` for one extension and caller: refuses what the grant does not cover,
234
+ * then sends the call to the server as `principal`. `dispatch` is the server's
235
+ * own handler, set once the server is built.
236
+ */
237
+ export function createBundleApi(options: {
238
+ bundleId: string
239
+ origin: string
240
+ backOfficePath: string
241
+ granted: () => readonly string[]
242
+ principal: () => Promise<Principal | undefined>
243
+ dispatch: () => ((request: Request) => Promise<Response>) | undefined
244
+ }): BundleApi {
245
+ const base = options.backOfficePath.replace(/\/+$/, '')
246
+ const request = async (method: string, path: string, body?: unknown) => {
247
+ const verb = method.toUpperCase()
248
+ const clean = path.replace(/^\/+/, '')
249
+ const needs = permissionsFor(verb, clean)
250
+ const granted = new Set(options.granted())
251
+ if (!needs.some((permission) => granted.has(permission)))
252
+ throw new ApiRefusedError(
253
+ needs.length > 0
254
+ ? `${options.bundleId} may not ${verb} ${clean}: it needs ${needs.join(' or ')}, which it was not granted.`
255
+ : `${options.bundleId} may not ${verb} ${clean}: no permission reaches it.`,
256
+ )
257
+ const dispatch = options.dispatch()
258
+ if (!dispatch) throw new ApiRefusedError('The site is not answering yet.')
259
+ const principal = await options.principal()
260
+ if (!principal) throw new ApiRefusedError(`${options.bundleId} has no one to act as.`)
261
+ const call = crypto.randomUUID()
262
+ const sent = new Request(`${options.origin}${base}/${clean}`, {
263
+ method: verb,
264
+ headers: {
265
+ [ACTING_HEADER]: `${SECRET}.${call}`,
266
+ ...(body === undefined ? {} : { 'content-type': 'application/json' }),
267
+ },
268
+ body: body === undefined ? undefined : JSON.stringify(body),
269
+ })
270
+ acting.set(call, principal)
271
+ try {
272
+ return await calling.run(options.bundleId, () => dispatch(sent))
273
+ } finally {
274
+ acting.delete(call)
275
+ }
276
+ }
277
+ return {
278
+ request,
279
+ get: (path) => request('GET', path),
280
+ post: (path, body) => request('POST', path, body),
281
+ put: (path, body) => request('PUT', path, body),
282
+ delete: (path) => request('DELETE', path),
283
+ }
284
+ }
285
+
286
+ const KEY = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
287
+
288
+ /**
289
+ * Whom an `actAs` grant names, as stored: `installer` becomes the installing
290
+ * user's key, `caller` stays, and `user:<key>` names a user. Null when no choice
291
+ * was given, or one it cannot be.
292
+ */
293
+ export function actAsChoice(value: unknown, installerKey?: string): string | null {
294
+ if (value === 'caller') return 'caller'
295
+ if (value === 'installer') return installerKey ? `installer:${installerKey}` : null
296
+ if (typeof value === 'string' && value.startsWith('user:') && KEY.test(value.slice(5)))
297
+ return value.toLowerCase()
298
+ return null
299
+ }
@@ -41,7 +41,7 @@ export interface BundleBuildOptions {
41
41
  code?: readonly string[]
42
42
  /**
43
43
  * Carry the seed's media files (story 195). On unless turned off, so seeding
44
- * a site still brings its media; `crombolo bundle build` turns it off unless
44
+ * a site still brings its media; `crombolo site build` turns it off unless
45
45
  * `--with-media` is passed.
46
46
  */
47
47
  media?: boolean
@@ -150,7 +150,7 @@ export async function buildBundleFromDirectory(
150
150
  manifest: {
151
151
  ...seed.set.manifest,
152
152
  label: config.siteName,
153
- createdBy: 'crombolo bundle build',
153
+ createdBy: 'crombolo site build',
154
154
  },
155
155
  }
156
156
  const publicFiles = publicSources(config.publicDir)
@@ -159,7 +159,7 @@ export async function buildBundleFromDirectory(
159
159
  set,
160
160
  options.media === false ? new Map() : seed.blobs,
161
161
  [...sections, ...(code ? readCodeFiles(dir, code.paths) : [])],
162
- { public: publicFiles },
162
+ { public: publicFiles, bundleType: 'site' },
163
163
  ),
164
164
  {
165
165
  name,
@@ -169,6 +169,7 @@ export async function buildBundleFromDirectory(
169
169
  private: true,
170
170
  // As `release:version` writes it into every committed bundle.
171
171
  peerRange: `>=${VERSION}`,
172
+ bundleType: 'site',
172
173
  },
173
174
  )
174
175
  return {
@@ -6,21 +6,37 @@
6
6
  * docs/bundles.md, "Permissions".
7
7
  */
8
8
  import {
9
+ askedPermissions,
9
10
  type BundlePackage,
10
11
  type BundlePermission,
12
+ type DeclaredPermission,
11
13
  describePermissions,
14
+ isSchema3Field,
12
15
  } from '@crombolo/backoffice-host/registry'
13
16
  import { type BundleGrant, BundleGrantRepository, type Db } from '@crombolo/data'
17
+ import { API_PERMISSIONS } from './bundle-api.ts'
14
18
 
15
19
  /** The permissions each capability serves; `log` needs none. */
16
20
  export const CAPABILITY_PERMISSIONS: Record<string, readonly BundlePermission[]> = {
17
21
  redirects: ['redirects.read', 'redirects.write'],
18
- documents: ['documents.read'],
22
+ documents: ['content.read'],
19
23
  identityProviders: ['identityProviders.read', 'identityProviders.write'],
20
24
  media: ['media.read', 'media.write', 'member.delegate'],
21
25
  log: [],
26
+ // Story 308: the areas through the Management API, and requests out.
27
+ api: Object.keys(API_PERMISSIONS) as BundlePermission[],
28
+ fetch: ['http.outbound'],
22
29
  }
23
30
 
31
+ /** Permissions a bundle uses by what it declares, not by a capability: checked at boot instead. */
32
+ const DECLARATION_PERMISSIONS: ReadonlySet<string> = new Set([
33
+ 'events.content',
34
+ 'routes.public',
35
+ 'actAs',
36
+ 'templates',
37
+ 'member.delegate',
38
+ ])
39
+
24
40
  /** The permission each capability method needs. */
25
41
  const METHOD_PERMISSIONS: Record<string, Record<string, BundlePermission>> = {
26
42
  redirects: {
@@ -30,7 +46,8 @@ const METHOD_PERMISSIONS: Record<string, Record<string, BundlePermission>> = {
30
46
  replace: 'redirects.write',
31
47
  remove: 'redirects.write',
32
48
  },
33
- documents: { url: 'documents.read' },
49
+ documents: { url: 'content.read' },
50
+ fetch: { fetch: 'http.outbound' },
34
51
  identityProviders: {
35
52
  list: 'identityProviders.read',
36
53
  test: 'identityProviders.read',
@@ -48,9 +65,24 @@ const METHOD_PERMISSIONS: Record<string, Record<string, BundlePermission>> = {
48
65
  },
49
66
  }
50
67
 
51
- /** The permissions a package declares. */
68
+ /**
69
+ * What a package declares: each permission, its reason and its origins. Schema
70
+ * 3 listed names, read here in schema 4's terms, `documents.read` as
71
+ * `content.read`, so an extension already installed keeps working (story 308).
72
+ */
73
+ export const declaredEntries = (pkg: BundlePackage | undefined): DeclaredPermission[] =>
74
+ askedPermissions(pkg?.field)
75
+
76
+ /** The permissions a package declares, by name. */
52
77
  export const declaredPermissions = (pkg: BundlePackage | undefined): string[] =>
53
- Array.isArray(pkg?.field.permissions) ? [...(pkg?.field.permissions ?? [])] : []
78
+ declaredEntries(pkg).map((entry) => entry.permission)
79
+
80
+ /** The origins its `http.outbound` names; none when it asks for none. */
81
+ export const declaredOrigins = (pkg: BundlePackage | undefined): string[] =>
82
+ declaredEntries(pkg).find((entry) => entry.permission === 'http.outbound')?.origins ?? []
83
+
84
+ /** Whether it was written before permissions said why (story 308). */
85
+ export const isSchema3 = (pkg: BundlePackage | undefined): boolean => isSchema3Field(pkg?.field)
54
86
 
55
87
  /**
56
88
  * Why a bundle's capabilities and its declared permissions disagree: a
@@ -61,6 +93,8 @@ export function permissionProblems(
61
93
  label: string,
62
94
  capabilities: readonly string[],
63
95
  declared: readonly string[],
96
+ /** It has back-office screens, which `http.outbound` lets reach its origins too (story 313). */
97
+ screens = false,
64
98
  ): string[] {
65
99
  const problems: string[] = []
66
100
  const has = new Set(declared)
@@ -78,6 +112,8 @@ export function permissionProblems(
78
112
  )
79
113
  }
80
114
  for (const permission of declared) {
115
+ if (DECLARATION_PERMISSIONS.has(permission)) continue
116
+ if (permission === 'http.outbound' && screens) continue
81
117
  const used = capabilities.some((c) => CAPABILITY_PERMISSIONS[c]?.includes(permission as never))
82
118
  if (!used)
83
119
  problems.push(
@@ -130,33 +166,77 @@ export interface BundleGrantState {
130
166
  bundleId: string
131
167
  packageName: string
132
168
  version: string
133
- declared: { permission: string; allows: string }[]
134
- /** On unless an administrator disabled it: the site's code is its approval. */
169
+ declared: { permission: string; allows: string; reason: string | null; origins?: string[] }[]
170
+ /** It runs: granted what the installed version asks for, and not turned off (story 309). */
135
171
  on: boolean
172
+ /**
173
+ * Why, in a word: `on`; `off`, turned off by an administrator; `waiting`, its
174
+ * version asks for more than was granted; `not-granted`, never granted.
175
+ */
176
+ status: 'on' | 'off' | 'waiting' | 'not-granted'
177
+ /** With `waiting`: what it asks for that the grant does not cover. */
178
+ missing: string[]
136
179
  grant: BundleGrant | undefined
137
180
  /** Who disabled it, when it is off. */
138
181
  disabledBy: string | null
139
182
  }
140
183
 
184
+ /**
185
+ * What the installed version asks for that a grant does not cover (story 309):
186
+ * permissions, `http.outbound` origins, and whom `actAs` acts for. Empty when it
187
+ * covers it all. Pure.
188
+ */
189
+ export function grantGaps(pkg: BundlePackage, grant: BundleGrant | undefined): string[] {
190
+ if (!grant) return declaredPermissions(pkg)
191
+ // A schema 3 grant names `documents.read`, which is `content.read` now (story 308).
192
+ const has = new Set(grant.permissions.map((p) => (p === 'documents.read' ? 'content.read' : p)))
193
+ const gaps = declaredPermissions(pkg).filter((permission) => !has.has(permission))
194
+ for (const origin of declaredOrigins(pkg))
195
+ if (!grant.origins.includes(origin)) gaps.push(`http.outbound ${origin}`)
196
+ if (declaredPermissions(pkg).includes('actAs') && !grant.actAs && !gaps.includes('actAs'))
197
+ gaps.push('actAs: whom it acts for')
198
+ return gaps
199
+ }
200
+
141
201
  /** Whether a bundle may run, what it was approved for, and the switch to stop one. */
142
202
  export interface BundleGrants {
143
203
  /** Reads the rows again, as a node elsewhere may have changed them. */
144
204
  refresh(): Promise<void>
145
205
  isOn(bundleId: string): boolean
206
+ /** What it may use now: what it asks for while it is on, nothing otherwise (story 309). */
207
+ granted(bundleId: string): string[]
208
+ /**
209
+ * Narrows a grant to what the installed version asks for, when it asks for no
210
+ * more than was granted: a version that asks for less stays on. True when changed.
211
+ */
212
+ narrow(pkg: BundlePackage): Promise<boolean>
146
213
  state(pkg: BundlePackage): BundleGrantState
147
- /** Records what a bundle is approved for, and by whom; true when that changed. */
148
- grant(pkg: BundlePackage, by: string | null): Promise<boolean>
214
+ /**
215
+ * Records what a bundle is approved for, and by whom; true when that changed.
216
+ * `actAs` is whom it acts for, when it asks to act for a user (story 308).
217
+ */
218
+ grant(
219
+ pkg: BundlePackage,
220
+ by: string | null,
221
+ options?: { actAs?: string | null },
222
+ ): Promise<boolean>
149
223
  disable(pkg: BundlePackage, by: string | null): Promise<BundleGrantState>
150
224
  enable(pkg: BundlePackage): Promise<BundleGrantState>
151
225
  }
152
226
 
153
227
  /** Whether a recorded approval already holds this version and list. */
154
- export function approvalHolds(pkg: BundlePackage, grant: BundleGrant | undefined): boolean {
228
+ export function approvalHolds(
229
+ pkg: BundlePackage,
230
+ grant: BundleGrant | undefined,
231
+ actAs?: string | null,
232
+ ): boolean {
155
233
  if (!grant || grant.version !== pkg.version) return false
156
- const declared = declaredPermissions(pkg)
234
+ const same = (a: readonly string[], b: readonly string[]) =>
235
+ a.length === b.length && a.every((entry) => b.includes(entry))
157
236
  return (
158
- grant.permissions.length === declared.length &&
159
- declared.every((permission) => grant.permissions.includes(permission))
237
+ same(grant.permissions, declaredPermissions(pkg)) &&
238
+ same(grant.origins, declaredOrigins(pkg)) &&
239
+ (actAs === undefined || grant.actAs === actAs)
160
240
  )
161
241
  }
162
242
 
@@ -185,12 +265,22 @@ export function createBundleGrants(options: {
185
265
  }
186
266
  const stateOf = (pkg: BundlePackage): BundleGrantState => {
187
267
  const grant = grants.get(pkg.id)
268
+ const missing = grantGaps(pkg, grant)
269
+ const status = grant?.disabledAt
270
+ ? 'off'
271
+ : !grant?.recorded
272
+ ? 'not-granted'
273
+ : missing.length > 0
274
+ ? 'waiting'
275
+ : 'on'
188
276
  return {
189
277
  bundleId: pkg.id,
190
278
  packageName: pkg.packageName,
191
279
  version: pkg.version,
192
- declared: describePermissions(declaredPermissions(pkg)),
193
- on: !grant?.disabledAt,
280
+ declared: describePermissions(declaredEntries(pkg)),
281
+ on: status === 'on',
282
+ status,
283
+ missing: status === 'waiting' ? missing : [],
194
284
  grant,
195
285
  disabledBy: grant?.disabledAt ? grant.disabledBy : null,
196
286
  }
@@ -200,19 +290,44 @@ export function createBundleGrants(options: {
200
290
  refresh: read,
201
291
  isOn(bundleId) {
202
292
  stale()
203
- return options.packages().has(bundleId) && !grants.get(bundleId)?.disabledAt
293
+ const pkg = options.packages().get(bundleId)
294
+ return pkg !== undefined && stateOf(pkg).on
295
+ },
296
+ granted(bundleId) {
297
+ stale()
298
+ const pkg = options.packages().get(bundleId)
299
+ return pkg && stateOf(pkg).on ? declaredPermissions(pkg) : []
300
+ },
301
+ async narrow(pkg) {
302
+ const grant = grants.get(pkg.id)
303
+ if (!grant?.recorded || grantGaps(pkg, grant).length > 0 || approvalHolds(pkg, grant))
304
+ return false
305
+ await repository.grant({
306
+ bundleId: pkg.id,
307
+ packageName: pkg.packageName,
308
+ version: pkg.version,
309
+ permissions: declaredPermissions(pkg),
310
+ origins: declaredOrigins(pkg),
311
+ actAs: declaredPermissions(pkg).includes('actAs') ? grant.actAs : null,
312
+ grantedBy: grant.grantedBy,
313
+ })
314
+ await read()
315
+ return true
204
316
  },
205
317
  state(pkg) {
206
318
  stale()
207
319
  return stateOf(pkg)
208
320
  },
209
- async grant(pkg, by) {
210
- if (approvalHolds(pkg, grants.get(pkg.id))) return false
321
+ async grant(pkg, by, options = {}) {
322
+ if (approvalHolds(pkg, grants.get(pkg.id), options.actAs)) return false
323
+ const asks = declaredPermissions(pkg)
211
324
  await repository.grant({
212
325
  bundleId: pkg.id,
213
326
  packageName: pkg.packageName,
214
327
  version: pkg.version,
215
- permissions: declaredPermissions(pkg),
328
+ permissions: asks,
329
+ origins: declaredOrigins(pkg),
330
+ actAs: asks.includes('actAs') ? (options.actAs ?? grants.get(pkg.id)?.actAs ?? null) : null,
216
331
  grantedBy: by,
217
332
  })
218
333
  await read()