@fabrika/app 0.9.0-dev.1 → 0.9.0-dev.10

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 (222) hide show
  1. package/package.json +32 -26
  2. package/skill/SKILL.md +46 -15
  3. package/skill/references/app-setup.md +43 -12
  4. package/skill/references/dev.md +5 -2
  5. package/skill/references/endpoint.md +39 -28
  6. package/skill/references/errors.md +50 -37
  7. package/skill/references/files.md +8 -4
  8. package/skill/references/jobs.md +39 -7
  9. package/skill/references/table-and-migration.md +47 -3
  10. package/skill/references/tests.md +61 -10
  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 +888 -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/capability-cases.ts +30 -0
  30. package/src/contract/compile.ts +1 -0
  31. package/src/contract/containers.ts +19 -0
  32. package/src/contract/context.ts +35 -9
  33. package/src/contract/declaration.ts +2 -0
  34. package/src/contract/defaults.ts +22 -2
  35. package/src/contract/define.ts +29 -3
  36. package/src/contract/index.ts +1 -0
  37. package/src/contract/kit.ts +4 -1
  38. package/src/contract/platform.ts +3 -2
  39. package/src/contract/vocabulary.ts +26 -8
  40. package/src/dev/changes.ts +5 -43
  41. package/src/dev/contract-digest.ts +17 -0
  42. package/src/dev/index.ts +1 -1
  43. package/src/dev/launcher.ts +197 -41
  44. package/src/dev/output.ts +13 -3
  45. package/src/dev/wire.ts +11 -1
  46. package/src/disk-assets.ts +8 -3
  47. package/src/files/archive.ts +2 -2
  48. package/src/files/handle.ts +2 -1
  49. package/src/files/job-names.ts +12 -0
  50. package/src/files/kinds.ts +74 -32
  51. package/src/files/scan.ts +3 -4
  52. package/src/files/streams.ts +3 -1
  53. package/src/implement/anonymous.ts +12 -11
  54. package/src/implement/boot.ts +84 -27
  55. package/src/implement/bounded.ts +21 -2
  56. package/src/implement/capability.ts +16 -4
  57. package/src/implement/dispatch.ts +423 -178
  58. package/src/implement/failures.ts +59 -4
  59. package/src/implement/faults.ts +5 -1
  60. package/src/implement/index.ts +1 -0
  61. package/src/implement/invocation.ts +62 -11
  62. package/src/implement/principal.ts +25 -2
  63. package/src/implement/terminals.ts +93 -0
  64. package/src/implement/tokens.ts +4 -2
  65. package/src/implement/types.ts +22 -4
  66. package/src/implement/workload.ts +42 -16
  67. package/src/jobs/mail.ts +8 -0
  68. package/src/jobs/report.ts +5 -1
  69. package/src/jobs/runner.ts +702 -126
  70. package/src/jobs/schedule.ts +7 -1
  71. package/src/jobs/scrub.ts +14 -1
  72. package/src/jobs/types.ts +6 -0
  73. package/src/spa-fallback.ts +12 -0
  74. package/src/testing/endpoint-access.ts +331 -169
  75. package/src/testing/index.ts +1 -1
  76. package/src/testing/isolation.ts +8 -1
  77. package/src/testing/kit.ts +86 -4
  78. package/src/testing/policy-isolation.ts +2 -2
  79. package/src/testing/proxy.ts +15 -10
  80. package/types/src/agent-skill.d.ts +29 -0
  81. package/types/src/build-recipe.d.ts +70 -0
  82. package/types/src/build.d.ts +29 -0
  83. package/types/src/bun.d.ts +99 -0
  84. package/types/src/client/caller.d.ts +19 -0
  85. package/types/src/client/contract.d.ts +131 -0
  86. package/types/src/client/error-reporting.d.ts +66 -0
  87. package/types/src/client/index.d.ts +4 -0
  88. package/types/src/client/rpc.d.ts +14 -0
  89. package/types/src/client/share.d.ts +2 -0
  90. package/types/src/client/transport.d.ts +42 -0
  91. package/types/src/cloudflare/application.d.ts +73 -0
  92. package/types/src/cloudflare/bindings.d.ts +33 -0
  93. package/types/src/cloudflare/export.d.ts +16 -0
  94. package/types/src/cloudflare/import.d.ts +47 -0
  95. package/types/src/cloudflare/maintenance.d.ts +117 -0
  96. package/types/src/cloudflare/names.d.ts +11 -0
  97. package/types/src/cloudflare/ops.d.ts +81 -0
  98. package/types/src/cloudflare/r2-files.d.ts +9 -0
  99. package/types/src/cloudflare/restore.d.ts +9 -0
  100. package/types/src/cloudflare/tracker.d.ts +29 -0
  101. package/types/src/cloudflare.d.ts +43 -0
  102. package/types/src/contract/app-id.d.ts +2 -0
  103. package/types/src/contract/artifact-schema.d.ts +10 -0
  104. package/types/src/contract/attachment.d.ts +41 -0
  105. package/types/src/contract/build.d.ts +12 -0
  106. package/types/src/contract/capability-cases.d.ts +9 -0
  107. package/types/src/contract/compile.d.ts +11 -0
  108. package/types/src/contract/connect.d.ts +51 -0
  109. package/types/src/contract/containers.d.ts +3 -0
  110. package/types/src/contract/context.d.ts +525 -0
  111. package/types/src/contract/declaration.d.ts +307 -0
  112. package/types/src/contract/defaults.d.ts +226 -0
  113. package/types/src/contract/define.d.ts +376 -0
  114. package/types/src/contract/file.d.ts +44 -0
  115. package/types/src/contract/group.d.ts +274 -0
  116. package/types/src/contract/handled.d.ts +18 -0
  117. package/types/src/contract/index.d.ts +20 -0
  118. package/types/src/contract/kit.d.ts +211 -0
  119. package/types/src/contract/platform.d.ts +9 -0
  120. package/types/src/contract/problems.d.ts +14 -0
  121. package/types/src/contract/redirect.d.ts +25 -0
  122. package/types/src/contract/schema-from-shape.d.ts +10 -0
  123. package/types/src/contract/schema-shape.d.ts +5 -0
  124. package/types/src/contract/snapshot-source.d.ts +15 -0
  125. package/types/src/contract/token.d.ts +58 -0
  126. package/types/src/contract/vocabulary.d.ts +32 -0
  127. package/types/src/contract/webhook-binding.d.ts +24 -0
  128. package/types/src/contract/webhook-scheme.d.ts +23 -0
  129. package/types/src/dev/changes.d.ts +7 -0
  130. package/types/src/dev/contract-digest.d.ts +1 -0
  131. package/types/src/dev/index.d.ts +2 -0
  132. package/types/src/dev/launcher.d.ts +32 -0
  133. package/types/src/dev/output.d.ts +28 -0
  134. package/types/src/dev/wire.d.ts +126 -0
  135. package/types/src/disk-assets.d.ts +6 -0
  136. package/types/src/errors.d.ts +46 -0
  137. package/types/src/fetch.d.ts +7 -0
  138. package/types/src/files/archive.d.ts +26 -0
  139. package/types/src/files/clamscan.d.ts +32 -0
  140. package/types/src/files/handle.d.ts +107 -0
  141. package/types/src/files/job-names.d.ts +9 -0
  142. package/types/src/files/kinds.d.ts +112 -0
  143. package/types/src/files/scan.d.ts +78 -0
  144. package/types/src/files/sniff.d.ts +7 -0
  145. package/types/src/files/streams.d.ts +17 -0
  146. package/types/src/files/treatment.d.ts +18 -0
  147. package/types/src/from-row.d.ts +20 -0
  148. package/types/src/honeypot.d.ts +2 -0
  149. package/types/src/implement/anonymous.d.ts +24 -0
  150. package/types/src/implement/attachment.d.ts +14 -0
  151. package/types/src/implement/boot.d.ts +128 -0
  152. package/types/src/implement/bounded.d.ts +32 -0
  153. package/types/src/implement/browser-config.d.ts +19 -0
  154. package/types/src/implement/capability.d.ts +142 -0
  155. package/types/src/implement/challenge.d.ts +75 -0
  156. package/types/src/implement/client-address.d.ts +11 -0
  157. package/types/src/implement/connect.d.ts +67 -0
  158. package/types/src/implement/crashes.d.ts +31 -0
  159. package/types/src/implement/dispatch.d.ts +251 -0
  160. package/types/src/implement/egress.d.ts +14 -0
  161. package/types/src/implement/environment.d.ts +14 -0
  162. package/types/src/implement/failures.d.ts +58 -0
  163. package/types/src/implement/faults.d.ts +48 -0
  164. package/types/src/implement/headers.d.ts +7 -0
  165. package/types/src/implement/implement.d.ts +58 -0
  166. package/types/src/implement/index.d.ts +25 -0
  167. package/types/src/implement/invocation.d.ts +136 -0
  168. package/types/src/implement/membership.d.ts +201 -0
  169. package/types/src/implement/multipart.d.ts +36 -0
  170. package/types/src/implement/params.d.ts +7 -0
  171. package/types/src/implement/principal.d.ts +57 -0
  172. package/types/src/implement/project.d.ts +11 -0
  173. package/types/src/implement/public.d.ts +61 -0
  174. package/types/src/implement/serve.d.ts +25 -0
  175. package/types/src/implement/terminals.d.ts +33 -0
  176. package/types/src/implement/tokens.d.ts +49 -0
  177. package/types/src/implement/types.d.ts +263 -0
  178. package/types/src/implement/urls.d.ts +15 -0
  179. package/types/src/implement/verifiers.d.ts +19 -0
  180. package/types/src/implement/webhook.d.ts +55 -0
  181. package/types/src/implement/workload.d.ts +61 -0
  182. package/types/src/implement/xlsx.d.ts +6 -0
  183. package/types/src/index.d.ts +12 -0
  184. package/types/src/jobs/exception.d.ts +40 -0
  185. package/types/src/jobs/mail.d.ts +67 -0
  186. package/types/src/jobs/report.d.ts +56 -0
  187. package/types/src/jobs/runner.d.ts +218 -0
  188. package/types/src/jobs/schedule.d.ts +17 -0
  189. package/types/src/jobs/scrub.d.ts +12 -0
  190. package/types/src/jobs/types.d.ts +98 -0
  191. package/types/src/react/caller.d.ts +30 -0
  192. package/types/src/react/errors.d.ts +40 -0
  193. package/types/src/react/hooks.d.ts +110 -0
  194. package/types/src/react/index.d.ts +5 -0
  195. package/types/src/react/provider.d.ts +58 -0
  196. package/types/src/react/store.d.ts +68 -0
  197. package/types/src/react/testing.d.ts +28 -0
  198. package/types/src/react/types.d.ts +33 -0
  199. package/types/src/rpc/builder.d.ts +52 -0
  200. package/types/src/rpc/contract.d.ts +23 -0
  201. package/types/src/rpc/dispatcher.d.ts +11 -0
  202. package/types/src/rpc/types.d.ts +62 -0
  203. package/types/src/service/define.d.ts +42 -0
  204. package/types/src/service/index.d.ts +3 -0
  205. package/types/src/service/serve.d.ts +28 -0
  206. package/types/src/spa-fallback.d.ts +2 -0
  207. package/types/src/standard-schema.d.ts +55 -0
  208. package/types/src/testing/caller.d.ts +95 -0
  209. package/types/src/testing/challenge.d.ts +11 -0
  210. package/types/src/testing/dev.d.ts +97 -0
  211. package/types/src/testing/endpoint-access.d.ts +132 -0
  212. package/types/src/testing/index.d.ts +12 -0
  213. package/types/src/testing/isolation.d.ts +3 -0
  214. package/types/src/testing/kit.d.ts +207 -0
  215. package/types/src/testing/membership.d.ts +132 -0
  216. package/types/src/testing/policy-isolation.d.ts +113 -0
  217. package/types/src/testing/preload.d.ts +1 -0
  218. package/types/src/testing/proxy.d.ts +40 -0
  219. package/types/src/testing/runner.d.ts +8 -0
  220. package/types/src/testing/sample-file.d.ts +5 -0
  221. package/types/src/testing/status.d.ts +4 -0
  222. package/types/src/undumpable.d.ts +5 -0
