@fabrika/app 0.9.0-dev.4 → 0.9.0-dev.6

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 (113) hide show
  1. package/package.json +9 -9
  2. package/skill/SKILL.md +41 -14
  3. package/skill/references/app-setup.md +43 -12
  4. package/skill/references/dev.md +2 -1
  5. package/skill/references/endpoint.md +30 -24
  6. package/skill/references/errors.md +40 -35
  7. package/skill/references/files.md +4 -2
  8. package/skill/references/jobs.md +21 -4
  9. package/skill/references/table-and-migration.md +19 -2
  10. package/skill/references/tests.md +40 -1
  11. package/skill/references/webhooks-links-connectors.md +1 -1
  12. package/src/build-recipe.ts +198 -0
  13. package/src/build.ts +60 -4
  14. package/src/bun.ts +181 -13
  15. package/src/cloudflare/application.ts +822 -0
  16. package/src/cloudflare/bindings.ts +159 -0
  17. package/src/cloudflare/export.ts +621 -0
  18. package/src/cloudflare/import.ts +1013 -0
  19. package/src/cloudflare/maintenance.ts +518 -0
  20. package/src/cloudflare/names.ts +16 -0
  21. package/src/cloudflare/ops.ts +375 -0
  22. package/src/cloudflare/r2-files.ts +172 -0
  23. package/src/cloudflare/restore.ts +167 -0
  24. package/src/cloudflare/tracker.ts +192 -0
  25. package/src/cloudflare.ts +100 -146
  26. package/src/contract/app-id.ts +5 -0
  27. package/src/contract/artifact-schema.ts +9 -1
  28. package/src/contract/build.ts +40 -2
  29. package/src/contract/compile.ts +1 -0
  30. package/src/contract/context.ts +35 -9
  31. package/src/contract/declaration.ts +2 -0
  32. package/src/contract/defaults.ts +22 -2
  33. package/src/contract/define.ts +29 -3
  34. package/src/contract/kit.ts +4 -1
  35. package/src/contract/platform.ts +3 -2
  36. package/src/contract/vocabulary.ts +26 -8
  37. package/src/dev/launcher.ts +50 -4
  38. package/src/disk-assets.ts +8 -3
  39. package/src/files/archive.ts +2 -2
  40. package/src/files/job-names.ts +12 -0
  41. package/src/files/kinds.ts +73 -31
  42. package/src/files/scan.ts +3 -4
  43. package/src/files/streams.ts +3 -1
  44. package/src/implement/anonymous.ts +12 -11
  45. package/src/implement/boot.ts +75 -6
  46. package/src/implement/bounded.ts +21 -2
  47. package/src/implement/capability.ts +15 -3
  48. package/src/implement/dispatch.ts +419 -177
  49. package/src/implement/failures.ts +17 -1
  50. package/src/implement/faults.ts +1 -0
  51. package/src/implement/index.ts +1 -0
  52. package/src/implement/invocation.ts +58 -10
  53. package/src/implement/principal.ts +25 -2
  54. package/src/implement/terminals.ts +93 -0
  55. package/src/implement/workload.ts +42 -16
  56. package/src/jobs/mail.ts +8 -0
  57. package/src/jobs/report.ts +5 -1
  58. package/src/jobs/runner.ts +672 -113
  59. package/src/jobs/schedule.ts +7 -1
  60. package/src/jobs/scrub.ts +14 -1
  61. package/src/jobs/types.ts +6 -0
  62. package/src/spa-fallback.ts +12 -0
  63. package/src/testing/endpoint-access.ts +307 -152
  64. package/src/testing/isolation.ts +8 -1
  65. package/src/testing/kit.ts +80 -2
  66. package/src/testing/proxy.ts +15 -10
  67. package/types/src/build-recipe.d.ts +70 -0
  68. package/types/src/build.d.ts +19 -1
  69. package/types/src/bun.d.ts +34 -1
  70. package/types/src/cloudflare/application.d.ts +73 -0
  71. package/types/src/cloudflare/bindings.d.ts +33 -0
  72. package/types/src/cloudflare/export.d.ts +16 -0
  73. package/types/src/cloudflare/import.d.ts +51 -0
  74. package/types/src/cloudflare/maintenance.d.ts +117 -0
  75. package/types/src/cloudflare/names.d.ts +11 -0
  76. package/types/src/cloudflare/ops.d.ts +81 -0
  77. package/types/src/cloudflare/r2-files.d.ts +9 -0
  78. package/types/src/cloudflare/restore.d.ts +9 -0
  79. package/types/src/cloudflare/tracker.d.ts +29 -0
  80. package/types/src/cloudflare.d.ts +12 -18
  81. package/types/src/contract/app-id.d.ts +2 -0
  82. package/types/src/contract/artifact-schema.d.ts +2 -0
  83. package/types/src/contract/context.d.ts +35 -11
  84. package/types/src/contract/declaration.d.ts +4 -0
  85. package/types/src/contract/defaults.d.ts +19 -1
  86. package/types/src/contract/define.d.ts +20 -3
  87. package/types/src/contract/kit.d.ts +2 -1
  88. package/types/src/contract/platform.d.ts +2 -2
  89. package/types/src/contract/vocabulary.d.ts +9 -7
  90. package/types/src/disk-assets.d.ts +4 -1
  91. package/types/src/files/job-names.d.ts +9 -0
  92. package/types/src/files/kinds.d.ts +21 -14
  93. package/types/src/files/scan.d.ts +1 -3
  94. package/types/src/implement/anonymous.d.ts +2 -4
  95. package/types/src/implement/boot.d.ts +17 -1
  96. package/types/src/implement/bounded.d.ts +11 -1
  97. package/types/src/implement/capability.d.ts +4 -2
  98. package/types/src/implement/dispatch.d.ts +34 -1
  99. package/types/src/implement/failures.d.ts +5 -0
  100. package/types/src/implement/faults.d.ts +1 -0
  101. package/types/src/implement/index.d.ts +1 -0
  102. package/types/src/implement/invocation.d.ts +22 -7
  103. package/types/src/implement/principal.d.ts +6 -1
  104. package/types/src/implement/terminals.d.ts +33 -0
  105. package/types/src/implement/workload.d.ts +5 -0
  106. package/types/src/jobs/runner.d.ts +66 -2
  107. package/types/src/jobs/schedule.d.ts +2 -0
  108. package/types/src/jobs/types.d.ts +6 -0
  109. package/types/src/spa-fallback.d.ts +2 -0
  110. package/types/src/testing/endpoint-access.d.ts +37 -5
  111. package/types/src/testing/isolation.d.ts +1 -1
  112. package/types/src/testing/kit.d.ts +22 -1
  113. package/types/src/testing/proxy.d.ts +4 -4
