@crombolo/server 0.63.0 → 0.64.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.
@@ -5,18 +5,21 @@
5
5
  * `content` commands read `--set`; and stored values back into that shorthand,
6
6
  * as `content export` and `content show` write them.
7
7
  */
8
- import { type ContentTypeAggregate, dateFromText, normaliseUuid } from '@crombolo/core'
8
+ import {
9
+ type Block,
10
+ type ContentTypeAggregate,
11
+ dateFromText,
12
+ isBlockValue,
13
+ normaliseUuid,
14
+ readBlocks,
15
+ SINGLE_BLOCK_EDITOR_ALIAS,
16
+ } from '@crombolo/core'
9
17
  import { ContentTypeRepository, DataTypeRepository, type Db, looksLikeKey } from '@crombolo/data'
10
18
  import { blockKey, pickKey } from './keys.ts'
11
19
 
12
20
  const isRecord = (value: unknown): value is Record<string, unknown> =>
13
21
  typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Date)
14
22
 
15
- const BLOCK_LAYOUT = {
16
- 'Umbraco.BlockList': 'Umbraco.BlockList',
17
- 'Umbraco.BlockGrid': 'Umbraco.BlockGrid',
18
- } as const
19
-
20
23
  /** A block's alias: a name a view or a command picks it out by (story 253). */
21
24
  export const BLOCK_ALIAS = /^[A-Za-z][A-Za-z0-9_-]*$/
22
25
 
@@ -136,58 +139,91 @@ export function valueWriter(lookup: SchemaLookup, refs: ValueRefs) {
136
139
  return { ok: true, data: { key, contentTypeKey: type.key, values: values.value } }
137
140
  }
138
141
 
