@crombolo/server 0.45.0 → 0.47.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.
@@ -17,9 +17,9 @@
17
17
  * browser cannot reach npm, and the backoffice keeps making same-origin
18
18
  * requests only.
19
19
  */
20
- import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
20
+ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
21
21
  import { tmpdir } from 'node:os'
22
- import { join } from 'node:path'
22
+ import { join, resolve } from 'node:path'
23
23
  import {
24
24
  type BundlePackage,
25
25
  describePermissions,
@@ -28,6 +28,12 @@ import {
28
28
  type PackageJson,
29
29
  validateBundlePackage,
30
30
  } from '@crombolo/backoffice-host'
31
+ import {
32
+ LOCAL_BUNDLES_DIR,
33
+ localBundleFileName,
34
+ localBundlePath,
35
+ localBundlesNamed,
36
+ } from '@crombolo/transfer'
31
37
  import { type BundleGrants, declaredPermissions } from './bundle-grants.ts'
32
38
  import { logger } from './logging.ts'
33
39
  import {
@@ -157,6 +163,8 @@ export interface InstallOutcome {
157
163
  restartPending?: boolean
158
164
  /** Where the version checked was built, from its signature (story 060). */
159
165
  provenance?: ProvenanceResult
166
+ /** The file an install from a file keeps in the site, to commit: `bundles/acme-crm-1.2.0.tgz` (story 245). */
167
+ file?: string
160
168
  }
161
169
 
162
170
  export type PackageInstaller = (
@@ -296,6 +304,36 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
296
304
  }
297
305
  let cached: { at: number; query: string; listings: MarketplaceListing[] } | undefined
298
306
 
307
+ /**
308
+ * A bundle's file at `bundles/<name>-<version>.tgz`: used in place when it is
309
+ * there already, copied there otherwise. Another file under that name is
310
+ * refused, since one version is one file.
311
+ */
312
+ const keepInSite = (
313
+ file: string,
314
+ declared: { name: string; version: string },
315
+ ): { path: string; copied: boolean } | string => {
316
+ const path = `${LOCAL_BUNDLES_DIR}/${localBundleFileName(declared.name, declared.version)}`
317
+ const target = join(options.siteDir, path)
318
+ if (resolve(file) === resolve(target)) return { path, copied: false }
319
+ const bytes = readFileSync(file)
320
+ if (existsSync(target)) {
321
+ if (readFileSync(target).equals(bytes)) return { path, copied: false }
322
+ return `${path} already holds a different ${declared.name}@${declared.version} than ${file}, so it was not installed: one version is one file. Remove ${path} first if ${file} is the one to keep.`
323
+ }
324
+ mkdirSync(join(options.siteDir, LOCAL_BUNDLES_DIR), { recursive: true })
325
+ copyFileSync(file, target)
326
+ return { path, copied: true }
327
+ }
328
+
329
+ /** The `bundles/` file a dependency used to name, removed once nothing names it. */
330
+ const removeUnnamed = (previousRange: string | undefined, keep?: string) => {
331
+ const path = localBundlePath(previousRange)
332
+ if (!path || path === keep) return
333
+ if (localBundlesNamed(options.siteDir).includes(path)) return
334
+ rmSync(join(options.siteDir, path), { force: true })
335
+ }
336
+
299
337
  const installedVersion = (name: string): string | null =>
300
338
  options.extensions.bundles().bundles.find((bundle) => bundle.packageName === name)?.version ??
301
339
  null
@@ -370,7 +408,7 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
370
408
  const response = await call(dist.tarball)
371
409
  if (!response.ok)
372
410
  return {
373
- state: 'invalid',
411
+ state: 'unchecked',
374
412
  reason: `${name} could not be fetched to check its signature (the registry answered ${response.status})`,
375
413
  }
376
414
  const bytes = new Uint8Array(await response.arrayBuffer())
@@ -386,7 +424,7 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
386
424
  return await verify(unpacked)
387
425
  } catch (error) {
388
426
  return {
389
- state: 'invalid',
427
+ state: 'unchecked',
390
428
  reason: `${name} could not be checked: ${error instanceof Error ? error.message : String(error)}`,
391
429
  }
392
430
  } finally {
@@ -417,12 +455,15 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
417
455
  let found = installedProvenance.get(key)
418
456
  if (!found) {
419
457
  found = verify(bundle.directory).catch((error: unknown) => ({
420
- state: 'invalid' as const,
458
+ state: 'unchecked' as const,
421
459
  reason: error instanceof Error ? error.message : String(error),
422
460
  }))
423
461
  installedProvenance.set(key, found)
424
462
  }
425
- return found
463
+ const result = await found
464
+ // Not kept: the next look may be able to check it.
465
+ if (result.state === 'unchecked') installedProvenance.delete(key)
466
+ return result
426
467
  }
427
468
 
428
469
  /** What the registry says this package's latest version carries, when it is a valid bundle. */
@@ -592,21 +633,47 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
592
633
  if (typeof declared === 'string') return { ok: false, message: declared }
593
634
  if (declared.server && !consented(request, declared.permissions))
594
635
  return serverConsentNeeded(declared.name, declared.permissions)
595
- const provenance = await verifyPackage(file).catch((error: unknown) => ({
596
- state: 'invalid' as const,
597
- reason: error instanceof Error ? error.message : String(error),
598
- }))
636
+ // Kept in the site's bundles/ (story 245), so it is committed and every
637
+ // node, checkout and CI build installs the same file.
638
+ const kept = keepInSite(file, declared)
639
+ if (typeof kept === 'string') return { ok: false, message: kept }
640
+ const discard = () => {
641
+ if (kept.copied) rmSync(join(options.siteDir, kept.path), { force: true })
642
+ }
643
+ const provenance = await verifyPackage(join(options.siteDir, kept.path)).catch(
644
+ (error: unknown) => ({
645
+ state: 'unchecked' as const,
646
+ reason: error instanceof Error ? error.message : String(error),
647
+ }),
648
+ )
599
649
  const refused = refusedBySignature(declared.name, provenance)
600
- if (refused) return refused
601
- return { ...(await added(declared.name, file, undefined, request)), provenance }
650
+ if (refused) {
651
+ discard()
652
+ return refused
653
+ }
654
+ const previous = await rangeFor(declared.name)
655
+ const outcome = await added(declared.name, `./${kept.path}`, undefined, request)
656
+ if (!outcome.ok) {
657
+ discard()
658
+ return { ...outcome, provenance }
659
+ }
660
+ removeUnnamed(previous, kept.path)
661
+ return {
662
+ ...outcome,
663
+ provenance,
664
+ file: kept.path,
665
+ message: `${outcome.message} Commit ${kept.path} with package.json and bun.lock.`,
666
+ }
602
667
  },