@@ -24,6 +24,7 @@ import {
24
24
  type SchemaShape,
25
25
  type StringShape,
26
26
  type TablePolicyArtifact,
27
+ terminalIdentifyProblem,
27
28
  type TupleShape,
28
29
  } from '@fabrika/auth-core'
29
30
  import { isPolicyOrigin, WORKER_BLOB_SOURCE } from '@fabrika/proxy-core/headers'
@@ -48,6 +49,12 @@ const record = <T extends z.core.$ZodType>(value: T) => z.record(z.string().min(
48
49
  /** A contract's actions are exact: IAM treats `*` as a pattern, which would widen every grant naming it. */
49
50
  const action = name.refine((value) => !value.includes('*'), 'an action is exact; * is not an action')
50
51
  const actions = z.array(action)
52
+ /** A file's object key starts with its kind: the framework keeps its own objects in the files bucket under this prefix. */
53
+ export const RESERVED_FILE_KIND_PREFIX = '__fabrika'
54
+ const fileKindName = name.refine(
55
+ (kind) => !kind.startsWith(RESERVED_FILE_KIND_PREFIX),
56
+ `a file kind name the framework reserves (${RESERVED_FILE_KIND_PREFIX}*)`,
57
+ )
51
58
  /** IAM's own role keys win over an application role of the same key at resolution. */
52
59
  const roleKey = name.refine((key) => !BUILTIN_ROLE_KEYS.includes(key), 'a built-in IAM role key is not a contract role name')
53
60
 
@@ -356,7 +363,7 @@ export const contractArtifactSchema: z.ZodType<ContractArtifact> = z.strictObjec
356
363
  link: z.union([z.boolean(), z.array(name).nonempty()]),
357
364
  scan: z.literal(true).optional(),
358
365
  })),