142
+ /**
143
+ * Blocks from their shorthand: a list of `{ type, alias, values, settings }`,
144
+ * a grid block's `areas` as `[{ key, blocks = [ … ] }]`, and a Single Block's one
145
+ * block as a table (story 345). A value already in the stored shape passes.
146
+ */
139
147
  const blocks = async (
140
- editor: keyof typeof BLOCK_LAYOUT,
148
+ editor: string,
141
149
  raw: unknown,
142
150
  owner: string,
143
151
  where: string,
144
152
  ): Promise<Converted> => {
153
+ const single = editor === SINGLE_BLOCK_EDITOR_ALIAS
154
+ if (isRecord(raw) && 'layout' in raw) return { ok: true, value: raw }
155
+ if (single && isRecord(raw)) raw = [raw]
156
+ if (single && (raw === null || raw === undefined)) raw = []
145
157
  if (!Array.isArray(raw)) {
146
- if (isRecord(raw) && 'layout' in raw) return { ok: true, value: raw }
147
- return fail('blocks are a list of { type = "<element alias>", values = { … } }')
158
+ return fail(
159
+ single
160
+ ? 'a Single Block is one { type = "<element alias>", values = { … } }'
161
+ : 'blocks are a list of { type = "<element alias>", values = { … } }',
162
+ )
148
163
  }
149
- const layout: Record<string, unknown>[] = []
164
+ if (single && raw.length > 1) return fail('a Single Block holds one block')
150
165
  const contentData: unknown[] = []
151
166
  const settingsData: unknown[] = []
152
- const aliases = new Set<string>()
153
- for (const [index, entry] of raw.entries()) {
154
- if (!isRecord(entry)) return fail(`block ${index + 1} has no type`)
155
- const content = await element(entry, owner, `${where}/${index}`, `block ${index + 1}`)
156
- if (!content.ok) return fail(content.message)
157
- contentData.push(content.data)
158
- const item: Record<string, unknown> = { contentKey: content.data.key }
159
- if (entry.alias !== undefined) {
160
- if (typeof entry.alias !== 'string' || !BLOCK_ALIAS.test(entry.alias))
161
- return fail(
162
- `block ${index + 1}: an alias is letters, digits, - and _, starting with a letter`,
167
+ const entries = async (
168
+ list: unknown[],
169
+ path: string,
170
+ label: string,
171
+ ): Promise<Record<string, unknown>[] | string> => {
172
+ const layout: Record<string, unknown>[] = []
173
+ const aliases = new Set<string>()
174
+ for (const [index, entry] of list.entries()) {
175
+ const name = `${label}${index + 1}`
176
+ if (!isRecord(entry)) return `block ${name} has no type`
177
+ const content = await element(entry, owner, `${path}/${index}`, `block ${name}`)
178
+ if (!content.ok) return content.message
179
+ contentData.push(content.data)
180
+ const item: Record<string, unknown> = { contentKey: content.data.key }
181
+ if (entry.alias !== undefined) {
182
+ if (typeof entry.alias !== 'string' || !BLOCK_ALIAS.test(entry.alias))
183
+ return `block ${name}: an alias is letters, digits, - and _, starting with a letter`
184
+ if (aliases.has(entry.alias.toLowerCase()))
185
+ return `two blocks are called "${entry.alias}"`
186
+ aliases.add(entry.alias.toLowerCase())
187
+ item.alias = entry.alias
188
+ }
189
+ if (isRecord(entry.settings)) {
190
+ const settings = await element(
191
+ entry.settings,
192
+ owner,
193
+ `${path}/${index}/settings`,
194
+ `block ${name} settings`,
163
195
  )
164
- if (aliases.has(entry.alias.toLowerCase()))
165
- return fail(`two blocks are called "${entry.alias}"`)
166
- aliases.add(entry.alias.toLowerCase())
167
- item.alias = entry.alias
168
- }
169
- if (isRecord(entry.settings)) {
170
- const settings = await element(
171
- entry.settings,
172
- owner,
173
- `${where}/${index}/settings`,
174
- `block ${index + 1} settings`,
175
- )
176
- if (!settings.ok) return fail(settings.message)
177
- settingsData.push(settings.data)
178
- item.settingsKey = settings.data.key
179
- }
180
- if (editor === 'Umbraco.BlockGrid') {
181
- item.columnSpan = typeof entry.columns === 'number' ? entry.columns : 12
182
- item.rowSpan = typeof entry.rows === 'number' ? entry.rows : 1
183
- item.areas = Array.isArray(entry.areas) ? entry.areas : []
196
+ if (!settings.ok) return settings.message
197
+ settingsData.push(settings.data)
198
+ item.settingsKey = settings.data.key
199
+ }
200
+ if (editor === 'Umbraco.BlockGrid') {
201
+ item.columnSpan = typeof entry.columns === 'number' ? entry.columns : 12
202
+ item.rowSpan = typeof entry.rows === 'number' ? entry.rows : 1
203
+ const areas: unknown[] = []
204
+ for (const [a, area] of (Array.isArray(entry.areas) ? entry.areas : []).entries()) {
205
+ // An area already in the stored shape, as older files have it, passes.
206
+ if (!isRecord(area) || !Array.isArray(area.blocks)) {
207
+ areas.push(area)
208
+ continue
209
+ }
210
+ const items = await entries(
211
+ area.blocks,
212
+ `${path}/${index}/areas/${a}`,
213
+ `${name}.${String(area.key ?? a + 1)}.`,
214
+ )
215
+ if (typeof items === 'string') return items
216
+ areas.push({ key: area.key, items })
217
+ }
218
+ item.areas = areas
219
+ }
220
+ layout.push(item)
184
221
  }
185
- layout.push(item)
186
- }
187
- return {
188
- ok: true,
189
- value: { layout: { [BLOCK_LAYOUT[editor]]: layout }, contentData, settingsData },
222
+ return layout
190
223
  }
224
+ const layout = await entries(raw, where, '')
225
+ if (typeof layout === 'string') return fail(layout)
226
+ return { ok: true, value: { layout: { [editor]: layout }, contentData, settingsData } }
191
227
  }
192
228
 
193
229
  const elementValues = async (
@@ -352,6 +388,7 @@ export function valueWriter(lookup: SchemaLookup, refs: ValueRefs) {
352
388
  }
353
389
  case 'Umbraco.BlockList':
354
390
  case 'Umbraco.BlockGrid':
391
+ case SINGLE_BLOCK_EDITOR_ALIAS:
355
392
  return blocks(editor, raw, owner, where)
356
393
  default:
357
394
  return { ok: true, value: raw }
@@ -428,6 +465,7 @@ export function shorthandReader(
428
465
  }
429
466
  case 'Umbraco.BlockList':
430
467
  case 'Umbraco.BlockGrid':
468
+ case SINGLE_BLOCK_EDITOR_ALIAS:
431
469
  return blocks(editor, value)
432
470
  default:
433
471
  return value
@@ -453,49 +491,52 @@ export function shorthandReader(
453
491
  return link
454
492
  }
455
493
 
456
- /** Blocks as `{ type, alias, key, values, settings }`, when their layout is plain enough to say so. */
494
+ /**
495
+ * Blocks as `{ type, alias, key, values, settings }`, read through `readBlocks`
496
+ * (story 345): a grid block's areas as `[{ key, blocks }]`, and a Single Block as
497
+ * its one block, or nothing. A value whose blocks cannot all be said that way
498
+ * stays as it is stored.
499
+ */
457
500
  const blocks = async (editor: string, value: unknown): Promise<unknown> => {
458
- if (!isRecord(value) || !isRecord(value.layout) || !Array.isArray(value.contentData))
459
- return value
460
- const layout = value.layout[editor]
461
- if (!Array.isArray(layout)) return value
462
- const content = new Map(
463
- (value.contentData as unknown[]).filter(isRecord).map((d) => [String(d.key), d]),
464
- )
465
- const settings = new Map(
466
- ((value.settingsData as unknown[] | undefined) ?? [])
467
- .filter(isRecord)
468
- .map((d) => [String(d.key), d]),
469
- )
470
- const out: unknown[] = []
471
- for (const item of layout) {
472
- if (!isRecord(item)) return value
473
- const data = content.get(String(item.contentKey))
474
- if (!data || typeof data.contentTypeKey !== 'string') return value
475
- if (editor === 'Umbraco.BlockGrid' && Array.isArray(item.areas) && item.areas.length > 0)
476
- return value
477
- const entry: Record<string, unknown> = {
478
- type: await aliasOf(data.contentTypeKey),
479
- ...(typeof item.alias === 'string' ? { alias: item.alias } : {}),
480
- key: item.contentKey,
481
- values: await elementValues(data),
482
- }
483
- if (typeof item.settingsKey === 'string') {
484
- const setting = settings.get(item.settingsKey)
485
- if (!setting || typeof setting.contentTypeKey !== 'string') return value
486
- entry.settings = {
487
- type: await aliasOf(setting.contentTypeKey),
488
- key: item.settingsKey,
489
- values: await elementValues(setting),
501
+ if (!isBlockValue(value)) return value
502
+ const say = async (list: Block[]): Promise<unknown[] | undefined> => {
503
+ const out: unknown[] = []
504
+ for (const { layout, content, settings, areas } of list) {
505
+ if (!content || typeof content.contentTypeKey !== 'string') return undefined
506
+ const entry: Record<string, unknown> = {
507
+ type: await aliasOf(content.contentTypeKey),
508
+ ...(typeof layout.alias === 'string' ? { alias: layout.alias } : {}),
509
+ key: layout.contentKey,
510
+ values: await elementValues(content as unknown as Record<string, unknown>),
490
511
  }
512
+ if (typeof layout.settingsKey === 'string') {
513
+ if (!settings || typeof settings.contentTypeKey !== 'string') return undefined
514
+ entry.settings = {
515
+ type: await aliasOf(settings.contentTypeKey),
516
+ key: layout.settingsKey,
517
+ values: await elementValues(settings as unknown as Record<string, unknown>),
518
+ }
519
+ }
520
+ if (editor === 'Umbraco.BlockGrid') {
521
+ entry.columns = layout.columnSpan
522
+ entry.rows = layout.rowSpan
523
+ if (areas.length > 0) {
524
+ const said: unknown[] = []
525
+ for (const area of areas) {
526
+ const inner = await say(area.blocks)
527
+ if (!inner) return undefined
528
+ said.push({ key: area.key, blocks: inner })
529
+ }
530
+ entry.areas = said
531
+ }
532
+ }
533
+ out.push(entry)
491
534
  }
492
- if (editor === 'Umbraco.BlockGrid') {
493
- entry.columns = item.columnSpan
494
- entry.rows = item.rowSpan
495
- }
496
- out.push(entry)
535
+ return out
497
536
  }
498
- return out
537
+ const said = await say(readBlocks(value, editor))
538
+ if (!said) return value
539
+ return editor === SINGLE_BLOCK_EDITOR_ALIAS ? (said[0] ?? null) : said
499
540
  }
500
541
 
501
542
  const elementValues = async (data: Record<string, unknown>) => {
package/src/server.ts CHANGED
@@ -195,8 +195,9 @@ import { createDeliveryMemberSecurity } from './delivery-members.ts'
195
195
  import { handleDictionaryWords } from './dictionary-words-api.ts'
196
196
  import { syncDomainsFile } from './domains.ts'
197
197
  import { editorTypeLibs, siteJsxImportSource } from './editor-types.ts'
198
- import { emailAvailability } from './email.ts'
198
+ import { emailAvailability, emailReady } from './email.ts'
199
199
  import { noticeAboutEmail } from './email-notice.ts'
200
+ import { createEmailSettings, type EmailSettingsInput } from './email-settings.ts'
200
201
  import { activityCsv, readActivityQuery } from './extension-activity.ts'
201
202
  import { createBackOfficeBuilds } from './extension-backoffice.ts'
202
203
  import { warnAboutAppPlugins } from './extensions-notice.ts'
@@ -240,6 +241,7 @@ import {
240
241
  } from './preview-tokens.ts'
241
242
  import { provenanceProblem } from './provenance.ts'
242
243
  import { createRemote, may, type RestartOutcome } from './remote.ts'
244
+ import { createSchemaTransfer, UPLOAD_LIMITS } from './schema-transfer.ts'
243
245
  import { SiteAssets } from './site-assets.ts'
244
246
  import { unknownHostProvided } from './site-file.ts'
245
247
  import { PublicFiles } from './site-public.ts'
@@ -1303,7 +1305,16 @@ export async function createServer(
1303
1305
  // Whether an invitation or a reset link can reach anyone at all, which is what
1304
1306
  // gates the options rather than `emailStatus.available`: development delivers
1305
1307
  // to the console, and that is a working flow for the person using it.
1306
- const canSendUserLinks = Boolean(resolveUserLinkSender(config, email))
1308
+ // Asked each time, as e-mail set up in Settings changes without a restart (story 340).
1309
+ const canSendUserLinks = () => Boolean(resolveUserLinkSender(config, email))
1310
+ const emailSettings = createEmailSettings(db, config, { port: () => email })
1311
+ const schemaTransfer = createSchemaTransfer(db, config, {
1312
+ boot: schema,
1313
+ afterApply: async (report) => {
1314
+ cache.invalidate()
1315
+ await afterSync(report)
1316
+ },
1317
+ })
1307
1318
  const images = new ImageProcessor(mediaStore)
1308
1319
  // Asked at boot, so the first AVIF request does not wait on it.
1309
1320
  void canEncodeAvif()
@@ -1516,6 +1527,7 @@ export async function createServer(
1516
1527
  const MEDIA_JOB_QUEUED_EVENT = { eventSource: 'Crombolo:MediaJob', eventType: 'Queued' } as const
1517
1528
  const hostTokenPath = `${paths.pluginPath}/api/host-token`
1518
1529
  const contentQueryPath = `${paths.pluginPath}/api/content-query`
1530
+ const selfAudited = [`${paths.pluginPath}/api/email/`, `${paths.pluginPath}/api/schema-transfer/`]
1519
1531
  const bundleInstallPaths = new Set(
1520
1532
  ['install', 'uninstall', 'disable', 'enable', 'grant', 'settings'].flatMap((action) => [
1521
1533
  `${paths.pluginPath}/api/extensions/${action}`,
@@ -1933,8 +1945,10 @@ export async function createServer(
1933
1945
  if (pathname === hostTokenPath) return
1934
1946
  // A content query is a POST that reads.
1935
1947
  if (pathname === contentQueryPath) return
1936
- // Installs and removals write their own entry, with the package (story 194).
1948
+ // Installs and removals write their own entry, with the package (story 194),
1949
+ // as do e-mail settings (story 340) and schema imports (story 342).
1937
1950
  if (bundleInstallPaths.has(pathname) || pathname.startsWith(`${jobsPath}/`)) return
1951
+ if (selfAudited.some((path) => pathname.startsWith(path))) return
1938
1952
  const principal = await authenticate(request)
1939
1953
  if (!principal) return
1940
1954
  const plan = pluginAuditPlan(request.method, pathname.slice(prefix.length))
@@ -2467,16 +2481,100 @@ export async function createServer(
2467
2481
 
2468
2482
  if (pathname === `${paths.pluginPath}/api/email` && request.method === 'GET') {
2469
2483
  if (!(await authenticate(request))) return new Response('Unauthorized', { status: 401 })
2484
+ const status = emailAvailability(email)
2470
2485
  return Response.json({
2471
- available: emailStatus.available,
2472
- provider: emailStatus.provider,
2473
- reason: emailStatus.reason,
2474
- affects: emailStatus.affects,
2475
- canSendUserLinks,
2476
- canSendNotifications: Boolean(email),
2486
+ available: status.available,
2487
+ provider: status.provider,
2488
+ reason: status.reason,
2489
+ affects: status.affects,
2490
+ canSendUserLinks: canSendUserLinks(),
2491
+ canSendNotifications: emailReady(email),
2477
2492
  })
2478
2493
  }
2479
2494
 
2495
+ // Story 342: Settings → Schema, administrators only. An upload waits for
2496
+ // approval on the Changes dashboard; nothing changes until it is applied.
2497
+ const schemaAction = /^\/api\/schema-transfer\/(export|import|import\/apply)$/.exec(
2498
+ pathname.slice(paths.pluginPath.length),
2499
+ )?.[1]
2500
+ if (pathname.startsWith(paths.pluginPath) && schemaAction) {
2501
+ const principal = await authenticate(request)
2502
+ if (!principal) return new Response('Unauthorized', { status: 401 })
2503
+ if (!principal.isAdmin)
2504
+ return Response.json(
2505
+ { ok: false, message: 'Only an administrator imports or exports the schema.' },
2506
+ { status: 403 },
2507
+ )
2508
+ const actor = actorOf(principal, request)
2509
+ if (schemaAction === 'export' && request.method === 'GET')
2510
+ return new Response(schemaTransfer.exportZip(), {
2511
+ headers: {
2512
+ 'content-type': 'application/zip',
2513
+ 'content-disposition': 'attachment; filename="schema.zip"',
2514
+ 'cache-control': PRIVATE_NO_STORE,
2515
+ },
2516
+ })
2517
+ if (schemaAction === 'import' && request.method === 'GET')
2518
+ return Response.json({
2519
+ pending: (await schemaTransfer.pending()) ?? null,
2520
+ writable: config.schemaWritable,
2521
+ })
2522
+ let outcome: Awaited<ReturnType<typeof schemaTransfer.discard>> | undefined
2523
+ if (schemaAction === 'import' && request.method === 'POST') {
2524
+ const length = Number(request.headers.get('content-length') ?? 0)
2525
+ if (length > UPLOAD_LIMITS.maxUploadBytes)
2526
+ return Response.json(
2527
+ { ok: false, message: 'That file is too large to be a schema.' },
2528
+ { status: 413 },
2529
+ )
2530
+ const name = new URL(request.url).searchParams.get('name') ?? 'schema.zip'
2531
+ outcome = await schemaTransfer.upload(
2532
+ actor,
2533
+ name,
2534
+ new Uint8Array(await request.arrayBuffer()),
2535
+ )
2536
+ } else if (schemaAction === 'import' && request.method === 'DELETE')
2537
+ outcome = await schemaTransfer.discard(actor)
2538
+ else if (schemaAction === 'import/apply' && request.method === 'POST')
2539
+ outcome = await schemaTransfer.apply(actor)
2540
+ if (!outcome) return new Response('Method Not Allowed', { status: 405 })
2541
+ return outcome.ok
2542
+ ? Response.json(outcome)
2543
+ : Response.json(outcome, { status: outcome.status })
2544
+ }
2545
+
2546
+ // Story 340: Settings → E-mail, administrators only.
2547
+ const emailAction = /^\/api\/email\/(settings|test)$/.exec(
2548
+ pathname.slice(paths.pluginPath.length),
2549
+ )?.[1]
2550
+ if (pathname.startsWith(paths.pluginPath) && emailAction) {
2551
+ const principal = await authenticate(request)
2552
+ if (!principal) return new Response('Unauthorized', { status: 401 })
2553
+ if (!principal.isAdmin)
2554
+ return Response.json(
2555
+ { ok: false, message: 'Only an administrator sets up e-mail.' },
2556
+ { status: 403 },
2557
+ )
2558
+ const actor = actorOf(principal, request)
2559
+ if (emailAction === 'settings' && request.method === 'GET')
2560
+ return Response.json(await emailSettings.view())
2561
+ const outcome =
2562
+ emailAction === 'settings' && request.method === 'PUT'
2563
+ ? await emailSettings.save(
2564
+ actor,
2565
+ ((await request.json().catch(() => ({}))) ?? {}) as EmailSettingsInput,
2566
+ )
2567
+ : emailAction === 'settings' && request.method === 'DELETE'
2568
+ ? await emailSettings.clear(actor)
2569
+ : emailAction === 'test' && request.method === 'POST'
2570
+ ? await emailSettings.test(actor)
2571
+ : undefined
2572
+ if (!outcome) return new Response('Method Not Allowed', { status: 405 })
2573
+ return outcome.ok
2574
+ ? Response.json(outcome)
2575
+ : Response.json({ ok: false, message: outcome.message }, { status: outcome.status })
2576
+ }
2577
+
2480
2578
  /**
2481
2579
  * Non-contract: forms and their entries. There is no form operation in the
2482
2580
  * vendored contract — Umbraco Forms ships its own API and its own client,
@@ -3149,7 +3247,10 @@ export async function createServer(
3149
3247
  bundles,
3150
3248
  upgrades,
3151
3249
  transfers: await pendingTransfers(db),
3250
+ // Story 342: an uploaded schema waiting for an administrator.
3251
+ schemaImport: principal.isAdmin ? ((await schemaTransfer.pending()) ?? null) : null,
3152
3252
  mayImport,
3253
+ mayApplySchema: principal.isAdmin,
3153
3254
  })
3154
3255
  }
3155
3256
 
@@ -3250,7 +3351,7 @@ export async function createServer(
3250
3351
  allowUserInvite: false,
3251
3352
  // Offering "forgot password" with no way to send the link is a dead
3252
3353
  // end that looks like a bug; without a sender the option is not there.
3253
- allowPasswordReset: config.allowPasswordReset && canSendUserLinks,
3354
+ allowPasswordReset: config.allowPasswordReset && canSendUserLinks(),
3254
3355
  disableLocalLogin: !config.allowLocalLogin,
3255
3356
  // Set by the authorize endpoint so sign-in resumes the OAuth flow. Only
3256
3357
  // a path on this site: the login page hands this to the browser once
package/src/settings.ts CHANGED
@@ -443,12 +443,13 @@ const DECLARED = [
443
443
  description: 'Whether the back office may change the schema files.',
444
444
  },
445
445
  {
446
- env: 'CROMBOLO_CONTENT_FILES_READONLY',
447
- kind: 'boolean',
448
- default: 'false',
446
+ env: 'CROMBOLO_CONTENT_MODE',
447
+ kind: 'enum',
448
+ values: ['development', 'production'],
449
+ default: 'development',
449
450
  section: 'Schema',
450
451
  description:
451
- 'Stops the back office changing templates, stylesheets and scripts, for a site whose files come from its repository.',
452
+ 'In production, the back office cannot change templates, stylesheets and scripts, for a site whose files come from its repository.',
452
453
  },
453
454
  {
454
455
  env: 'CROMBOLO_SYNC_SCHEMA_AT_BOOT',
@@ -299,7 +299,8 @@ export class PublicFiles {
299
299
  /** The servable files of a folder, which may not exist. */
300
300
  function filesFrom(root: string): string[] {
301
301
  try {
302
- return existsSync(root) ? filesIn(root).filter(isServable) : []
302
+ // Sorted: the folder's own order differs between file systems.
303
+ return existsSync(root) ? filesIn(root).filter(isServable).sort() : []
303
304
  } catch {
304
305
  return []
305
306
  }
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',
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
+ }