603
668
 
604
669
  async uninstall(name) {
605
670
  if (options.installs === false) return refusedHere(name, 'remove', options.installsElsewhere)
606
671
  if (!isValidPackageName(name))
607
672
  return { ok: false, message: `'${name}' is not a package name npm would accept.` }
673
+ const previous = await rangeFor(name)
608
674
  const result = await install('remove', name, options.siteDir)
609
675
  options.extensions.invalidate()
676
+ if (result.ok) removeUnnamed(previous)
610
677
  return result.ok
611
678
  ? {
612
679
  ok: true,
@@ -704,18 +771,19 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
704
771
  /** What a packed bundle on this machine declares, read from its package.json, or why it cannot be installed. */
705
772
  async function declaresIn(
706
773
  file: string,
707
- ): Promise<{ name: string; server: boolean; permissions: string[] } | string> {
774
+ ): Promise<{ name: string; version: string; server: boolean; permissions: string[] } | string> {
708
775
  const dir = mkdtempSync(join(tmpdir(), 'crombolo-bundle-file-'))
709
776
  try {
710
777
  await extractTarball(file, dir)
711
778
  const root = existsSync(join(dir, 'package', 'package.json')) ? join(dir, 'package') : dir
712
779
  const json = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as PackageJson
713
780
  const problems = validateBundlePackage(json)
714
- if (problems.length > 0 || typeof json.name !== 'string')
781
+ if (problems.length > 0 || typeof json.name !== 'string' || typeof json.version !== 'string')
715
782
  return `${file} is not a bundle for this site, so it was not installed.`
716
783
  const field = json.crombolo as { server?: string; permissions?: string[] }
717
784
  return {
718
785
  name: json.name,
786
+ version: json.version,
719
787
  server: field.server !== undefined,
720
788
  permissions: Array.isArray(field.permissions) ? field.permissions : [],
721
789
  }
@@ -99,6 +99,8 @@ export interface MemberAuth {
99
99
  * error page for one who is signed in but not allowed.
100
100
  */
101
101
  decide(content: PublishedContent, member: RequestMember | undefined): Promise<AccessDecision>
102
+ /** A member by key, as a page sees them, for previewing as them (story 264). */
103
+ byKey(key: string): Promise<RequestMember | undefined>
102
104
  /** Handles the member endpoints, or undefined when the path is not one. */
103
105
  handle(request: Request, pathname: string): Promise<Response | undefined>
104
106
  /** The `Set-Cookie` value that ends a member's site session. */
@@ -586,6 +588,10 @@ export function createMemberAuth(
586
588
  resolve,
587
589
  session,
588
590
  decide,
591
+ async byKey(key) {
592
+ const member = await members.byKey(key)
593
+ return member ? asRequestMember(member) : undefined
594
+ },
589
595
  signOutCookie: () => expireCookie(cookie, config.secureCookies),
590
596
  externalSignInUrl: (providerId, returnUrl) =>
591
597
  config.memberIdentityProviders.some((p) => p.oidc.id === providerId)
package/src/no-nodes.ts CHANGED
@@ -138,7 +138,7 @@ export function noNodesPage(options: { siteName: string; backOfficePath: string
138
138
  <h2>Configure page metadata</h2>
139
139
  <p>A content type says what a kind of page holds: a title, a summary, a body. Add one in the back office under <strong>Settings → Structure</strong>, or from the command line:</p>
140
140
  <pre><code>bunx crombolo types new content-type article --at-root
141
- bunx crombolo types add-property article summary --type textarea</code></pre>
141
+ bunx crombolo types property add article summary --type textarea</code></pre>
142
142
  <p>Either way it is saved as a file, <code>schema/content-types/article.toml</code>, so it travels with your code.</p>
143
143
  </li>
144
144
  <li>
@@ -55,6 +55,8 @@ export interface NodeOperationsOptions {
55
55
  webhooks?: WebhookService
56
56
  nudgeEvents?: () => void
57
57
  backOfficeUrl?: string
58
+ /** Where a large media branch's write is queued (story 246); made in the request when absent. */
59
+ background?: (queuedBy: string) => { enqueue(name: string, payload: unknown): Promise<string> }
58
60
  }
59
61
 
60
62
  export function createNodeOperations(options: NodeOperationsOptions): NodeOperations {
@@ -117,6 +119,7 @@ export function createNodeOperations(options: NodeOperationsOptions): NodeOperat
117
119
  // Only the items it touched: a media change leaves the pages alone (story 197).
118
120
  onChange: (change) => cache?.media?.apply(change),
119
121
  refusalReason,
122
+ background: options.background,
120
123
  })
121
124
  return { valueIntake: repository.valueIntake, tracker, approvals, documents, media }
122
125
  }
package/src/owner-jobs.ts CHANGED
@@ -14,6 +14,13 @@ import {
14
14
  } from '@crombolo/data'
15
15
  import { type Cron, isTimezone, nextOccurrence, parseCron } from './cron.ts'
16
16
  import { logger } from './logging.ts'
17
+ import { inSpan, recordJob } from './telemetry.ts'
18
+
19
+ /**
20
+ * Core's own queued work (story 246). A bundle's id is letters, digits and
21
+ * hyphens, so this can never be one.
22
+ */
23
+ export const CORE_JOB_OWNER = 'crombolo:core'
17
24
 
18
25
  /** The largest payload a job may carry, as JSON. */
19
26
  export const MAX_PAYLOAD_BYTES = 64 * 1024
@@ -267,14 +274,26 @@ export function createJobRunner(options: {
267
274
  enqueue: (name: string, payload?: unknown) =>
268
275
  enqueue(owner.id, name, payload, `job ${job.id}`),
269
276
  })
277
+ // Story 262: each run a span, on the role that ran it, and counted by outcome.
278
+ const started = performance.now()
279
+ const attributes = { 'crombolo.job.name': `${job.owner}/${job.name}` }
280
+ let outcome = 'succeeded'
270
281
  try {
271
- await handler(job.payload, { ...owner.context(), job: info })
282
+ await inSpan(
283
+ `job ${job.owner}/${job.name}`,
284
+ { ...attributes, 'crombolo.job.attempt': job.attempts },
285
+ async () => {
286
+ await handler(job.payload, { ...owner.context(), job: info })
287
+ },
288
+ )
272
289
  await jobs.succeed(job.id)
273
290
  } catch (error) {
274
291
  if (signal.aborted) {
292
+ outcome = 'released'
275
293
  await jobs.release(job.id)
276
294
  return
277
295
  }
296
+ outcome = 'failed'
278
297
  const message = (error instanceof Error ? error.message : String(error)).slice(0, MAX_ERROR)
279
298
  const retryAt =
280
299
  job.attempts < job.maxAttempts
@@ -289,6 +308,10 @@ export function createJobRunner(options: {
289
308
  })
290
309
  } finally {
291
310
  clearInterval(heartbeat)
311
+ recordJob((performance.now() - started) / 1000, {
312
+ ...attributes,
313
+ 'crombolo.job.outcome': outcome,
314
+ })
292
315
  }
293
316
  }
294
317
 
package/src/ports.ts CHANGED
@@ -587,6 +587,7 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
587
587
  ).memberAuthorization.clientCredentialsFlow.associatedMembers.map((m) => m.userName),
588
588
  })
589
589
  deps.publicAccess = createPublicAccessPort(options.db, {
590
+ nodeId: options.schema?.nodeId,
590
591
  onChange: () => options.cache?.invalidate(),
591
592
  })
592
593
  deps.elements = createElementPort(options.db, {
package/src/provenance.ts CHANGED
@@ -76,7 +76,11 @@ export interface ProvenanceFile {
76
76
  links: ProvenanceLinks
77
77
  }
78
78
 
79
- export type ProvenanceState = 'signed' | 'unsigned' | 'invalid' | 'local'
79
+ /**
80
+ * `unchecked`: Sigstore's trusted root could not be had, so the signature was not
81
+ * checked either way (story 244). Refused like `invalid`, and worth trying again.
82
+ */
83
+ export type ProvenanceState = 'signed' | 'unsigned' | 'invalid' | 'unchecked' | 'local'
80
84
 
81
85
  export interface ProvenanceResult {
82
86
  state: ProvenanceState
@@ -194,6 +198,8 @@ export function describeProvenance(result: ProvenanceResult): string {
194
198
  return 'Local: from this machine, not a registry'
195
199
  case 'invalid':
196
200
  return `Signature not accepted: ${result.reason ?? 'it does not check out'}`
201
+ case 'unchecked':
202
+ return `Couldn't be checked right now: ${result.reason ?? 'try again'}`
197
203
  }
198
204
  }
199
205
 
@@ -260,12 +266,20 @@ export async function signPackage(dir: string, options: SignOptions = {}): Promi
260
266
  export interface VerifyProvenanceOptions {
261
267
  /** Sigstore's trusted root as JSON; the public one, refreshed through TUF, by default. */
262
268
  trustedRoot?: unknown
263
- /**
264
- * Checks the Sigstore bundle itself, throwing when it does not verify; the
265
- * Sigstore verifier by default. Only a test passes one: a signature in this
266
- * format is made in GitHub Actions, not offline.
267
- */
268
- verifySignature?: (signature: SerializedBundle) => void | Promise<void>
269
+ }
270
+
271
+ /**
272
+ * Checks the Sigstore bundle itself, throwing when it does not verify. Only a
273
+ * test passes one, through `verifyProvenanceWith`: a signature in this format is
274
+ * made in GitHub Actions, never offline.
275
+ */
276
+ export type SignatureCheck = (signature: SerializedBundle) => void | Promise<void>
277
+
278
+ /** What a test replaces in `verifyProvenanceWith`; nothing a host is offered. */
279
+ export interface ProvenanceSeams {
280
+ verifySignature?: SignatureCheck
281
+ /** Stands in for fetching Sigstore's public trusted root. */
282
+ publicRoot?: () => Promise<TrustedRoot>
269
283
  }
270
284
 
271
285
  let publicRoot: { at: number; root: Promise<TrustedRoot> } | undefined
@@ -300,11 +314,21 @@ const invalid = (reason: string, digest?: string): ProvenanceResult => ({
300
314
  * Checks a package directory's signature: its digest, Sigstore's signature and
301
315
  * certificate against the trusted root, that GitHub Actions signed it, and that
302
316
  * `provenance.json` claims what the certificate says. Unsigned when there is no
303
- * `provenance.json`; invalid, with the reason, when anything disagrees.
317
+ * `provenance.json`; invalid, with the reason, when anything disagrees;
318
+ * unchecked when the trusted root could not be fetched and none is cached.
304
319
  */
305
- export async function verifyProvenance(
320
+ export function verifyProvenance(
306
321
  dir: string,
307
322
  options: VerifyProvenanceOptions = {},
323
+ ): Promise<ProvenanceResult> {
324
+ return verifyProvenanceWith(dir, options)
325
+ }
326
+
327
+ /** `verifyProvenance`, with Sigstore's steps replaced: for tests only. */
328
+ export async function verifyProvenanceWith(
329
+ dir: string,
330
+ options: VerifyProvenanceOptions,
331
+ seams: ProvenanceSeams = {},
308
332
  ): Promise<ProvenanceResult> {
309
333
  const file = join(dir, PROVENANCE_FILE)
310
334
  if (!existsSync(file)) return { state: 'unsigned' }
@@ -320,19 +344,20 @@ export async function verifyProvenance(
320
344
  if (provenance.digest !== digest)
321
345
  return invalid('the bundle has changed since it was signed', digest)
322
346
 
323
- let check = options.verifySignature
347
+ let check = seams.verifySignature
324
348
  if (!check) {
325
349
  let root: TrustedRoot
326
350
  try {
327
351
  root =
328
352
  options.trustedRoot !== undefined
329
353
  ? TrustedRoot.fromJSON(options.trustedRoot)
330
- : await publicTrustedRoot()
354
+ : await (seams.publicRoot ?? publicTrustedRoot)()
331
355
  } catch (error) {
332
- return invalid(
333
- `Sigstore's trusted root could not be fetched, so the signature cannot be checked: ${error instanceof Error ? error.message : String(error)}`,
356
+ return {
357
+ state: 'unchecked',
358
+ reason: `Sigstore's trusted root could not be fetched: ${error instanceof Error ? error.message : String(error)}`,
334
359
  digest,
335
- )
360
+ }
336
361
  }
337
362
  check = (signature) => {
338
363
  new Verifier(toTrustMaterial(root)).verify(toSignedEntity(bundleFromJSON(signature)), {
@@ -398,7 +423,8 @@ export function sourceAllowed(source: ProvenanceSource, entry: string): boolean
398
423
 
399
424
  /**
400
425
  * Why the site will not take this bundle, or undefined when it will. An
401
- * invalid signature is refused whatever the policy; `local` is the site's own.
426
+ * invalid or unchecked signature is refused whatever the policy; `local` is the
427
+ * site's own.
402
428
  */
403
429
  export function provenanceProblem(
404
430
  result: ProvenanceResult,
@@ -406,6 +432,8 @@ export function provenanceProblem(
406
432
  ): string | undefined {
407
433
  if (result.state === 'invalid')
408
434
  return `its signature was not accepted: ${result.reason ?? 'it does not check out'}`
435
+ if (result.state === 'unchecked')
436
+ return `its signature could not be checked right now (${result.reason ?? 'try again'}); try again`
409
437
  if (result.state === 'local') return undefined
410
438
  if (result.state === 'unsigned')
411
439
  return policy.signatures === 'required'