@@ -2,7 +2,9 @@
2
2
  // fixed codes and bounded identifiers only, never an error's name or message: application code, drivers and even the
3
3
  // framework's own refusals can put request data there. The event adds what was thrown as its cause chain, scrubbed of
4
4
  // the environment's secrets and of credential patterns, a framework failure's message replaced by its catalog text
5
- // (ADR-0059).
5
+ // (ADR-0059). A writing invocation that held its Durable Object's transaction too long is an event on the same budget.
6
+ // The author's own run (`fabrika app dev`, a test that passes `revealHandlerErrors`) also sees what was thrown, whole,
7
+ // beside the log line; no deployed application sets that sink.
6
8
 
7
9
  import { CAPABILITY_ERRORS, CapabilityError, QUERY_REFUSALS, QueryRefusedError } from '@fabrika/db/framework'
8
10
  import { isStructuralError } from '../errors'
@@ -18,6 +20,27 @@ export type RequestFailureCode =
18
20
  | 'handler_status'
19
21
  | 'handler_failed'
20
22
 
23
+ /**
24
+ * Where the author's own run shows what a request's 5xx or a job attempt threw, whole, with where it happened:
25
+ * `fabrika app dev` sets one, and a test may pass one to the kit. No deployed application has one.
26
+ */
27
+ export type HandlerErrorSink = (where: string, error: unknown) => void
28
+
29
+ /**
30
+ * Hands `error` to the author's sink, if there is one. A sink that throws (a test's `expect` inside it) changes nothing
31
+ * of the failure it was shown: the failure is classified, logged and reported as without it.
32
+ */
33
+ export function reveal(sink: HandlerErrorSink | null, where: string, error: unknown): void {
34
+ if (sink === null) {
35
+ return
36
+ }
37
+ try {
38
+ sink(where, error)
39
+ } catch {
40
+ console.error(`fabrika: revealHandlerErrors threw while it showed ${where}; the failure stands as it was`)
41
+ }
42
+ }
43
+
21
44
  /** At most this many request failures per process and minute become Operations events; every one is logged. */