359
- fileKinds: z.record(name, z.strictObject({ types: names, maxBytes: z.int().positive(), scan: z.literal(true).optional() })).optional(),
366
+ fileKinds: z.record(fileKindName, z.strictObject({ types: names, maxBytes: z.int().positive(), scan: z.literal(true).optional() })).optional(),
360
367
  jobs: record(z.strictObject({
361
368
  schedule: name,
362
369
  actions,
@@ -425,6 +432,7 @@ export const contractArtifactSchema: z.ZodType<ContractArtifact> = z.strictObjec
425
432
  .optional(),
426
433
  members: z.strictObject({ manage: action, list: action }).optional(),
427
434
  directory: z.literal('labels').optional(),
435
+ terminal: z.strictObject({ identify: z.string().refine((path) => terminalIdentifyProblem(path) === null, 'not an identification path') }).optional(),
428
436
  procedures: record(z.strictObject({
429
437
  rate: z.strictObject({
430
438
  perClient: bucket,
@@ -13,6 +13,7 @@ import {
13
13
  type CapabilityAccessForm,
14
14
  type CapabilityRequirement,
15
15
  type ChallengeProvider,
16
+ compileEndpointTable,
16
17
  CONTRACT_FORMAT,
17
18
  type ContractArtifact,
18
19
  type CspExtensions,
@@ -48,6 +49,7 @@ import {
48
49
  type MessageKind,
49
50
  type MountArtifact,
50
51
  type OutputShape,
52
+ planEndpoint,
51
53
  type ProcedureArtifact,
52
54
  type ProcedureChallenge,
53
55
  type RoleArtifact,
@@ -55,12 +57,15 @@ import {
55
57
  type ScopeBinding,
56
58
  tableActions,
57
59
  type TablePolicyArtifact,
60
+ type TerminalArtifact,
61
+ terminalIdentifyProblem,
58
62
  type TokenPurposeArtifact,
59
63
  type WebhookScheme,
60
64
  } from '@fabrika/auth-core'
61
65
  import { isPolicyOrigin, MAX_CSP_ORIGINS, WORKER_BLOB_SOURCE } from '@fabrika/proxy-core/headers'
62
66
  import { z } from 'zod/v4'
63
- import { contractArtifactSchema } from './artifact-schema'
67
+ import { CONTRACT_APP_ID_PATTERN as APP_ID } from './app-id'
68
+ import { contractArtifactSchema, RESERVED_FILE_KIND_PREFIX } from './artifact-schema'
64
69
  import {
65
70
  type AccessDeclaration,
66
71
  type Builder,
@@ -117,7 +122,6 @@ import { ContractError, Problems } from './problems'
117
122
  import { TOKEN_MAX_DAYS } from './token'
118
123
  import { hmacSchemeSchema, WEBHOOK_SCHEME_ALLOWED, webhookSchemeSchema } from './webhook-scheme'
119
124
 
120
- const APP_ID = /^[a-z0-9][a-z0-9-]*$/
121
125
  const NAME = /^[A-Za-z][A-Za-z0-9_]*$/
122
126
  const DIMENSION = /^[a-z][A-Za-z0-9_]*$/
123
127
  const ACTION = /^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*)+$/
@@ -234,6 +238,7 @@ class ArtifactBuilder {
234
238
  const displayName = this.#displayName()
235
239
  const mail = this.#mail()
236
240
  const people = this.#people()
241
+ const terminal = this.#terminal()
237
242
  const artifact: ContractArtifact = {
238
243
  format: CONTRACT_FORMAT,
239
244
  app: contract.app,
@@ -256,6 +261,7 @@ class ArtifactBuilder {
256
261
  ...(displayName === null ? {} : { displayName }),
257
262
  ...(mail === null ? {} : { mail }),
258
263
  ...people,
264
+ ...(terminal === null ? {} : { terminal }),
259
265
  ...(Object.keys(this.#procedureRules).length === 0 ? {} : { procedures: this.#procedureRules }),
260
266
  ...(Object.keys(tokens).length === 0 ? {} : { tokens }),
261
267
  }
@@ -263,10 +269,38 @@ class ArtifactBuilder {
263
269
  assertNoAmbiguity(artifact)
264
270
  } catch (error) {
265
271
  this.#problem('endpoints', error instanceof Error ? error.message : String(error))
272
+ return artifact
273
+ }
274
+ if (terminal !== null) {
275
+ this.#checkIdentifyPage(artifact, terminal)
266
276
  }
267
277
  return artifact
268
278
  }
269
279
 
280
+ /** The terminal's identification page, when its path is one. */
281
+ #terminal(): TerminalArtifact | null {
282
+ const terminal = this.#contract.terminal
283
+ if (terminal === undefined) return null
284
+ const problem = terminalIdentifyProblem(terminal.identify)
285
+ if (problem !== null) {
286
+ this.#problem('terminal.identify', `'${terminal.identify}' ${problem}`)
287
+ return null
288
+ }
289
+ return { identify: terminal.identify }
290
+ }
291
+
292
+ /**
293
+ * Nobody is signed in on the identification page, so a public SPA mount must serve it: under a credentialed one, the
294
+ * proxy would bounce the terminal's browser back to sign-in, which sends it to the page again.
295
+ */
296
+ #checkIdentifyPage(artifact: ContractArtifact, terminal: TerminalArtifact): void {
297
+ const plan = planEndpoint(compileEndpointTable(artifact), 'GET', terminal.identify)
298
+ if (plan.outcome !== 'endpoint' || plan.endpoint.kind !== 'public-spa') {
299
+ const served = plan.outcome === 'endpoint' ? `'${plan.endpoint.id}' (${plan.endpoint.kind})` : 'no endpoint'
300
+ this.#problem('terminal.identify', `'${terminal.identify}' is served by ${served}; serve it from an spa mount with access: { public: true }`)
301
+ }
302
+ }
303
+
270
304
  /** The member directory each endpoint reads, recorded so the approval and the digest cover the reach. */
271
305
  #directories(dimensions: ContractArtifact['dimensions']): Record<string, EndpointDirectory> {
272
306
  const directories: Record<string, EndpointDirectory> = {}
@@ -1678,6 +1712,10 @@ class ArtifactBuilder {
1678
1712
  const kinds: Record<string, FileKindArtifact> = {}
1679
1713
  for (const [name, declared] of Object.entries(this.#contract.files)) {
1680
1714
  const where = `files '${name}'`
1715
+ if (name.startsWith(RESERVED_FILE_KIND_PREFIX)) {
1716
+ this.#problem(where, `is a file kind name the framework reserves (${RESERVED_FILE_KIND_PREFIX}*)`)
1717
+ continue
1718
+ }
1681
1719
  if (!this.#name(where, name) || !this.#kind(where, declared, 'file-kind', 'c.files({ types, maxBytes, scan? })')) {
1682
1720
  continue
1683
1721
  }
@@ -81,6 +81,7 @@ export function describeContract(contract: AnyContract): ContractDeclaration<Sch
81
81
  ...(vocabulary.mail === undefined ? {} : { mail: vocabulary.mail }),
82
82
  ...(vocabulary.members === undefined ? {} : { members: vocabulary.members }),
83
83
  ...(vocabulary.directory === undefined ? {} : { directory: vocabulary.directory }),
84
+ ...(vocabulary.terminal === undefined ? {} : { terminal: { identify: vocabulary.terminal.identify } }),
84
85
  }
85
86
  }
86
87
 
@@ -25,6 +25,7 @@ import type { StoredFilesHandle, StoredFilesReadHandle } from '../files/handle'
25
25
  import type { AppCapability, Ref, Within } from '../implement/capability'
26
26
  import type { ApplicationDirectory, LinkIssuing, MemberDirectory, MemberLookup, MemberManagement } from '../implement/membership'
27
27
  import type { AppPrincipal, PrincipalOf, PublicPrincipal, ServicePrincipal } from '../implement/principal'
28
+ import type { TerminalIdentification } from '../implement/terminals'
28
29
  import type { CapabilityOf, ConnectCall, RequestContext } from '../implement/types'
29
30
  import type { WebhookDelivery, WebhookPrincipal } from '../implement/webhook'
30
31
  import type { AppMail, JobContext } from '../jobs/types'
@@ -56,6 +57,8 @@ export interface KitTypes {
56
57
  readonly dimensions: unknown
57
58
  /** The actions of the application's own people, as written; `never` when the vocabulary declares none. */
58
59
  readonly members: { readonly manage: string; readonly list: string }
60
+ /** Whether the vocabulary declares `terminal: { identify }`, which gives `ctx.terminals`. */
61
+ readonly terminal: boolean
59
62
  readonly index: AnyDbIndex
60
63
  /** The table names of `src/db/tables.ts`. */
61
64
  readonly tables: string
@@ -115,20 +118,31 @@ export type SqlValue = string | number | boolean | bigint | Date | null | readon
115
118
  export interface SqlTag<Ix extends AnyDbIndex = AnyDbIndex, M extends SqlMode = SqlMode> {
116
119
  <Row extends Schema>(row: Row): (text: TemplateStringsArray, ...values: readonly (SqlValue | SqlScope)[]) => Promise<z.output<Row>[]>
117
120
  /**
118
- * The capability's whole predicate on `table` (`alias` its name in the statement, the table's by default): the
119
- * object's key and every link of its chain for a `Ref`, what `ctx.db.within` matches for a `Within`, every row for
120
- * `ctx.app`. Interpolated as `where ${ctx.sql.scope(ctx.target, 'tasks', 't')}`, its values are bound parameters.
121
- * A table the capability reaches for no use of this site is a type error here; at run time the fragment on the
122
- * statement's UPDATE or DELETE target needs that operation's action, and anywhere else an action the table reads
123
- * with.
121
+ * The capability's whole predicate on `table`: the object's key and every link of its chain for a `Ref`, what
122
+ * `ctx.db.within` matches for a `Within`, every row for `ctx.app`. Interpolated as
123
+ * `where ${ctx.sql.scope(ctx.target, 'tasks', { alias: 't' })}`, its values are bound parameters. `alias` is the
124
+ * table's name in the statement (the table's own by default). `use` states what the statement does with the table:
125
+ * `'read'` (the default) needs an action the table reads with, `'update'` or `'delete'` (a `'write'` site only) that
126
+ * operation's action, checked when the fragment is built. The statement is not read for where the fragment stands:
127
+ * using it as stated is the author's and the approver's to check. A table the capability reaches for no use of this
128
+ * site is a type error here.
124
129
  */
125
130
  scope<C extends Ref<string, string> | Within<string, string> | AppCapability<string>, T extends FragmentTable<Ix, C, M>>(
126
131
  capability: C,
127
132
  table: T,
128
- alias?: string,
133
+ options?: SqlScopeOptions,
129
134
  ): SqlScope
130
135
  }
131
136
 
137
+ /**
138
+ * The third argument of `ctx.sql.scope`: the table's alias in the statement, and what the statement does with it. A
139
+ * `'read'` site's `ctx.sql` is refused `'update'` and `'delete'` at run time; a `'write'` site's stays assignable to it.
140
+ */
141
+ export interface SqlScopeOptions {
142
+ readonly alias?: string
143
+ readonly use?: 'read' | 'update' | 'delete'
144
+ }
145
+
132
146
  declare const sqlScope: unique symbol
133
147
 
134
148
  /** What `ctx.sql.scope(…)` builds: only the framework makes one, and only its own tag takes it. */
@@ -357,6 +371,10 @@ type ConnectContext<K extends KitTypes, Cn extends readonly string[]> = [Cn] ext
357
371
  ? { readonly connect: Unavailable<"declare connect: ['<connector>'] on this endpoint to call another application"> }
358
372
  : { readonly connect: { readonly [N in Cn[number]]: ConnectorOf<K['imports'][N]> } }
359
373
 
374
+ /** `ctx.terminals`, where the vocabulary declares the terminal identification page. */
375
+ type TerminalsContext<K extends KitTypes> = K['terminal'] extends true ? { readonly terminals: TerminalIdentification }
376
+ : { readonly terminals: Unavailable<"the application declares no terminal: terminal: { identify: '/identify' } in the vocabulary"> }
377
+
360
378
  /** What the handler of an RPC endpoint receives, for mount callers `Caller`, kind `Kind` and its declaration. */
361
379
  export type EndpointContext<
362
380
  K extends KitTypes,
@@ -370,6 +388,7 @@ export type EndpointContext<
370
388
  & MembersContext<K, Acc>
371
389
  & LinksContext<Acc, Of<D, 'issues'>>
372
390
  & ConnectContext<K, Of<D, 'connect'>>
391
+ & TerminalsContext<K>
373
392
  & SqlContext<Of<D, 'sql'>, K['index']>
374
393
  & FilesContext<K['index'], Kind>
375
394
  & { readonly db: DataOf<K['index'], EndpointData<K['index'], Kind, Acc, Of<D, 'unscoped'>>> }
@@ -396,6 +415,7 @@ export type PublicContext<K extends KitTypes, Kind extends DataKind, Acts extend
396
415
  readonly files: Kind extends 'query' ? StoredFilesReadHandle : StoredFilesHandle
397
416
  readonly sql: Unavailable<'a public procedure reaches its actions only: it declares no sql'>
398
417
  }
418
+ & TerminalsContext<K>
399
419
  & {
400
420
  readonly db: DataOf<
401
421
  K['index'],
@@ -411,13 +431,19 @@ export type PublicContext<K extends KitTypes, Kind extends DataKind, Acts extend
411
431
 
412
432
  /**
413
433
  * `ctx.kick('<job>')` of a site that declares `kicks`: the job runs in the background after the site's transaction
414
- * committed, once however often it is kicked, and not at all on a rollback.
434
+ * committed, once however often it is kicked, and not at all on a rollback. `ctx.kick('<job>', { at })` runs it at `at`
435
+ * instead. Either way the kick is a durable wake written in the site's transaction, and it carries nothing.
415
436
  */
416
437
  export type KickContext<Ks> = [Ks] extends [never]
417
438
  ? { readonly kick: Unavailable<"declare kicks: ['<cron job>'] on this site to kick a job after its commit"> }
418
- : Ks extends readonly (infer N extends string)[] ? { kick(job: N): void }
439
+ : Ks extends readonly (infer N extends string)[] ? { kick(job: N, options?: KickOptions): void }
419
440
  : never
420
441
 
442
+ /** When a kicked job runs: at `at`, a `Date`; without options, as soon as the site committed. */
443
+ export interface KickOptions {
444
+ readonly at: Date
445
+ }
446
+
421
447
  /** `ctx.tokens.sign('<purpose>', claims, { days })` of a site that declares `signs`: a token of one of those purposes. */
422
448
  export type TokensContext<K extends KitTypes, Sg> = [Sg] extends [never]
423
449
  ? { readonly tokens: Unavailable<"declare signs: ['<token purpose>'] on this site to sign its tokens"> }
@@ -26,6 +26,8 @@ export interface ContractDeclaration<S> {
26
26
  readonly members?: { readonly manage: string; readonly list: string }
27
27
  /** `'labels'` only; `buildArtifact` refuses another value, and refuses it without `members`. */
28
28
  readonly directory?: string
29
+ /** The identification page of a terminal; `buildArtifact` refuses a path a public SPA mount does not serve. */
30
+ readonly terminal?: { readonly identify: string }
29
31
  }
30
32
 
31
33
  /**
@@ -29,6 +29,17 @@ export const PROCEDURE_LIMITS = {
29
29
  maxPartHeaderBytes: 8 * 1024,
30
30
  } as const
31
31
 
32
+ /**
33
+ * The slowest body a procedure or a webhook waits for: its deadline is `maxBytes` at `bytesPerSecond`, `minMs` at least.
34
+ * The handler's own `timeoutMs` starts after the last byte, so the approval diff names both.
35
+ */
36
+ export const BODY_DEADLINE = { bytesPerSecond: 16 * 1024, minMs: 30_000 } as const
37
+
38
+ /** How long a body of at most `maxBytes` may take to arrive. */
39
+ export function bodyDeadlineMs(maxBytes: number): number {
40
+ return Math.max(BODY_DEADLINE.minMs, Math.ceil((maxBytes / BODY_DEADLINE.bytesPerSecond) * 1000))
41
+ }
42
+
32
43
  /**
33
44
  * A procedure with file fields is `multipart/form-data`: its JSON input travels in the first part, named `input`, and
34
45
  * each file in a part named after its field. A field of several files sends one part per file, under its name.
@@ -46,9 +57,18 @@ export const WEBHOOK_LIMITS = {
46
57
  timeoutMs: PROCEDURE_LIMITS.timeoutMs,
47
58
  } as const
48
59
 
49
- /** A job attempt's time limit (`limits.timeoutMs`) and its ceiling, which keeps a lease and a timer within a day. */
60
+ /**
61
+ * The longest job segment on Cloudflare: setup, one attempt and its finish. A framework policy inside the 15 minutes
62
+ * `waitUntil` keeps an object alive, not a platform guarantee; longer work chunks through claims.
63
+ */
64
+ export const CLOUDFLARE_MAX_JOB_SEGMENT_MS = 14 * 60_000
65
+
66
+ /**
67
+ * A job attempt's time limit (`limits.timeoutMs`) and its ceiling, which keeps a lease and a timer within a day. The
68
+ * default is one Cloudflare segment, so a job that declares no limit deploys on either provider.
69
+ */
50
70
  export const JOB_LIMITS = {
51
- timeoutMs: 15 * 60_000,
71
+ timeoutMs: CLOUDFLARE_MAX_JOB_SEGMENT_MS,
52
72
  maxTimeoutMs: 24 * 60 * 60_000,
53
73
  } as const
54
74
 
@@ -26,7 +26,12 @@ import type { TokenPurposes } from './token'
26
26
 
27
27
  export type Path = `/${string}`
28
28
 
29
- /** A job attempt's time limit: 15 minutes by default, at most a day. A job reads no body, so it has no `maxBytes`. */
29
+ /** Whether `value` is written as a `Path`; what `buildArtifact` refuses of one is a separate check. */
30
+ export function isPath(value: string): value is Path {
31
+ return value.startsWith('/')
32
+ }
33
+
34
+ /** A job attempt's time limit: 14 minutes by default, at most a day. A job reads no body, so it has no `maxBytes`. */
30
35
  export interface JobLimitsOption {
31
36
  readonly timeoutMs?: number
32
37
  }
@@ -92,7 +97,7 @@ export interface RoleDef<A extends string, D extends string, R extends string> {
92
97
  readonly external?: true
93
98
  }
94
99
 
95
- export interface Vocabulary<A extends string, D extends string, R extends string> extends Presentation, AppPeople<A> {
100
+ export interface Vocabulary<A extends string, D extends string, R extends string> extends Presentation, AppPeople<A>, AppTerminal {
96
101
  readonly app: string
97
102
  readonly dimensions: { readonly [K in D]: DimensionDef<A, D, R> }
98
103
  readonly actions: { readonly [K in A]: string }
@@ -124,6 +129,26 @@ export function peopleOf<A extends string>(vocabulary: AppPeople<A>): AppPeople<
124
129
  }
125
130
  }
126
131
 
132
+ /** The page that identifies a person at an enrolled terminal (ADR-0067). */
133
+ export interface TerminalDeclaration {
134
+ /** An absolute path on the application's own origin, served by a public SPA mount; IAM appends `?identification=<id>`. */
135
+ readonly identify: Path
136
+ }
137
+
138
+ /**
139
+ * `terminal: { identify: '/identify' }`: the application identifies a person at an enrolled terminal on that page and
140
+ * asserts who stands there (`ctx.terminals`). IAM sends a terminal's browser there only for an application its
141
+ * administrator lists on the terminal. A reviewed declaration.
142
+ */
143
+ export interface AppTerminal {
144
+ readonly terminal?: TerminalDeclaration
145
+ }
146
+
147
+ /** A vocabulary's terminal, copied field by field: it exists only when declared. */
148
+ export function terminalOf(vocabulary: AppTerminal): AppTerminal {
149
+ return vocabulary.terminal === undefined ? {} : { terminal: { identify: vocabulary.terminal.identify } }
150
+ }
151
+
127
152
  /** How IAM names the application to a person: on its sign-in, password and invitation pages, and in its e-mails. */
128
153
  export interface Presentation {
129
154
  /** The language of those pages and e-mails; absent, the installation's default. */
@@ -535,7 +560,7 @@ export function defineContract<
535
560
  const Dims extends { readonly [K in D]: DimensionDef<NoInfer<A>, NoInfer<D>, NoInfer<R>> },
536
561
  const S extends Surface,
537
562
  >(
538
- vocabulary: Presentation & AppPeople<NoInfer<A>> & {
563
+ vocabulary: Presentation & AppPeople<NoInfer<A>> & AppTerminal & {
539
564
  readonly app: string
540
565
  readonly dimensions: Dims & { readonly [K in D]: DimensionDef<NoInfer<A>, NoInfer<D>, NoInfer<R>> }
541
566
  readonly actions: { readonly [K in A]: K extends `${string}*${string}` ? WildcardMessage : string }
@@ -551,6 +576,7 @@ export function defineContract<
551
576
  roles: vocabulary.roles,
552
577
  ...presentationOf(vocabulary),
553
578
  ...peopleOf(vocabulary),
579
+ ...terminalOf(vocabulary),
554
580
  },
555
581
  dimensions: vocabulary.dimensions,
556
582
  surface: surface(surfaceKit()),
@@ -45,6 +45,7 @@ import {
45
45
  type Schema,
46
46
  type Surface,
47
47
  surfaceKit,
48
+ terminalOf,
48
49
  type WebhookMount,
49
50
  } from './define'
50
51
  import type {
@@ -73,13 +74,14 @@ type Owned<K extends string> = { readonly [P in K]?: never }
73
74
 
74
75
  /** The kit's types, computed once from the vocabulary, the tables' index, the imports and the token purposes. */
75
76
  export type KitOf<V, Ix, Imp extends KitImports, Tk extends TokenPurposes = Record<never, never>> = V extends
76
- AppVocabulary<infer A, infer D, infer R, infer Dims, infer M> ? {
77
+ AppVocabulary<infer A, infer D, infer R, infer Dims, infer M, infer T> ? {
77
78
  readonly action: A
78
79
  readonly dimension: D
79
80
  readonly creatable: CreatableDimension<Dims>
80
81
  readonly role: R
81
82
  readonly dimensions: Dims
82
83
  readonly members: M
84
+ readonly terminal: [T] extends [never] ? false : true
83
85
  readonly index: Ix
84
86
  readonly tables: Ix extends { readonly tables: infer T } ? keyof T & string : never
85
87
  readonly imports: Imp
@@ -555,6 +557,7 @@ function runtimeApp(vocabulary: AnyAppVocabulary, options: KitOptions | undefine
555
557
  roles: vocabulary.roles,
556
558
  ...presentationOf(vocabulary),
557
559
  ...peopleOf(vocabulary),
560
+ ...terminalOf(vocabulary),
558
561
  },
559
562
  dimensions: vocabulary.dimensions,
560
563
  surface: declared,
@@ -23,8 +23,8 @@ import {
23
23
  /**
24
24
  * The IAM vocabulary of a contract application, marked `contract` so IAM refuses every wildcard written for it: the
25
25
  * dimensions as scopes with their container, creator role and members actions; the actions; the roles, a membership
26
- * role with its scope and the roles that may assign it; the link mounts; the delegations; the workloads; and the locale,
27
- * display name and e-mail wording IAM names the application with. Every artifact
26
+ * role with its scope and the roles that may assign it; the link mounts; the delegations; the workloads; the locale,
27
+ * display name and e-mail wording IAM names the application with; and its terminal identification page. Every artifact
28
28
  * dimension is a scope, a file collection's `file:<name>` included, because access to a file is checked there.
29
29
  */
30
30
  export function schemaFromContract(artifact: ContractArtifact): AppSchema {
@@ -46,6 +46,7 @@ export function schemaFromContract(artifact: ContractArtifact): AppSchema {
46
46
  ...(artifact.mail === undefined ? {} : { mail: artifact.mail }),
47
47
  ...(artifact.members === undefined ? {} : { members: { manage: artifact.members.manage, list: artifact.members.list } }),
48
48
  ...(artifact.directory === 'labels' ? { directory: 'labels' } : {}),
49
+ ...(artifact.terminal === undefined ? {} : { terminal: { identify: artifact.terminal.identify } }),
49
50
  }
50
51
  }
51
52
 
@@ -2,20 +2,35 @@
2
2
  // nothing else, so the tables, the kit, the groups and the contract can each be typed by it without a cycle.
3
3
  // Browser-safe: plain data.
4
4
 
5
- import { type AppMembers, type DimensionDef, type Presentation, presentationOf, type RoleDefs, type Vocabulary, type WildcardMessage } from './define'
5
+ import {
6
+ type AppMembers,
7
+ type DimensionDef,
8
+ type Presentation,
9
+ presentationOf,
10
+ type RoleDefs,
11
+ type TerminalDeclaration,
12
+ type Vocabulary,
13
+ type WildcardMessage,
14
+ } from './define'
6
15
 
7
16
  /**
8
- * The vocabulary as `defineVocabulary` returned it, with its literal names, dimension definitions and the actions of its
9
- * people (`M`, `never` when it declares none).
17
+ * The vocabulary as `defineVocabulary` returned it, with its literal names, dimension definitions, the actions of its
18
+ * people (`M`, `never` when it declares none) and its terminal (`T`, `never` when it declares none).
10
19
  */
11
- export interface AppVocabulary<A extends string, D extends string, R extends string, Dims, M extends AppMembers<A> = never>
12
- extends Vocabulary<A, D, R>
13
- {
20
+ export interface AppVocabulary<
21
+ A extends string,
22
+ D extends string,
23
+ R extends string,
24
+ Dims,
25
+ M extends AppMembers<A> = never,
26
+ T extends TerminalDeclaration = never,
27
+ > extends Vocabulary<A, D, R> {
14
28
  readonly dimensions: Dims & { readonly [K in D]: DimensionDef<A, D, R> }
15
29
  readonly members?: M
30
+ readonly terminal?: T
16
31
  }
17
32
 
18
- export type AnyAppVocabulary = AppVocabulary<string, string, string, unknown, AppMembers<string>>
33
+ export type AnyAppVocabulary = AppVocabulary<string, string, string, unknown, AppMembers<string>, TerminalDeclaration>
19
34
 
20
35
  /**
21
36
  * Declares the dimensions, actions and roles, and how IAM names the application (`locale`, `displayName`). `src/vocabulary.ts` exports it; `defineTables`, `defineApp` and the
@@ -27,6 +42,7 @@ export function defineVocabulary<
27
42
  const R extends string,
28
43
  const Dims extends { readonly [K in D]: DimensionDef<NoInfer<A>, NoInfer<D>, NoInfer<R>> },
29
44
  const M extends AppMembers<NoInfer<A>> = never,
45
+ const T extends TerminalDeclaration = never,
30
46
  >(
31
47
  vocabulary: Presentation & {
32
48
  readonly app: string
@@ -35,8 +51,9 @@ export function defineVocabulary<
35
51
  readonly roles: RoleDefs<NoInfer<A>, NoInfer<D>, R>
36
52
  readonly members?: M
37
53
  readonly directory?: 'labels'
54
+ readonly terminal?: T
38
55
  },
39
- ): AppVocabulary<A, D, R, Dims, M> {
56
+ ): AppVocabulary<A, D, R, Dims, M, T> {
40
57
  const people = vocabulary.members
41
58
  return {
42
59
  app: vocabulary.app,
@@ -46,5 +63,6 @@ export function defineVocabulary<
46
63
  ...presentationOf(vocabulary),
47
64
  ...(people === undefined ? {} : { members: people }),
48
65
  ...(vocabulary.directory === undefined ? {} : { directory: vocabulary.directory }),
66
+ ...(vocabulary.terminal === undefined ? {} : { terminal: vocabulary.terminal }),
49
67
  }
50
68
  }
@@ -3,8 +3,11 @@
3
3
  // runtime credential only. It holds a long poll on Control's source receiver (ADR-0064); a new head brings the changed
4
4
  // files, which it writes, then it migrates when `db/migrations/` changed, runs the SPA commands when a web source
5
5
  // changed, and respawns the application. A change the build owns is refused with one line: it needs a bootstrap run.
6
+ // A new container migrates and verifies its schema here, not in an init command: only after Control said whether a reset
7
+ // is pending, since the database still holds what the previous container left.
6
8
 
7
9
  import {
10
+ DEV_LAUNCHER_BOOTED_FILE,
8
11
  DEV_LAUNCHER_CONFIG_FILE,
9
12
  DEV_LAUNCHER_STATE_FILE,
10
13
  type DevLauncherConfig,
@@ -91,6 +94,13 @@ async function readState(root: string, config: DevLauncherConfig): Promise<Launc
91
94
  return parsed?.success === true ? parsed.data : { head: config.head, reset: null, checks: null }
92
95
  }
93
96
 
97
+ /**
98
+ * `fabrika db codegen --verify` of the CLI that runs the configured `fabrika db migrate`. The configuration names no
99
+ * command for it, and a key of its own would fail the strict reader of every earlier 0.9 launcher.
100
+ */
101
+ const verifyCommand = (migrate: readonly string[]): readonly string[] | null =>
102
+ migrate.at(-2) === 'db' && migrate.at(-1) === 'migrate' ? [...migrate.slice(0, -1), 'codegen', '--verify'] : null
103
+
94
104
  export interface DevSourceTransport {
95
105
  readonly url: string
96
106
  readonly key: string
@@ -188,6 +198,8 @@ class Launcher {
188
198
  private reportFailing = false
189
199
  /** A newer bootstrap run replaced this container: it keeps serving until the platform stops it, and asks nothing. */
190
200
  private superseded = false
201
+ /** A new container checks the schema types at boot, as a bootstrap does; a restarted one holds synced files instead. */
202
+ private verifyAtBoot = false
191
203
 
192
204
  constructor(private readonly options: DevLauncherOptions) {
193
205
  this.root = options.root
@@ -207,9 +219,25 @@ class Launcher {
207
219
  }
208
220
 
209
221
  async start(): Promise<void> {
222
+ const booted = join(this.root, DEV_LAUNCHER_BOOTED_FILE)
223
+ await rm(booted, { force: true })
210
224
  this.state = await readState(this.root, this.config)
211
- const answer = await this.firstAnswer()
212
- await this.enqueue(() => this.apply(answer ?? { sync: null, reset: this.state.reset ?? 0, checks: this.state.checks ?? 0 }, true))
225
+ const fresh = this.state.reset === null
226
+ this.verifyAtBoot = fresh
227
+ let answer = await this.firstAnswer()
228
+ // A new container's first answer carries the reset generation the previous container applied; the second, any
229
+ // reset still pending, which the boot then runs before it migrates over the previous container's schema.
230
+ if (fresh && answer !== null && !this.superseded) {
231
+ this.state = { ...this.state, reset: answer.reset, checks: answer.checks }
232
+ answer = (await this.firstAnswer()) ?? answer
233
+ }
234
+ const boot = answer ?? { sync: null, reset: this.state.reset ?? 0, checks: this.state.checks ?? 0 }
235
+ try {
236
+ await this.enqueue(() => this.apply(boot, true))
237
+ } finally {
238
+ await mkdir(dirname(booted), { recursive: true })
239
+ await writeFile(booted, '')
240
+ }
213
241
  void this.follow()
214
242
  }
215
243
 
@@ -350,12 +378,16 @@ class Launcher {
350
378
  spaFailure = outcome.spaFailure
351
379
  }
352
380
  }
353
- if (changed || reset) await this.converge({ migrate: migrate || reset, reset, spaFailure, resetTo: answer.reset })
381
+ if (changed || reset) {
382
+ await this.converge({ migrate: migrate || reset, verify: (boot && this.verifyAtBoot) || reset, reset, spaFailure, resetTo: answer.reset })
383
+ }
354
384
  if (answer.checks > (this.state.checks ?? answer.checks)) await this.check(answer.checks)
355
385
  }
356
386
 
357
387
  /** Bring the database, the SPA and the running application to the files on disk, then report. */
358
- private async converge(steps: { migrate: boolean; reset: boolean; spaFailure: string | null; resetTo: number }): Promise<void> {
388
+ private async converge(
389
+ steps: { migrate: boolean; verify: boolean; reset: boolean; spaFailure: string | null; resetTo: number },
390
+ ): Promise<void> {
359
391
  this.status = steps.reset ? 'resetting' : 'syncing'
360
392
  void this.report()
361
393
  let failure: string | null = null
@@ -366,6 +398,7 @@ class Launcher {
366
398
  this.state = { ...this.state, reset: steps.resetTo }
367
399
  }
368
400
  if (failure === null && steps.migrate) failure = await this.timed('the migration', () => this.migrate())
401
+ if (failure === null && steps.verify) failure = await this.timed('the schema check', () => this.verifySchema())
369
402
  if (failure === null) failure = steps.spaFailure
370
403
  const served = await this.timed('the restart until healthy', () => this.restartApplication())
371
404
  failure ??= served
@@ -474,6 +507,19 @@ class Launcher {
474
507
  return `fabrika db migrate failed: ${lastLine(result)}; if an applied migration changed, call reset_dev`
475
508
  }
476
509
 
510
+ /** The committed schema types against the migrated schema, as a bootstrap verifies them: at a new container's boot and after a reset. */
511
+ private async verifySchema(): Promise<string | null> {
512
+ const command = verifyCommand(this.config.migrate)
513
+ if (this.provisioningUrl === null || command === null) return null
514
+ const result = await this.run(command, {
515
+ ...this.commandEnvironment,
516
+ FABRIKA_APP_ID: this.config.appId,
517
+ [PROVISIONING_DATABASE_URL]: this.provisioningUrl,
518
+ })
519
+ if (result.exitCode === 0) return null
520
+ return `fabrika db codegen --verify failed: ${lastLine(result)}; if the database holds another commit's schema, call reset_dev`
521
+ }
522
+
477
523
  private async resetDatabase(): Promise<string | null> {
478
524
  if (this.provisioningUrl === null) return null
479
525
  this.say(`dropping the schema and roles of ${this.config.appId}`)
@@ -4,8 +4,12 @@
4
4
  import { rawRequestTarget } from '@fabrika/auth-core'
5
5
  import { join, resolve, sep } from 'node:path'
6
6
  import type { SpaAssets } from './implement/dispatch.js'
7
+ import { isPageRoute } from './spa-fallback.js'
7
8
 
8
- /** Serves each SPA mount from its build directory under `root`; a path that names no file gets the SPA's `index.html`. */
9
+ /**
10
+ * Serves each SPA mount from its build directory under `root`; a page route that names no file gets the SPA's
11
+ * `index.html` (`isPageRoute`), and a missing asset is 404.
12
+ */
9
13
  export function diskAssets(root: string): SpaAssets {
10
14
  return {
11
15
  async serve(mount, request) {
@@ -15,8 +19,9 @@ export function diskAssets(root: string): SpaAssets {
15
19
  // The path is canonical, so every segment decodes and none is `.` or `..`.
16
20
  const file = join(dir, ...relative.split('/').filter((segment) => segment !== '').map((segment) => decodeURIComponent(segment)))
17
21
  const candidate = file.startsWith(`${dir}${sep}`) ? Bun.file(file) : null
18
- const served = candidate !== null && (await candidate.exists()) ? candidate : Bun.file(join(dir, 'index.html'))
19
- if (!(await served.exists())) {
22
+ const found = candidate !== null && (await candidate.exists()) ? candidate : null
23
+ const served = found ?? (isPageRoute(request) ? Bun.file(join(dir, 'index.html')) : null)
24
+ if (served === null || !(await served.exists())) {
20
25
  return new Response('Not found', { status: 404 })
21
26
  }
22
27
  return new Response(served)
@@ -4,7 +4,7 @@
4
4
  // stored or deflated entries, no encryption, a layout in which every byte belongs to an entry or the directory, sizes
5
5
  // and CRCs that match, bounded counts and sizes, and nested ZIPs to a small depth. Any other archive is refused.
6
6
 
7
- import { inflateRawSync } from 'node:zlib'
7
+ import { crc32, inflateRawSync } from 'node:zlib'
8
8
 
9
9
  export const ARCHIVE_LIMITS = {
10
10
  /** Entries of one archive, nested ones counted with their parent's. */
@@ -236,7 +236,7 @@ function unpacked(entry: Entry, data: Uint8Array, budget: Budget): Uint8Array {
236
236
  throw new Refused('malformed')
237
237
  }
238
238
  }
239
- if (content.length !== entry.uncompressed || Bun.hash.crc32(content) !== entry.crc) throw new Refused('malformed')
239
+ if (content.length !== entry.uncompressed || crc32(content) !== entry.crc) throw new Refused('malformed')
240
240
  return content
241
241
  }
242
242