@crombolo/server 0.63.0 → 0.65.1

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/status.ts CHANGED
@@ -31,6 +31,7 @@ import { loadSchemaDirectory } from '@crombolo/schema'
31
31
  import { type CromboloConfig, describeDatabase, VERSION } from './config.ts'
32
32
  import { BundleConfigurationError, pendingTablesSteps, tablesChainsFor } from './custom-tables.ts'
33
33
  import { type EmailAvailability, emailAvailability, resolveEmailPort } from './email.ts'
34
+ import { siteEmail } from './email-settings.ts'
34
35
  import { formTypesFor } from './form-types.ts'
35
36
  import { assertViewRuntime } from './view-runtime.ts'
36
37
 
@@ -197,6 +198,8 @@ export async function siteStatus(config: CromboloConfig): Promise<SiteStatus> {
197
198
  status.problems.push('the database is not installed yet; `crombolo start` will install it')
198
199
  return status
199
200
  }
201
+ // Story 340: e-mail may be set up in Settings, which only the database knows.
202
+ status.email = emailAvailability(await siteEmail(db, config).catch(() => undefined))
200
203
  if (status.framework.pending.length > 0 && !config.development)
201
204
  status.problems.push(
202
205
  `${status.framework.pending.length} framework migration(s) pending: run \`crombolo upgrade\``,
package/src/telemetry.ts CHANGED
@@ -468,9 +468,16 @@ export function tracedDb(db: Db): Db {
468
468
  /** The site's e-mail with each message a span: its provider and outcome, never its addresses. */
469
469
  export function tracedEmail<T extends EmailPort | undefined>(email: T): T {
470
470
  if (!email) return email
471
+ // Getters, and `refresh` passed through: e-mail set up in Settings changes under it (story 340).
472
+ const refresh = (email as { refresh?: () => Promise<void> }).refresh
471
473
  return {
472
- description: email.description,
473
- provider: email.provider,
474
+ get description() {
475
+ return email.description
476
+ },
477
+ get provider() {
478
+ return email.provider
479
+ },
480
+ ...(refresh ? { refresh: () => refresh.call(email) } : {}),
474
481
  send: (message) =>
475
482
  inSpan(
476
483
  'email send',
@@ -5,9 +5,12 @@
5
5
  * site's own key, are shown and never removed here. Settings, the CLI and the
6
6
  * back-office endpoint share it.
7
7
  */
8
+ import { createExtensionRegistry, type ExtensionRegistry } from '@crombolo/backoffice-host/registry'
8
9
  import { type Db, TrustedSignerRepository } from '@crombolo/data'
9
10
  import { recordAudit } from './adapters/audit.ts'
11
+ import { type BundleGrants, createBundleGrants } from './bundle-grants.ts'
10
12
  import type { CromboloConfig } from './config.ts'
13
+ import { switchOffUntrusted } from './grant-trust.ts'
11
14
  import { readPublicKey } from './signing-keys.ts'
12
15
  import { type TrustEntry, trustedSigners } from './site-trust.ts'
13
16
 
@@ -21,14 +24,42 @@ export interface SignerActor {
21
24
  }
22
25
 
23
26
  export type SignerOutcome =
24
- | { ok: true; entry?: TrustEntry }
27
+ | {
28
+ ok: true
29
+ entry?: TrustEntry
30
+ /** Extensions switched off as their signer was removed, by name (story 335). */
31
+ switchedOff?: string[]
32
+ }
25
33
  | { ok: false; status: number; message: string }
26
34
 
35
+ /** What removing a signer re-checks: the server's own, or this site's, read here. */
36
+ export interface SignerChecks {
37
+ extensions: ExtensionRegistry
38
+ grants: Pick<BundleGrants, 'granted' | 'isOn' | 'state' | 'forget'>
39
+ /** Brings a switched-off extension's process to its grant, where a server runs here (story 346). */
40
+ changed?: (id: string) => Promise<unknown>
41
+ }
42
+
27
43
  /** `org/repo`, `org/*`, or either `@` a ref pattern such as `v*`. */
28
44
  const SOURCE = /^[A-Za-z0-9_.-]+\/(\*|[A-Za-z0-9_.-]+)(@[A-Za-z0-9_.*/-]+)?$/
29
45
 
30
- export function createTrustedSignersAdmin(db: Db, config: CromboloConfig) {
46
+ export function createTrustedSignersAdmin(
47
+ db: Db,
48
+ config: CromboloConfig,
49
+ options: { checks?: SignerChecks } = {},
50
+ ) {
31
51
  const repo = new TrustedSignerRepository(db)
52
+ /** The running server's registry and grants, or this site's, read from its files and database. */
53
+ const checks = async (): Promise<SignerChecks> => {
54
+ if (options.checks) return options.checks
55
+ const extensions = createExtensionRegistry(config.siteDir, { cache: false })
56
+ const grants = createBundleGrants({
57
+ db,
58
+ packages: () => new Map(extensions.bundles().bundles.map((pkg) => [pkg.id, pkg])),
59
+ })
60
+ await grants.refresh()
61
+ return { extensions, grants }
62
+ }
32
63
  const audit = (actor: SignerActor, action: string, name: string, detail: string | null) =>
33
64
  recordAudit(db, {
34
65
  category: 'system',
@@ -124,7 +155,12 @@ export function createTrustedSignersAdmin(db: Db, config: CromboloConfig) {
124
155
  found.name,
125
156
  found.fingerprint ? `${found.kind} key ${found.fingerprint}` : `builds of ${found.source}`,
126
157
  )
127
- return { ok: true }
158
+ // Story 335: what it vouched for loses its upper level now, not at the next start.
159
+ const { extensions, grants, changed } = await checks()
160
+ const ids = await switchOffUntrusted(db, config, extensions, grants, 'untrusted')
161
+ for (const switched of ids) await changed?.(switched)
162
+ const names = new Map(extensions.bundles().bundles.map((pkg) => [pkg.id, pkg.name]))
163
+ return { ok: true, switchedOff: ids.map((id) => names.get(id) ?? id) }
128
164
  },
129
165
  }
130
166
  }
package/src/view-as.ts ADDED
@@ -0,0 +1,95 @@
1
+ /**
2
+ * An administrator's back-office session seen as user groups, for up to an hour
3
+ * (story 314). `<plugin>/api/view-as` says whether this session is (GET), starts
4
+ * it (POST `{ groups }`) and switches back (DELETE). docs/backoffice-hosting.md,
5
+ * "Viewing as a group".
6
+ */
7
+ import type { AuthService, ResolvedIdentity, ViewingAs } from '@crombolo/auth'
8
+ import { currentAuditContext, type Db, UserGroupRepository } from '@crombolo/data'
9
+ import { recordAudit } from './adapters/audit.ts'
10
+
11
+ export interface ViewAsStatus {
12
+ /** What this session is viewing as, or null when it is its user's own. */
13
+ viewing: { groups: Array<{ key: string; name: string }>; until: string } | null
14
+ /** Whether this person may view as groups: an administrator in their own right. */
15
+ allowed: boolean
16
+ /** The groups to choose from, for one who may. */
17
+ groups: Array<{ key: string; name: string }>
18
+ }
19
+
20
+ const named = (view: ViewingAs) => view.groups.map((g) => g.name).join(', ')
21
+
22
+ export function createViewAs(db: Db, auth: Pick<AuthService, 'startViewing' | 'stopViewing'>) {
23
+ const status = async (
24
+ identity: ResolvedIdentity,
25
+ viewing: ViewingAs | undefined,
26
+ ): Promise<ViewAsStatus> => {
27
+ // Viewing as groups is only ever on for an administrator, whatever the groups are.
28
+ const allowed = identity.isAdmin || identity.viewingAs !== undefined
29
+ return {
30
+ viewing: viewing ? { groups: viewing.groups, until: viewing.until.toISOString() } : null,
31
+ allowed,
32
+ groups: allowed
33
+ ? (await new UserGroupRepository(db).all()).map((g) => ({ key: g.key, name: g.name }))
34
+ : [],
35
+ }
36
+ }
37
+
38
+ const audit = (
39
+ identity: ResolvedIdentity,
40
+ action: string,
41
+ detail: string,
42
+ client: { ipAddress: string | null; forwardedFor: string | null },
43
+ ) => {
44
+ // The entry names the groups itself; the request's own view is not added to it.
45
+ const context = currentAuditContext()
46
+ if (context) context.viewing = undefined
47
+ return recordAudit(db, {
48
+ category: 'permission',
49
+ action,
50
+ source: 'request',
51
+ userKey: identity.user.key,
52
+ userName: identity.user.userName,
53
+ entityType: 'User',
54
+ entityKey: identity.user.key,
55
+ entityName: identity.user.userName,
56
+ detail,
57
+ ...client,
58
+ })
59
+ }
60
+
61
+ return {
62
+ async handle(
63
+ request: Request,
64
+ identity: ResolvedIdentity,
65
+ client: { ipAddress: string | null; forwardedFor: string | null },
66
+ ): Promise<Response> {
67
+ if (request.method === 'GET') return Response.json(await status(identity, identity.viewingAs))
68
+ if (request.method === 'DELETE') {
69
+ const was = await auth.stopViewing(identity.sessionId)
70
+ if (was) await audit(identity, 'Switched back', `from viewing as ${named(was)}`, client)
71
+ return Response.json(await status(identity, undefined))
72
+ }
73
+ if (request.method === 'POST') {
74
+ const body = (await request.json().catch(() => ({}))) as { groups?: unknown }
75
+ const keys = Array.isArray(body?.groups)
76
+ ? body.groups.filter((k): k is string => typeof k === 'string')
77
+ : []
78
+ const started = await auth.startViewing(identity.sessionId, keys)
79
+ if (started === 'refused')
80
+ return Response.json(
81
+ { message: 'Only an administrator can view the back office as a group.' },
82
+ { status: 403 },
83
+ )
84
+ if (started === 'no-groups')
85
+ return Response.json({ message: 'Choose at least one group.' }, { status: 400 })
86
+ await audit(identity, 'Started viewing as', named(started), client)
87
+ return Response.json(await status(identity, started))
88
+ }
89
+ return new Response('Method Not Allowed', {
90
+ status: 405,
91
+ headers: { allow: 'GET, POST, DELETE' },
92
+ })
93
+ },
94
+ }
95
+ }
package/src/zip.ts CHANGED
@@ -1,13 +1,13 @@
1
1
  /**
2
- * A minimal zip writer, because a created package is a zip and nothing else
3
- * here needs one (`docs/bundles.md`).
2
+ * A minimal zip writer, because a created package is a zip (`docs/bundles.md`),
3
+ * and a bounded reader, for a schema uploaded in Settings (story 342).
4
4
  *
5
5
  * No dependency: `node:zlib` provides `deflateRawSync` and `crc32`, which is
6
6
  * everything the format needs. Entries are written in the order given, each
7
7
  * stored if deflating does not make it smaller, and timestamps are fixed at the
8
8
  * epoch the format starts from so the same selection zips to the same bytes.
9
9
  */
10
- import { crc32, deflateRawSync } from 'node:zlib'
10
+ import { crc32, deflateRawSync, inflateRawSync } from 'node:zlib'
11
11
 
12
12
  export interface ZipEntry {
13
13
  /** The path inside the archive, `/`-separated and never absolute. */
@@ -150,3 +150,86 @@ export function writeZip(entries: readonly ZipEntry[]): Uint8Array<ArrayBuffer>
150
150
  out.u16(0)
151
151
  return out.concat()
152
152
  }
153
+
154
+ export class ZipError extends Error {}
155
+
156
+ export interface ZipLimits {
157
+ /** The most entries an archive may hold. */
158
+ maxEntries: number
159
+ /** The most bytes one entry may unpack to. */
160
+ maxEntryBytes: number
161
+ /** The most bytes every entry together may unpack to. */
162
+ maxTotalBytes: number
163
+ }
164
+
165
+ /**
166
+ * The files in an archive, read through its central directory as an unzip tool
167
+ * does. Directories are left out. Anything this writer would not write, an
168
+ * encrypted or unknown entry, or one past the limits, is refused rather than
169
+ * guessed at, so an upload can't unpack to more than the limits say.
170
+ */
171
+ export function readZip(archive: Uint8Array, limits: ZipLimits): ZipEntry[] {
172
+ const view = new DataView(archive.buffer, archive.byteOffset, archive.byteLength)
173
+ const decoder = new TextDecoder('utf-8', { fatal: true })
174
+ let end = archive.length - 22
175
+ const floor = Math.max(0, archive.length - 22 - 0xffff)
176
+ while (end >= floor && view.getUint32(end, true) !== END_OF_CENTRAL) end -= 1
177
+ if (end < floor) throw new ZipError('This is not a zip file.')
178
+
179
+ const count = view.getUint16(end + 10, true)
180
+ const centralOffset = view.getUint32(end + 16, true)
181
+ if (count > limits.maxEntries)
182
+ throw new ZipError(`It holds more than ${limits.maxEntries} files.`)
183
+
184
+ const entries: ZipEntry[] = []
185
+ let total = 0
186
+ let cursor = centralOffset
187
+ for (let index = 0; index < count; index += 1) {
188
+ if (cursor + 46 > archive.length || view.getUint32(cursor, true) !== CENTRAL_HEADER)
189
+ throw new ZipError('The zip file is damaged.')
190
+ const flags = view.getUint16(cursor + 8, true)
191
+ const method = view.getUint16(cursor + 10, true)
192
+ const compressedSize = view.getUint32(cursor + 20, true)
193
+ const size = view.getUint32(cursor + 24, true)
194
+ const nameLength = view.getUint16(cursor + 28, true)
195
+ const extraLength = view.getUint16(cursor + 30, true)
196
+ const commentLength = view.getUint16(cursor + 32, true)
197
+ const localOffset = view.getUint32(cursor + 42, true)
198
+ let path: string
199
+ try {
200
+ path = decoder.decode(archive.subarray(cursor + 46, cursor + 46 + nameLength))
201
+ } catch {
202
+ throw new ZipError('A file in the zip has a name that is not readable text.')
203
+ }
204
+ cursor += 46 + nameLength + extraLength + commentLength
205
+ if (path.endsWith('/')) continue
206
+ if (flags & 0x1) throw new ZipError(`"${path}" is encrypted.`)
207
+ if (method !== STORED && method !== DEFLATED)
208
+ throw new ZipError(`"${path}" is compressed in a way this can't read.`)
209
+ if (size > limits.maxEntryBytes) throw new ZipError(`"${path}" is too large.`)
210
+ total += size
211
+ if (total > limits.maxTotalBytes) throw new ZipError('The files in it are too large together.')
212
+
213
+ if (localOffset + 30 > archive.length || view.getUint32(localOffset, true) !== LOCAL_HEADER)
214
+ throw new ZipError('The zip file is damaged.')
215
+ const start =
216
+ localOffset +
217
+ 30 +
218
+ view.getUint16(localOffset + 26, true) +
219
+ view.getUint16(localOffset + 28, true)
220
+ if (start + compressedSize > archive.length) throw new ZipError('The zip file is damaged.')
221
+ const stored = archive.subarray(start, start + compressedSize)
222
+ let bytes: Uint8Array
223
+ try {
224
+ bytes =
225
+ method === STORED
226
+ ? stored.slice()
227
+ : new Uint8Array(inflateRawSync(stored, { maxOutputLength: limits.maxEntryBytes }))
228
+ } catch {
229
+ throw new ZipError(`"${path}" could not be unpacked.`)
230
+ }
231
+ if (bytes.length !== size) throw new ZipError('The zip file is damaged.')
232
+ entries.push({ path, bytes })
233
+ }
234
+ return entries
235
+ }