22
45
  export const MAX_FAILURE_REPORTS_PER_MINUTE = 30
23
46
 
@@ -65,6 +88,8 @@ export function failureReason(error: unknown): FailureReason | null {
65
88
  export interface RequestFailure {
66
89
  /** The endpoint id the request selected, or `request` before one was selected. */
67
90
  readonly endpoint: string
91
+ /** Whether the request selected an endpoint, so `endpoint` is its id and not the fallback. */
92
+ readonly selected: boolean
68
93
  /** The proxy's `X-Request-Id`. */
69
94
  readonly requestId: string | null
70
95
  readonly status: number
@@ -94,14 +119,24 @@ export class MinuteBudget {
94
119
  }
95
120
  }
96
121
 
122
+ export interface FailureReportsOptions {
123
+ readonly now?: () => number
124
+ readonly reveal?: HandlerErrorSink | null
125
+ }
126
+
97
127
  export class FailureReports {
98
128
  readonly #reporter: OperationsReporter | null
99
129
  readonly #budget: MinuteBudget
130
+ readonly #reveal: HandlerErrorSink | null
100
131
 
101
- /** `reporter` is `null` without an Operations DSN: the log line is then the only record. */
102
- constructor(reporter: OperationsReporter | null, now: () => number = Date.now) {
132
+ /**
133
+ * `reporter` is `null` without an Operations DSN: the log line is then the only record. `reveal` is `boot`'s
134
+ * `revealHandlerErrors`, set on the author's own run only; `now` is the budget's clock.
135
+ */
136
+ constructor(reporter: OperationsReporter | null, options: FailureReportsOptions = {}) {
103
137
  this.#reporter = reporter
104
- this.#budget = new MinuteBudget(MAX_FAILURE_REPORTS_PER_MINUTE, now)
138
+ this.#budget = new MinuteBudget(MAX_FAILURE_REPORTS_PER_MINUTE, options.now ?? Date.now)
139
+ this.#reveal = options.reveal ?? null
105
140
  }
106
141
 
107
142
  /** Never rejects. The returned delivery may outlive the response; a runtime with `waitUntil` keeps it alive. */
@@ -109,6 +144,10 @@ export class FailureReports {
109
144
  const code = failureCode(failure.error)
110
145
  const why = failureReason(failure.error)
111
146
  console.error(`fabrika: ${failure.endpoint}: ${code}${why === null ? '' : `: ${why.reason}: ${why.text}`}`)
147
+ if (this.#reveal !== null) {
148
+ // What the line withholds (a refusal's message names the place: a column, a line of ctx.sql) on the author's own run.
149
+ reveal(this.#reveal, failure.selected ? `endpoint '${failure.endpoint}'` : 'a request', failure.error)
150
+ }
112
151
  if (this.#reporter === null || !this.#budget.admit()) {
113
152
  return Promise.resolve()
114
153
  }
@@ -127,4 +166,20 @@ export class FailureReports {
127
166
  error: failure.error,
128
167
  })
129
168
  }
169
+
170
+ /**
171
+ * A writing invocation that held its object's transaction past `@fabrika/db`'s report threshold, which already
172
+ * logged it. Never rejects; the delivery may outlive the response like a failure's.
173
+ */
174
+ held(endpoint: string, heldMs: number): Promise<void> {
175
+ if (this.#reporter === null || !this.#budget.admit()) {
176
+ return Promise.resolve()
177
+ }
178
+ return this.#reporter.report({
179
+ fingerprint: ['fabrika-transaction-held', endpoint],
180
+ type: 'TransactionHeld',
181
+ message: `endpoint '${endpoint}' held its object's transaction for ${heldMs} ms`,
182
+ tags: { endpoint, code: 'transaction_held', held_ms: String(heldMs) },
183
+ })
184
+ }
130
185
  }
@@ -19,6 +19,7 @@ export const SERVER_FAULTS = {
19
19
  webhook_unverifiable: 'a webhook verifies a signature over its public URL (Twilio), and the environment has no FABRIKA_APP_ORIGIN',
20
20
  webhook_claim_lost: "a delivery's claim expired and another copy of the delivery took it over before this one committed; nothing it wrote is kept",
21
21
  workload_unauthorized: "the workload's key or token does not carry the authority its declaration needs",
22
+ terminal_refused: "IAM refused the application's own credential for an identification at a terminal",
22
23
  request_cancelled: 'the request was cancelled or outlived its budget before its transaction committed; nothing it wrote is kept',
23
24
  file_object_missing: "a file's object is missing from storage",
24
25
  file_object_mismatch: "a file's object has another size than its row records",
@@ -42,7 +43,10 @@ export const SERVER_FAULTS = {
42
43
 
43
44
  export type ServerFaultReason = keyof typeof SERVER_FAULTS
44
45
 
45
- /** A failure the framework itself describes. Its message is for the author's own run, never the response or a log. */
46
+ /**
47
+ * A failure the framework itself describes. Its message is for the author's own run (`revealHandlerErrors`), never the
48
+ * response or a log.
49
+ */
46
50
  export class ServerFault extends Error {
47
51
  override readonly name = 'ServerFault'
48
52
  readonly reason: ServerFaultReason
@@ -53,6 +53,7 @@ export type {
53
53
  } from './membership'
54
54
  export type { AppPrincipal, LinkHolder, Principal, PrincipalOf, PublicPrincipal, ServicePrincipal, UserPrincipal } from './principal'
55
55
  export { type AppDeps, defineDeps, serve, type ServeOptions } from './serve'
56
+ export type { AssertedIdentity, OpenIdentification, TerminalIdentification } from './terminals'
56
57
  export type {
57
58
  AccessContext,
58
59
  ConnectCall,
@@ -10,6 +10,7 @@ import {
10
10
  type DataSite,
11
11
  type FileBinding,
12
12
  type InvocationTransaction,
13
+ type NewWake,
13
14
  type QueryRefusal,
14
15
  QueryRefusedError,
15
16
  type Session,
@@ -321,6 +322,14 @@ export class Invocation {
321
322
  return { check: boundTo(this.#frame, () => transaction.ended, handle), session: () => transaction.session() }
322
323
  }
323
324
 
325
+ /**
326
+ * Runs `work`, from the handler to `commit`, in this invocation's transaction. On SQLite it encloses `work`, and a
327
+ * hold past `@fabrika/db`'s report threshold reaches `held`, logged under `site`.
328
+ */
329
+ enclose<T>(work: () => Promise<T>, site: string, held: (heldMs: number) => void): Promise<T> {
330
+ return this.#transaction.enclose(work, { site, held })
331
+ }
332
+
324
333
  /** Commits; a request the caller abandoned meanwhile rolls back instead. */
325
334
  async commit(signal: AbortSignal | null): Promise<void> {
326
335
  if (signal?.aborted === true) {
@@ -407,7 +416,8 @@ export function boundWebhookApp(webhook: string): (action: string) => never {
407
416
 
408
417
  /**
409
418
  * The handles of a job attempt, outside its fenced transaction (`'job'`, each read on its own) or inside it. `tickMs`,
410
- * the job's schedule period, is a queue claim's first backoff.
419
+ * the job's schedule period, is a queue claim's first backoff; `holds`, the actions the job holds, decide which file
420
+ * references of a claimed row it may open.
411
421
  */
412
422
  export function jobHandles(
413
423
  frame: RequestFrame,
@@ -419,6 +429,7 @@ export function jobHandles(
419
429
  ended: () => boolean,
420
430
  tickMs?: number,
421
431
  files?: FileBinding,
432
+ holds?: readonly string[],
422
433
  ): DataHandles {
423
434
  return data.handles({
424
435
  kind,
@@ -428,6 +439,7 @@ export function jobHandles(
428
439
  session,
429
440
  ...(tickMs === undefined ? {} : { tickMs }),
430
441
  ...(files === undefined ? {} : { files }),
442
+ ...(holds === undefined ? {} : { holds }),
431
443
  })
432
444
  }
433
445
 
@@ -458,22 +470,61 @@ export function jobSql(frame: RequestFrame, data: DataAccess, mode: SqlMode, ses
458
470
  return data.sql({ mode, check: boundTo(frame, ended, 'tx.sql'), session: async () => session, fail: () => session.fail() })
459
471
  }
460
472
 
473
+ /** The kicks of one invocation, as `ctx.kick` recorded them. */
474
+ export interface KickRecorder {
475
+ readonly kick: (job: string, options?: unknown) => void
476
+ /** The jobs kicked without `at`, each once: what the dispatcher starts after the commit. */
477
+ readonly kicked: () => readonly string[]
478
+ /** Whether the invocation kicked anything, now or for later. */
479
+ readonly recorded: () => boolean
480
+ /**
481
+ * Every kick's wake, one per job and due second (`kick:<job>:<due second>`); a kick without `at` is due at `now`. The
482
+ * site writes them in its transaction, so a rollback leaves none.
483
+ */
484
+ readonly wakes: (now: Date) => readonly NewWake[]
485
+ }
486
+
487
+ /** A kick's due time: `undefined` for one without options; anything but `{ at: <valid Date> }` is refused. */
488
+ function kickAt(site: string, options: unknown): Date | undefined {
489
+ if (options === undefined) {
490
+ return undefined
491
+ }
492
+ const keys = isPlainObject(options) ? Object.keys(options) : null
493
+ const at: unknown = isPlainObject(options) ? ownField(options, 'at') : undefined
494
+ if (keys === null || keys.length !== 1 || keys[0] !== 'at' || !(at instanceof Date) || Number.isNaN(at.getTime())) {
495
+ throw new QueryRefusedError('invalid_argument', `${site}: ctx.kick takes a job and optionally { at: <Date> }; a kick carries nothing else`)
496
+ }
497
+ return new Date(at.getTime())
498
+ }
499
+
500
+ const kickKey = (job: string, due: Date): string => `kick:${job}:${Math.floor(due.getTime() / 1_000)}`
501
+
461
502
  /**
462
- * `ctx.kick` of one invocation: it names only a declared job, and records it; the dispatcher sends each recorded job once,
463
- * after the commit, and nothing on a rollback.
503
+ * `ctx.kick` of one invocation: it names only a declared job, and records it; the site writes each kick's wake in its
504
+ * transaction, and the dispatcher starts each job kicked without `at` once, after the commit, and nothing on a rollback.
464
505
  */
465
- export function kickRecorder(
466
- site: string,
467
- declared: readonly string[],
468
- ): { readonly kick: (job: string) => void; readonly kicked: () => readonly string[] } {
469
- const kicked = new Set<string>()
506
+ export function kickRecorder(site: string, declared: readonly string[]): KickRecorder {
507
+ const kicks: { readonly job: string; readonly at: Date | undefined }[] = []
470
508
  return {
471
- kick: (job: string) => {
509
+ kick: (job: string, options?: unknown) => {
472
510
  if (!declared.includes(job)) {
473
511
  throw new CapabilityRefusedError('undeclared_kick', `${site} does not declare kicks: ['${String(job)}']`)
474
512
  }
475
- kicked.add(job)
513
+ kicks.push({ job, at: kickAt(site, options) })
514
+ },
515
+ kicked: () => [...new Set(kicks.filter((kick) => kick.at === undefined).map((kick) => kick.job))],
516
+ recorded: () => kicks.length > 0,
517
+ wakes: (now: Date) => {
518
+ const wakes = new Map<string, NewWake>()
519
+ for (const { job, at } of kicks) {
520
+ const dueAt = at ?? now
521
+ const dedupe = kickKey(job, dueAt)
522
+ const kept = wakes.get(dedupe)
523
+ if (kept === undefined || dueAt < kept.dueAt) {
524
+ wakes.set(dedupe, { job, reason: 'kick', dueAt, dedupe })
525
+ }
526
+ }
527
+ return [...wakes.values()]
476
528
  },
477
- kicked: () => [...kicked],
478
529
  }
479
530
  }
@@ -1,6 +1,15 @@
1
1
  // Who called: the caller kind a verified token presents, and the principal a handler sees for it.
2
2
 
3
- import { type AccessTokenClaims, APP_CALLER_PREFIX, type Caller, callerOf, matchAction, OAUTH_CALLER, type PermissionEntry } from '@fabrika/auth-core'
3
+ import {
4
+ type AccessTokenClaims,
5
+ APP_CALLER_PREFIX,
6
+ type Caller,
7
+ callerOf,
8
+ matchAction,
9
+ OAUTH_CALLER,
10
+ type PermissionEntry,
11
+ type TerminalTokenClaims,
12
+ } from '@fabrika/auth-core'
4
13
  import type { PageCaller } from '../client/caller'
5
14
 
6
15
  /** A person: the IAM session, or a `px_` key bound to a user principal. */
@@ -11,6 +20,11 @@ export interface UserPrincipal {
11
20
  readonly label: string
12
21
  /** The mailbox IAM recorded for the person, lower-cased: the one to mail, not proof of possession. Only a person has one. */
13
22
  readonly email: string
23
+ /**
24
+ * The enrolled terminal the person signed in on, when an application asserted them there (ADR-0067); absent for every
25
+ * other sign-in. Information for the handler: what the session may do is in its permissions already.
26
+ */
27
+ readonly terminal?: TerminalTokenClaims
14
28
  }
15
29
 
16
30
  /** A machine: a `px_` key bound to a service principal. */
@@ -65,7 +79,16 @@ export function presentedBy(claims: AccessTokenClaims): Presented | Unpresented
65
79
  switch (caller) {
66
80
  case 'human':
67
81
  if (claims.email === undefined) return 'no_mailbox'
68
- return { caller, principal: { kind: 'user', id: claims.sub, label: claims.label ?? claims.sub, email: claims.email } }
82
+ return {
83
+ caller,
84
+ principal: {
85
+ kind: 'user',
86
+ id: claims.sub,
87
+ label: claims.label ?? claims.sub,
88
+ email: claims.email,
89
+ ...(claims.terminal === undefined ? {} : { terminal: Object.freeze({ id: claims.terminal.id, label: claims.terminal.label }) }),
90
+ },
91
+ }
69
92
  case 'machine':
70
93
  return { caller, principal: { kind: 'service', id: claims.sub, label: claims.label ?? claims.sub } }
71
94
  case 'link':
@@ -0,0 +1,93 @@
1
+ // `ctx.terminals`: the identification of a person at an enrolled terminal (ADR-0067). The application's identification
2
+ // page sends what the person entered to its own procedure, which asks IAM through these calls. The framework presents
3
+ // the request's credential (a public procedure's workload token), and IAM takes the asserting application from the
4
+ // verified transport. Throttling guesses is the application's: `inspect` hands it the terminal to key them on.
5
+
6
+ import type { IamTerminalRpc, IdentificationTerminal, MembershipCaller, TerminalFailure } from '@fabrika/auth-core'
7
+ import { ServerFault } from './faults'
8
+
9
+ /** An identification id longer than this is none IAM issued, so no call is made for it. */
10
+ const MAX_IDENTIFICATION_ID_LENGTH = 200
11
+
12
+ /** An open identification: the terminal it was opened on and when it expires (unix seconds). */
13
+ export interface OpenIdentification {
14
+ readonly terminal: IdentificationTerminal
15
+ readonly expiresAt: number
16
+ }
17
+
18
+ /**
19
+ * IAM's answer to an assertion: the URL the browser goes to next, or why IAM refused. `not_found` is an identification
20
+ * that is unknown, expired, used, cancelled or no longer open to this application; `invalid_principal` a principal
21
+ * that cannot sign in on a terminal (unknown, disabled, not a person, or external).
22
+ */
23
+ export type AssertedIdentity =
24
+ | { readonly ok: true; readonly completionUrl: string }
25
+ | { readonly ok: false; readonly reason: 'not_found' | 'invalid_principal' }
26
+
27
+ /** `ctx.terminals` of an application that declares `terminal: { identify }`. */
28
+ export interface TerminalIdentification {
29
+ /** The open identification `id` (the page's `identification` query parameter), or null when there is none. */
30
+ inspect(id: string): Promise<OpenIdentification | null>
31
+ /**
32
+ * The application's word that `principalId` stands at the identification's terminal. IAM uses the identification up
33
+ * and, on `ok`, the handler sends the browser to `completionUrl`: IAM signs the person in there, and only on the
34
+ * terminal's own browser.
35
+ */
36
+ assert(id: string, principalId: string): Promise<AssertedIdentity>
37
+ /** Ends an identification the person abandoned; one that is no longer open is already ended. */
38
+ cancel(id: string): Promise<void>
39
+ }
40
+
41
+ /** `ctx.terminals` for one request: every call carries the request's credential and correlation id. */
42
+ export function terminalIdentification(rpc: IamTerminalRpc, caller: MembershipCaller): TerminalIdentification {
43
+ return Object.freeze({
44
+ async inspect(id: string): Promise<OpenIdentification | null> {
45
+ if (!isIdentificationId(id)) return null
46
+ const result = await ask(() => rpc.inspectIdentification({ ...caller, id }), 'inspect an identification')
47
+ if (!result.ok) return null
48
+ return Object.freeze({ terminal: Object.freeze({ id: result.terminal.id, label: result.terminal.label }), expiresAt: result.expiresAt })
49
+ },
50
+ async assert(id: string, principalId: string): Promise<AssertedIdentity> {
51
+ if (!isIdentificationId(id)) return { ok: false, reason: 'not_found' }
52
+ const result = await ask(() => rpc.assertIdentity({ ...caller, id, principalId }), 'assert an identity')
53
+ return result.ok ? { ok: true, completionUrl: result.completionUrl } : { ok: false, reason: result.reason }
54
+ },
55
+ async cancel(id: string): Promise<void> {
56
+ if (isIdentificationId(id)) {
57
+ await ask(() => rpc.cancelIdentification({ ...caller, id }), 'cancel an identification')
58
+ }
59
+ },
60
+ })
61
+ }
62
+
63
+ function isIdentificationId(id: string): boolean {
64
+ return id !== '' && id.length <= MAX_IDENTIFICATION_ID_LENGTH
65
+ }
66
+
67
+ /**
68
+ * Runs one IAM call. A transport failure is a 503 that names nothing; IAM refusing the application's own credential is
69
+ * a server fault, because the visitor cannot change it. What remains is the handler's answer.
70
+ */
71
+ async function ask<T extends { readonly ok: true }>(
72
+ work: () => Promise<T | TerminalFailure>,
73
+ operation: string,
74
+ ): Promise<T | { readonly ok: false; readonly reason: 'not_found' | 'invalid_principal' }> {
75
+ let result: T | TerminalFailure
76
+ try {
77
+ result = await work()
78
+ } catch {
79
+ throw new ServerFault('iam_unavailable', `IAM could not be asked to ${operation}`, 503)
80
+ }
81
+ if (result.ok) {
82
+ return result
83
+ }
84
+ switch (result.reason) {
85
+ case 'not_found':
86
+ case 'invalid_principal':
87
+ return { ok: false, reason: result.reason }
88
+ case 'missing_token':
89
+ case 'invalid_token':
90
+ case 'not_allowed':
91
+ throw new ServerFault('terminal_refused', `IAM refused the application's credential to ${operation}: ${result.reason}`)
92
+ }
93
+ }
@@ -2,6 +2,8 @@
2
2
  // declares `signs`, and the verification of each token field of a procedure's input and `http.query` as they are parsed.
3
3
  // A token is `<key id>.<payload>.<signature>`: the payload is the purpose, the expiry and the claims as base64url JSON,
4
4
  // and the signature an HMAC-SHA256 over the key id and the payload, so a token of one purpose never passes as another.
5
+ // The signature is compared as its text: its last character carries two padding bits that decode to nothing, so
6
+ // comparing decoded bytes would let four spellings of one token verify, and a token has exactly one.
5
7
 
6
8
  import { type ContractArtifact, FABRIKA_TOKEN_KEYS, type SchemaShape } from '@fabrika/auth-core'
7
9
  import { createHmac, timingSafeEqual } from 'node:crypto'
@@ -129,8 +131,8 @@ export class SignedTokens {
129
131
  if (rest.length > 0 || key === undefined || declared === undefined || !BASE64URL.test(payload) || !BASE64URL.test(given)) {
130
132
  throw invalid()
131
133
  }
132
- const expected = Buffer.from(signature(key, payload), 'base64url')
133
- const presented = Buffer.from(given, 'base64url')
134
+ const expected = Buffer.from(signature(key, payload))
135
+ const presented = Buffer.from(given)
134
136
  if (presented.byteLength !== expected.byteLength || !timingSafeEqual(presented, expected)) {
135
137
  throw invalid()
136
138
  }
@@ -93,10 +93,28 @@ type LinksContext<C, Acc> = TargetOf<Acc> extends readonly [infer D extends stri
93
93
  /** What a procedure's context carries for its access form in this contract. */
94
94
  export type ContractContext<C, Acc> = AccessContext<Acc> & MembersContext<C, Acc> & LinksContext<C, Acc>
95
95
 
96
- /** The input without the `from` field: the only copy of that id a handler has is the checked capability. */
97
- export type HandlerInput<I, Acc> = Acc extends { readonly from: infer F extends string }
98
- ? { readonly [K in keyof InputOf<I> as K extends F ? never : K]: InputOf<I>[K] }
99
- : InputOf<I>
96
+ /**
97
+ * The `from` fields an access form reads: its own, or under `capabilities` each `on` and `in` one's (`over` reads none).
98
+ * The runtime removes the same fields (`#access` and `#capabilities` in `dispatch.ts`). A widened `from` (`string`, or
99
+ * the union of the input's string fields an access widened to its declared constraint carries) removes every field it
100
+ * may name: the runtime removes one of them, and the declaration refuses such an access anyway.
101
+ */
102
+ type FromFields<Acc> = Acc extends { readonly capabilities: infer C } ? { [N in keyof C]: FieldRead<C[N]> }[keyof C] : FieldRead<Acc>
103
+
104
+ /** The field one access form reads, for each member of a form typed as a union; `never` for a form that reads none. */
105
+ type FieldRead<F> = F extends { readonly from: infer K extends string } ? K : never
106
+
107
+ /**
108
+ * The input as the runtime hands it to the handler: without the `from` fields and frozen under a form that reads one and
109
+ * under every `capabilities` access (`Object.freeze` in `takeField` and `#capabilities`); as parsed under any other.
110
+ */
111
+ export type HandlerInput<I, Acc> = IsAny<Acc> extends true ? InputOf<I>
112
+ : Acc extends { readonly capabilities: unknown } ? Without<InputOf<I>, FromFields<Acc>>
113
+ : Acc extends unknown ? [FromFields<Acc>] extends [never] ? InputOf<I> : Without<InputOf<I>, FromFields<Acc>>
114
+ : never
115
+
116
+ /** `In` without the fields `F`, read-only: the only copy of each removed id a handler has is the checked capability. */
117
+ type Without<In, F> = { readonly [K in keyof In as K extends F ? never : K]: In[K] }
100
118
 
101
119
  export type Handler<In, Ctx, O extends Schema> = (args: { readonly input: In; readonly ctx: Ctx }) => z.input<O> | Promise<z.input<O>>
102
120
 
@@ -16,6 +16,7 @@ import {
16
16
  } from '@fabrika/auth-core'
17
17
  import type { TokenVerifier } from '@fabrika/jwks'
18
18
  import { z } from 'zod/v4'
19
+ import { deadline } from './bounded'
19
20
 
20
21
  export type WorkloadKindOf = OwnWorkloadKind
21
22
 
@@ -39,20 +40,30 @@ export function issuerWorkloadTokens(
39
40
  ): WorkloadTokenSource {
40
41
  return {
41
42
  async exchange(input) {
42
- const response = await fetcher(
43
- new Request(new URL(WORKLOAD_TOKEN_PATH, issuer), {
44
- method: 'POST',
45
- headers: { authorization: `Bearer ${input.key}`, 'content-type': 'application/json' },
46
- body: JSON.stringify({ app: input.app }),
47
- redirect: 'manual',
48
- signal: AbortSignal.timeout(EXCHANGE_TIMEOUT_MS),
49
- }),
50
- )
51
- const parsed = response.status === 200 ? mintResultSchema.safeParse(await response.json()) : null
52
- if (parsed === null || !parsed.success) {
53
- throw new Error(`IAM answered the workload token exchange with ${response.status}`)
43
+ const timer = deadline(EXCHANGE_TIMEOUT_MS)
44
+ try {
45
+ const response = await fetcher(
46
+ new Request(new URL(WORKLOAD_TOKEN_PATH, issuer), {
47
+ method: 'POST',
48
+ headers: { authorization: `Bearer ${input.key}`, 'content-type': 'application/json' },
49
+ body: JSON.stringify({ app: input.app }),
50
+ redirect: 'manual',
51
+ signal: timer.signal,
52
+ }),
53
+ )
54
+ if (response.status !== 200) {
55
+ // Nothing reads a refusal's body, and once the deadline is cleared nothing else would end its stream.
56
+ await response.body?.cancel().catch(() => {})
57
+ throw new Error(`IAM answered the workload token exchange with ${response.status}`)
58
+ }
59
+ const parsed = mintResultSchema.safeParse(await response.json())
60
+ if (!parsed.success) {
61
+ throw new Error(`IAM answered the workload token exchange with ${response.status}`)
62
+ }
63
+ return parsed.data
64
+ } finally {
65
+ timer.clear()
54
66
  }
55
- return parsed.data
56
67
  },
57
68
  }
58
69
  }
@@ -91,12 +102,27 @@ export class WorkloadCredential {
91
102
  if (cached !== null && cached.exp - Math.floor(Date.now() / 1000) > TOKEN_REFRESH_SKEW_SECONDS) {
92
103
  return Promise.resolve({ ok: true, perms: cached.perms, token: cached.token })
93
104
  }
94
- this.#pending ??= this.#exchange().finally(() => {
95
- this.#pending = null
96
- })
105
+ if (this.#pending === null) {
106
+ const pending: Promise<WorkloadAuthority> = this.#exchange().finally(() => {
107
+ if (this.#pending === pending) {
108
+ this.#pending = null
109
+ }
110
+ })
111
+ this.#pending = pending
112
+ }
97
113
  return this.#pending
98
114
  }
99
115
 
116
+ /**
117
+ * The caller stopped waiting for `pending`, an answer of `authority()` (its attempt timed out or was stopped): the
118
+ * next call exchanges afresh instead of waiting on an exchange that may never answer.
119
+ */
120
+ abandon(pending: Promise<WorkloadAuthority>): void {
121
+ if (this.#pending === pending) {
122
+ this.#pending = null
123
+ }
124
+ }
125
+
100
126
  async #exchange(): Promise<WorkloadAuthority> {
101
127
  const { kind, name, key, audience, source, verifier } = this.#options
102
128
  let minted: MintFromKeyResult
package/src/jobs/mail.ts CHANGED
@@ -93,6 +93,10 @@ export function jobMail(input: JobMailInput): AppMail {
93
93
  if (typeof key !== 'string' || !APP_MAIL_KEY.test(key)) {
94
94
  throw new EmailDeliveryError(`Email idempotency key is not 1..${MAX_APP_MAIL_KEY_LENGTH} visible ASCII characters`, { code: 'invalid_message' })
95
95
  }
96
+ // Checked here, not left to the sender: one written before `broadcast` existed would send it as transactional mail.
97
+ if (available && message.broadcast === true && sender.capabilities.broadcast !== true) {
98
+ throw new EmailDeliveryError('This mail transport sends no broadcast email', { code: 'invalid_message' })
99
+ }
96
100
  // Without a transport the send fails `mail_not_configured` below, and no file is read for it.
97
101
  const attachments = available ? await readAttachments(message.attachments ?? [], sender.capabilities.maxAttachmentBytes, open) : []
98
102
  const transported: EmailMessage = {
@@ -104,6 +108,7 @@ export function jobMail(input: JobMailInput): AppMail {
104
108
  ...(message.replyTo === undefined ? {} : { replyTo: message.replyTo }),
105
109
  ...(message.fromName === undefined ? {} : { fromName: message.fromName }),
106
110
  ...(message.unsubscribe === undefined ? {} : { unsubscribeUrl: message.unsubscribe.url }),
111
+ ...(message.broadcast === true ? { broadcast: true } : {}),
107
112
  ...(attachments.length === 0 ? {} : { attachments }),
108
113
  }
109
114
  try {
@@ -309,6 +314,9 @@ const SenderCapabilities = z.object({
309
314
  maxBatch: z.int().positive(),
310
315
  listUnsubscribe: z.boolean().optional(),
311
316
  maxAttachmentBytes: z.int().positive().optional(),
317
+ refusedAttachmentExtensions: z.array(z.string()).readonly().optional(),
318
+ minBodyLength: z.int().positive().optional(),
319
+ broadcast: z.boolean().optional(),
312
320
  })
313
321
 
314
322
  /** What `serve`'s `mail` returned: a sender, `null` for none, `undefined` for anything else. */
@@ -3,6 +3,7 @@
3
3
  // groups a framework report by its fingerprint and raises its new-issue and regression alerts, so each kind of
4
4
  // failure becomes one issue. What was thrown travels scrubbed as the report's cause chain (ADR-0059).
5
5
 
6
+ import { deadline } from '../implement/bounded'
6
7
  import { exceptionChain, type ReportedException } from './exception'
7
8
  import type { Scrubber } from './scrub'
8
9
 
@@ -136,6 +137,7 @@ export function crashEnvelope(kind: CrashKind, error: unknown, options: Envelope
136
137
 
137
138
  async function deliver(options: OperationsReporterOptions, body: string): Promise<void> {
138
139
  const send = options.fetch ?? ((request: Request) => fetch(request))
140
+ const timer = deadline(DELIVERY_TIMEOUT_MS)
139
141
  const request = new Request(options.target.envelopeUrl, {
140
142
  method: 'POST',
141
143
  headers: {
@@ -143,7 +145,7 @@ async function deliver(options: OperationsReporterOptions, body: string): Promis
143
145
  'x-sentry-auth': `Sentry sentry_version=7, sentry_key=${options.target.publicKey}`,
144
146
  },
145
147
  body,
146
- signal: AbortSignal.timeout(DELIVERY_TIMEOUT_MS),
148
+ signal: timer.signal,
147
149
  })
148
150
  try {
149
151
  const response = await send(request)
@@ -154,6 +156,8 @@ async function deliver(options: OperationsReporterOptions, body: string): Promis
154
156
  } catch {
155
157
  // The error may quote the ingest URL with its key.
156
158
  console.error('fabrika: a report to Operations could not be delivered')
159
+ } finally {
160
+ timer.clear()
157
161
  }
158
162
  }
159
163