@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
@@ -7,6 +7,7 @@
7
7
  import {
8
8
  type AccessForm,
9
9
  type Caller,
10
+ type CapabilitiesRequirement,
10
11
  type ContractArtifact,
11
12
  type EndpointDirectory,
12
13
  endpointDirectory,
@@ -20,8 +21,12 @@ import type { Tables } from '@fabrika/db'
20
21
  import { tablePolicies } from '@fabrika/db/tables'
21
22
  import { type IsolationWorlds, type SampleValue, SEEDED_OBJECT_VERSION, type TestDatabase, type WorldRow } from '@fabrika/db/testing'
22
23
  import { MemoryFileObjects } from '@fabrika/platform/testing'
24
+ import { readFile } from 'node:fs/promises'
25
+ import { basename } from 'node:path'
26
+ import { fileURLToPath } from 'node:url'
23
27
  import { z } from 'zod/v4'
24
28
  import type { RpcFetch } from '../client/transport'
29
+ import { deniedCaseRuledOutBy } from '../contract/capability-cases'
25
30
  import { compileContract } from '../contract/compile'
26
31
  import {
27
32
  FILE_INPUT_PART,
@@ -33,6 +38,7 @@ import {
33
38
  } from '../contract/defaults'
34
39
  import type { AnyContract } from '../contract/define'
35
40
  import type { FileScanner, ScanVerdict } from '../files/scan'
41
+ import { bytesAreOfType, SNIFF_BYTES } from '../files/sniff'
36
42
  import type { ApplicationEnvironment, ContractImplementation } from '../implement/implement'
37
43
  import type { TestCaller, TestGrant } from './caller'
38
44
  import { standInIamKit } from './kit'
@@ -58,6 +64,13 @@ export type ReachOutcome = { readonly answered: true } | { readonly answered: fa
58
64
  /** Column → value of the row of the table that owns the endpoint's dimension, in both scopes: the author's seed. */
59
65
  export type Seed = Readonly<Record<string, SampleValue>>
60
66
 
67
+ /**
68
+ * Table → column → value: one row of each application table the handler reads for the caller's own scope, seeded
69
+ * before a leak or an own case asks and removed once it is over, with every row that refers to it, so no other case
70
+ * finds it. Both scopes may see it, so its values are never counted as the other scope's.
71
+ */
72
+ export type AppRows = Readonly<Record<string, Seed>>
73
+
61
74
  export interface EndpointAccessKit {
62
75
  /**
63
76
  * A caller holding the endpoint's action in one scope names an object (`on`) or a scope value (`in`) of another;
@@ -66,16 +79,18 @@ export interface EndpointAccessKit {
66
79
  denied(endpoint: string, input: Readonly<Record<string, unknown>>, seed?: Seed): Promise<DeniedOutcome>
67
80
  /**
68
81
  * A caller of the other scope asks first, then a caller of one scope asks for its own object (`on`), its list
69
- * (`over`) or, for every table that lies in the dimension, its scope value (`in`).
82
+ * (`over`) or, for every table that lies in the dimension, its scope value (`in`). `appRows` are seeded first, as
83
+ * for `own`.
70
84
  */
71
- leaked(endpoint: string, input: Readonly<Record<string, unknown>>, seed?: Seed): Promise<LeakOutcome>
85
+ leaked(endpoint: string, input: Readonly<Record<string, unknown>>, seed?: Seed, appRows?: AppRows): Promise<LeakOutcome>
72
86
  /**
73
87
  * A caller that holds only the endpoint's action asks for its own object: a person or a script in its scope, or, on
74
88
  * a link mount, the holder of a link bound to the object. A write action reads its own target. Where IAM requires more
75
89
  * of the caller, it holds that too: a member manager an assigning role and the assigned role's actions, a link's
76
- * issuer the actions the link grants.
90
+ * issuer the actions the link grants. `appRows` are the rows of application tables its handler reads (the guide a link
91
+ * holder downloads), each seeded first.
77
92
  */
78
- own(endpoint: string, input: Readonly<Record<string, unknown>>, seed?: Seed): Promise<DeniedOutcome>
93
+ own(endpoint: string, input: Readonly<Record<string, unknown>>, seed?: Seed, appRows?: AppRows): Promise<DeniedOutcome>
79
94
  /**
80
95
  * An `app` or a `creates` endpoint asked by a caller who holds its action in one value of a dimension only, never
81
96
  * globally: refused (403), by the proxy for `app` and by IAM for `creates`, since both need a global grant.
@@ -88,9 +103,10 @@ export interface EndpointAccessKit {
88
103
  global(endpoint: string, input: Readonly<Record<string, unknown>>): Promise<ReachOutcome>
89
104
  /**
90
105
  * One capability of an endpoint of several, refused while every other one passes: the caller holds each other one's
91
- * action in a scope of its own and addresses its object or value there (or, for `over`, holds the action globally).
92
- * For an `on` or `in` capability it also holds the named one's action in its own scope and addresses the other's
93
- * object (404) or value (403); for `over` it holds the named action nowhere (403). `seed` is the named one's.
106
+ * action in a scope of its own and addresses its object or value there. For an `on` or `in` capability it also holds
107
+ * the named one's action in its own scope and addresses the other's object (404) or value (403); for `over` it holds
108
+ * the named action only where the others need it (403). An `over` capability without a denied case
109
+ * (`deniedCaseRuledOutBy`) throws. `seed` is the named one's.
94
110
  */
95
111
  capability(endpoint: string, capability: string, input: Readonly<Record<string, unknown>>, seed?: Seed): Promise<DeniedOutcome>
96
112
  /**
@@ -101,6 +117,54 @@ export interface EndpointAccessKit {
101
117
  anyone(endpoint: string, input: Readonly<Record<string, unknown>>): Promise<ReachOutcome>
102
118
  }
103
119
 
120
+ export interface EndpointAccessOptions {
121
+ /**
122
+ * The file every case of an endpoint sends in a file field instead of the kit's sample, by endpoint id and input
123
+ * field: a file of the application's repository that a handler inspecting the content accepts (a valid package). Its
124
+ * type is the first of the field's kind that its bytes are; a file of none of them throws. `files` of the fixtures.
125
+ */
126
+ readonly files?: Readonly<Record<string, Readonly<Record<string, URL>>>>
127
+ /**
128
+ * The error types of the refusals (400) an endpoint's handler answers its own object with when the case's input meets
129
+ * no domain rule the kit can satisfy, by endpoint id: such a 400 is the handler's own answer, so the request passed
130
+ * the access form, and the endpoint's own case gets it as `{ status: 400 }` instead of failing; so does the other
131
+ * scope's request a leak case makes first. The own scope's answer of a leak case, and a global or capability case,
132
+ * still throw on it (an answer that holds nothing proves no isolation), so does any other 400, and an input the schema
133
+ * refuses (`validation`) always does. `refusals` of the fixtures.
134
+ */
135
+ readonly refusals?: Readonly<Record<string, readonly string[]>>
136
+ /**
137
+ * Known values for text columns of the row the endpoint addresses (the row of the table that owns its dimension), by
138
+ * endpoint id: the value in the own scope's row, and `<value>-other` in the other scope's, which counts among the
139
+ * other scope's values a leak shows. For a handler whose rule ties a column to the input or a file fixture (a package
140
+ * that names the skill's slug). `pins` of the fixtures.
141
+ */
142
+ readonly pins?: Readonly<Record<string, Readonly<Record<string, string>>>>
143
+ }
144
+
145
+ /**
146
+ * Whether a request takes a refusal the fixtures declare for its endpoint as the handler's answer: an own case's, and the
147
+ * other scope's request a leak case makes first, whose answer is not the one checked.
148
+ */
149
+ type Refusals = 'declared' | 'none'
150
+
151
+ /**
152
+ * The pins of a case's endpoint (column → the own scope's value of a text column), and the removals of the case: rows
153
+ * seeded with pins are removed once the case is over, so the next case can pin the same values under a unique index.
154
+ */
155
+ interface Pinning {
156
+ readonly pins: Readonly<Record<string, string>>
157
+ readonly removals: (() => Promise<void>)[]
158
+ }
159
+
160
+ const NO_PINNING: Pinning = { pins: {}, removals: [] }
161
+
162
+ /** Seeded worlds, their removal taken by the case when they hold pinned values. */
163
+ const pinned = <W extends { readonly remove: () => Promise<void> }>(worlds: W, pinning: Pinning): W => {
164
+ if (Object.keys(pinning.pins).length > 0) pinning.removals.push(worlds.remove)
165
+ return worlds
166
+ }
167
+
104
168
  interface ActionEndpoint {
105
169
  readonly id: string
106
170
  /** The link mount of a link procedure; `null` for every other endpoint. */
@@ -276,7 +340,12 @@ export const managerGrants = (
276
340
  * The endpoint access kit of `app`, whose data layer is `scoped(tables)`, over `postgres`. It boots `app` once, so the
277
341
  * application's layer is bound here and nowhere else in the process.
278
342
  */
279
- export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract>, tables: Tables<DB, P>, postgres: TestDatabase): EndpointAccessKit {
343
+ export function endpointAccessKit<DB, P>(
344
+ app: ContractImplementation<AnyContract>,
345
+ tables: Tables<DB, P>,
346
+ postgres: TestDatabase,
347
+ options: EndpointAccessOptions = {},
348
+ ): EndpointAccessKit {
280
349
  // The objects of the files the cases seed live in memory; their rows are the application's own tables.
281
350
  const objects = new MemoryFileObjects()
282
351
  const { kit, standIn } = standInIamKit(app, {
@@ -327,14 +396,16 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
327
396
  )
328
397
  }
329
398
 
330
- /** An endpoint of several capabilities, as one `ActionEndpoint` per capability, by its name. */
331
- const capabilitiesEndpointOf = (id: string): ReadonlyMap<string, ActionEndpoint> => {
399
+ /** An endpoint of several capabilities: its requirement, and one `ActionEndpoint` per capability, by its name. */
400
+ const capabilitiesEndpointOf = (
401
+ id: string,
402
+ ): { readonly requirement: CapabilitiesRequirement; readonly capabilities: ReadonlyMap<string, ActionEndpoint> } => {
332
403
  const row = kit.artifact.endpoints.find((candidate) => candidate.id === id)
333
404
  const requirement = row?.requirement
334
405
  if (row === undefined || requirement?.kind !== 'capabilities') {
335
406
  throw new Error(`${id} is not an endpoint of the contract with several capabilities`)
336
407
  }
337
- return new Map(
408
+ const capabilities = new Map(
338
409
  Object.entries(requirement.capabilities).map(([name, capability]) => [name, {
339
410
  id: row.id,
340
411
  link: null,
@@ -349,6 +420,7 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
349
420
  links: [],
350
421
  }]),
351
422
  )
423
+ return { requirement, capabilities }
352
424
  }
353
425
 
354
426
  const globalEndpointOf = (id: string): ActionEndpoint => {
@@ -368,21 +440,14 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
368
440
  return parent?.mode === 'dimension' ? (parent.container?.dimension ?? parent.dimension) : undefined
369
441
  }
370
442
 
371
- const callerFor = (
372
- row: ActionEndpoint,
373
- grants: readonly Grant[],
374
- global: readonly { readonly action: string }[] = [],
375
- ): { readonly caller: TestCaller; readonly fetch: RpcFetch } => {
376
- const asGrants: TestGrant<AnyContract>[] = [
377
- ...grants.map((grant) => ('role' in grant ? { role: grant.role, scope: grant.scope } : { action: grant.action, scope: grant.scope })),
378
- ...global,
379
- ]
443
+ /** A new caller holding `grants`; an action without a scope is held globally. */
444
+ const callerFor = (row: ActionEndpoint, grants: readonly TestGrant<AnyContract>[]): { readonly caller: TestCaller; readonly fetch: RpcFetch } => {
380
445
  if (row.callers.some((caller) => caller === 'human')) {
381
- const caller = kit.testCaller(asGrants)
446
+ const caller = kit.testCaller(grants)
382
447
  return { caller, fetch: kit.browser(caller) }
383
448
  }
384
449
  if (row.callers.some((caller) => caller === 'machine')) {
385
- const caller = kit.testCaller(asGrants, { kind: 'machine' })
450
+ const caller = kit.testCaller(grants, { kind: 'machine' })
386
451
  return {
387
452
  caller,
388
453
  fetch: (input, init) => {
@@ -395,16 +460,20 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
395
460
  throw new Error(`${row.id} admits neither a human nor a machine caller`)
396
461
  }
397
462
 
398
- /** A case's request by a new caller holding `grants`, its generated fields filled for `chain` and that caller. */
463
+ /**
464
+ * A case's request by a new caller holding `grants`, its generated fields filled for `chain` and that caller. Only an
465
+ * own case passes `refusals: 'declared'`.
466
+ */
399
467
  const ask = async (
400
468
  row: ActionEndpoint,
401
469
  grants: readonly Grant[],
402
470
  input: Readonly<Record<string, unknown>>,
403
471
  chain: Chain,
472
+ refusals: Refusals = 'none',
404
473
  ): Promise<{ readonly status: number; readonly text: string; readonly marks: readonly string[] }> => {
405
474
  const asker = callerFor(row, grants)
406
475
  const asked = withGenerated(row, input, chain, asker.caller)
407
- return { ...(await askAs(row, asker.fetch, asked.input)), marks: asked.marks }
476
+ return { ...(await askAs(row, asker.fetch, asked.input, refusals)), marks: asked.marks }
408
477
  }
409
478
 
410
479
  // A seeded file column references an empty object, which a handler that serves or opens the file reads here.
@@ -418,7 +487,7 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
418
487
  }
419
488
 
420
489
  /** The request of a case: a GET's input in its URL, a file field's marker as a file of its kind in a multipart body. */
421
- const requestOf = (row: ActionEndpoint, body: Readonly<Record<string, unknown>>): readonly [string, RequestInit] => {
490
+ const requestOf = async (row: ActionEndpoint, body: Readonly<Record<string, unknown>>): Promise<readonly [string, RequestInit]> => {
422
491
  if (row.method === 'GET') {
423
492
  const params = new URLSearchParams(Object.entries(body).map(([name, value]) => [name, value === null ? 'null' : String(value)]))
424
493
  return [params.size === 0 ? row.path : `${row.path}?${params}`, { method: 'GET' }]
@@ -437,7 +506,7 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
437
506
  for (const item of Array.isArray(value) ? value : [value]) {
438
507
  const kind = fileKindOf(item)
439
508
  if (kind === undefined) throw new Error(`${row.id}: the file field ${name} holds ${JSON.stringify(item)}, not a generated file`)
440
- files.push([name, generatedFile(kind)])
509
+ files.push([name, await generatedFile(row.id, name, kind)])
441
510
  }
442
511
  }
443
512
  const form = new FormData()
@@ -446,30 +515,69 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
446
515
  return [row.path, { method: 'POST', body: form }]
447
516
  }
448
517
 
449
- const generatedFile = (kind: string): File => {
450
- const sample = sampleFile(kind, kit.artifact.fileKinds?.[kind]?.types ?? [])
451
- return new File([sample.bytes], `generated-${kind}`, { type: sample.type })
518
+ /** The file a case sends in `field`: the author's file fixture of the endpoint's field, else a sample of `kind`. */
519
+ const generatedFile = async (endpoint: string, field: string, kind: string): Promise<File> => {
520
+ const types = kit.artifact.fileKinds?.[kind]?.types ?? []
521
+ const fixture = options.files?.[endpoint]?.[field]
522
+ if (fixture === undefined) {
523
+ const sample = sampleFile(kind, types)
524
+ return new File([sample.bytes], `generated-${kind}`, { type: sample.type })
525
+ }
526
+ const path = fileURLToPath(fixture)
527
+ const bytes = await fixtureBytes(endpoint, field, path)
528
+ const type = types.find((candidate) => bytesAreOfType(candidate, bytes.subarray(0, SNIFF_BYTES)))
529
+ if (type === undefined) {
530
+ throw new Error(`${endpoint}: the file of ${field}, ${path}, is none of the types of files.${kind} (${types.join(', ')})`)
531
+ }
532
+ return new File([bytes], basename(path), { type })
533
+ }
534
+
535
+ // A file fixture is read once; every case sends the same bytes.
536
+ const fixtureFiles = new Map<string, Uint8Array<ArrayBuffer>>()
537
+ const fixtureBytes = async (endpoint: string, field: string, path: string): Promise<Uint8Array<ArrayBuffer>> => {
538
+ const known = fixtureFiles.get(path)
539
+ if (known !== undefined) return known
540
+ let bytes: Uint8Array<ArrayBuffer>
541
+ try {
542
+ bytes = new Uint8Array(await readFile(path))
543
+ } catch {
544
+ throw new Error(`${endpoint}: the file of ${field} in the fixtures, ${path}, cannot be read; add it to the repository or correct its path`)
545
+ }
546
+ fixtureFiles.set(path, bytes)
547
+ return bytes
452
548
  }
453
549
 
454
550
  const askAs = async (
455
551
  row: ActionEndpoint,
456
552
  fetch: RpcFetch,
457
553
  body: Readonly<Record<string, unknown>>,
554
+ refusals: Refusals = 'none',
458
555
  ): Promise<{ readonly status: number; readonly text: string }> => {
459
556
  stockSeededObjects()
460
- const [url, init] = requestOf(row, body)
557
+ const [url, init] = await requestOf(row, body)
461
558
  const response = await fetch(url, init)
462
559
  const text = await response.text()
463
560
  // A 400 hides what the case is about: input is parsed before the access form runs, and a handler's refusal of
464
561
  // the input it was given is no answer to another scope. Either is what the generator could not build.
465
562
  if (response.status === 400) {
466
563
  const type = errorType(text)
564
+ const declared = type !== undefined && type !== 'validation' && options.refusals?.[row.id]?.includes(type) === true
565
+ // The own case may take it: it shows the access form let the caller through. The answer a leak case checks, or a
566
+ // global case's, would pass holding nothing, which proves nothing.
567
+ if (declared && refusals === 'declared') {
568
+ return { status: response.status, text }
569
+ }
570
+ if (declared) {
571
+ throw new Error(
572
+ `${row.id}: the handler answered its declared refusal (400 ${type}), which only the own case takes; this case proves nothing on it until the fixtures give what the handler needs (pins, files, fixtures) (${text})`,
573
+ )
574
+ }
467
575
  throw new Error(
468
576
  type === 'validation'
469
577
  ? `${row.id}: the case's input does not match the endpoint's input schema; correct its fixture (${text})`
470
578
  : `${row.id}: the handler refused the case's input (400 ${
471
579
  type ?? 'without a type'
472
- }); the case cannot reach what it tests until its fixtures give what the handler needs: a picked person in members, a row of its object in rows, the state in seeds or the whole input in fixtures (${text})`,
580
+ }); the case cannot reach what it tests until its fixtures give what the handler needs: a picked person in members, a row of its object in rows, the state in seeds, a file it accepts in files, the whole input in fixtures, or the refusal it answers in refusals (${text})`,
473
581
  )
474
582
  }
475
583
  return { status: response.status, text }
@@ -485,6 +593,7 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
485
593
  field: SchemaShape | undefined,
486
594
  seed: Seed,
487
595
  input: Readonly<Record<string, unknown>>,
596
+ pinning: Pinning = NO_PINNING,
488
597
  ): Promise<Scopes> => {
489
598
  const named = rowFields(input)
490
599
  const owner = ownerOf(dimension)
@@ -505,7 +614,7 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
505
614
  },
506
615
  }
507
616
  }
508
- const worlds = await postgres.seedWorlds(tables, owner, seed)
617
+ const worlds = pinned(await postgres.seedWorlds(tables, owner, seed, pinning.pins), pinning)
509
618
  const own = await rowsIn(worlds.own, named)
510
619
  const other = await rowsIn(worlds.other, named)
511
620
  return {
@@ -560,14 +669,17 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
560
669
  * For a report `in` `dimension`: one row in each scope of every table that lies in it, the table that owns it with
561
670
  * `seed`. Each side's targets are its rows' values of `dimension`, and each caller holds all of them.
562
671
  */
563
- const inScopesOf = async (action: string, dimension: string, field: SchemaShape | undefined, seed: Seed) => {
672
+ const inScopesOf = async (action: string, dimension: string, field: SchemaShape | undefined, seed: Seed, pinning: Pinning = NO_PINNING) => {
564
673
  const own: InTarget[] = []
565
674
  const other: InTarget[] = []
566
675
  const values: string[] = []
567
676
  for (const name of tableNames) {
568
677
  const mode = policies[name]?.scope.mode
569
678
  if (mode !== 'dimension' && mode !== 'child') continue
570
- const worlds = await postgres.seedWorlds(tables, name, name === ownerOf(dimension) ? seed : {})
679
+ const owned = name === ownerOf(dimension)
680
+ const worlds = owned
681
+ ? pinned(await postgres.seedWorlds(tables, name, seed, pinning.pins), pinning)
682
+ : await postgres.seedWorlds(tables, name)
571
683
  const ownAt = worlds.own.chain.findIndex((link) => link.type === dimension)
572
684
  const otherAt = worlds.other.chain.findIndex((link) => link.type === dimension)
573
685
  const ownValue = worlds.own.chain[ownAt]?.value
@@ -579,7 +691,7 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
579
691
  }
580
692
  }
581
693
  if (own.length === 0) {
582
- const scopes = await scopesOf(action, dimension, field, seed, {})
694
+ const scopes = await scopesOf(action, dimension, field, seed, {}, pinning)
583
695
  return { own: [scopes.own], other: [scopes.other], values: scopes.other.values }
584
696
  }
585
697
  return { own, other, values }
@@ -702,6 +814,7 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
702
814
  mount: string,
703
815
  seed: Seed,
704
816
  input: Readonly<Record<string, unknown>>,
817
+ pinning: Pinning,
705
818
  ): Promise<{ readonly fetch: RpcFetch; readonly rows: Readonly<Record<string, string>> }> => {
706
819
  const access = row.access
707
820
  if (access.form !== 'on') {
@@ -711,7 +824,7 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
711
824
  if (owner === undefined) {
712
825
  throw new Error(`${row.id}: no table owns ${access.dimension}, so no link can be bound to one`)
713
826
  }
714
- const { own } = await postgres.seedWorlds(tables, owner, seed)
827
+ const { own } = pinned(await postgres.seedWorlds(tables, owner, seed, pinning.pins), pinning)
715
828
  const holder = kit.testCaller([{ action: row.action, scope: { type: access.dimension, value: own.key } }], {
716
829
  kind: 'link',
717
830
  link: { mount, chain: own.chain },
@@ -724,147 +837,196 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
724
837
  return { fetch, rows: (await rowsIn(own, rowFields(input))).rows }
725
838
  }
726
839
 
727
- const accessKit: EndpointAccessKit = {
728
- async denied(endpoint, input, seed = {}) {
729
- const row = endpointOf(endpoint)
730
- const { action, access } = row
731
- if (access.form !== 'on' && access.form !== 'in') {
732
- throw new Error(`${endpoint} has the access form ${access.form}; only on and in name an object or a scope value`)
733
- }
734
- const scopes = await scopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, input)
735
- const asked = addressing(input, access.from, scopes.other)
736
- const { status } = await ask(row, holding(row, input, scopes.own.grants, scopes.own.chain), asked, scopes.own.chain)
737
- return { status }
738
- },
739
- async leaked(endpoint, input, seed = {}) {
740
- const row = endpointOf(endpoint)
741
- const { action, access } = row
742
- if (access.form === 'in') {
743
- const scopes = await inScopesOf(action, access.dimension, fieldOf(row.input, access.from), seed)
744
- const grants = (targets: readonly InTarget[]): Grant[] =>
745
- targets.flatMap(({ target, chain }) => holding(row, input, [{ action, scope: { type: access.dimension, value: target } }], chain))
746
- const marks: string[] = []
747
- for (const side of scopes.other) {
748
- const answer = await ask(row, grants(scopes.other), addressing(input, access.from, side), side.chain)
749
- marks.push(...answer.marks)
840
+ // The cases of one call: `removals` takes the removal of the application rows it seeds, which `drained` runs once
841
+ // the call and the runs it kicked are over. A list per call, so a concurrent case never removes the rows another
842
+ // was given; the generated cases run one after another, since a row a required foreign key needed is shared.
843
+ const accessKitOf = (removals: (() => Promise<void>)[]): EndpointAccessKit => {
844
+ /** The pins of `endpoint`, whose seeded rows this call removes once it is over. */
845
+ const pinningOf = (endpoint: string): Pinning => ({ pins: options.pins?.[endpoint] ?? {}, removals })
846
+
847
+ /** One row of each application table `appRows` names, for this call only. */
848
+ const seedAppRows = async (appRows: AppRows): Promise<void> => {
849
+ if (Object.keys(appRows).length === 0) return
850
+ removals.push((await postgres.seedApplicationRows(tables, appRows)).remove)
851
+ }
852
+
853
+ return {
854
+ async denied(endpoint, input, seed = {}) {
855
+ const row = endpointOf(endpoint)
856
+ const { action, access } = row
857
+ if (access.form !== 'on' && access.form !== 'in') {
858
+ throw new Error(`${endpoint} has the access form ${access.form}; only on and in name an object or a scope value`)
750
859
  }
751
- const answers = []
752
- for (const side of scopes.own) {
753
- answers.push(await ask(row, grants(scopes.own), addressing(input, access.from, side), side.chain))
860
+ const scopes = await scopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, input, pinningOf(endpoint))
861
+ const asked = addressing(input, access.from, scopes.other)
862
+ const { status } = await ask(row, holding(row, input, scopes.own.grants, scopes.own.chain), asked, scopes.own.chain)
863
+ return { status }
864
+ },
865
+ async leaked(endpoint, input, seed = {}, appRows = {}) {
866
+ const row = endpointOf(endpoint)
867
+ const { action, access } = row
868
+ if (access.form === 'in') {
869
+ await seedAppRows(appRows)
870
+ const scopes = await inScopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, pinningOf(endpoint))
871
+ const grants = (targets: readonly InTarget[]): Grant[] =>
872
+ targets.flatMap(({ target, chain }) => holding(row, input, [{ action, scope: { type: access.dimension, value: target } }], chain))
873
+ const marks: string[] = []
874
+ for (const side of scopes.other) {
875
+ const answer = await ask(row, grants(scopes.other), addressing(input, access.from, side), side.chain, 'declared')
876
+ marks.push(...answer.marks)
877
+ }
878
+ const answers = []
879
+ for (const side of scopes.own) {
880
+ answers.push(await ask(row, grants(scopes.own), addressing(input, access.from, side), side.chain))
881
+ }
882
+ return leakOutcome(answers, [...scopes.values, ...marks])
754
883
  }
755
- return leakOutcome(answers, [...scopes.values, ...marks])
756
- }
757
- if (access.form !== 'on' && access.form !== 'over') {
758
- throw new Error(`${endpoint} has the access form ${access.form}; only on, in and over answer with rows of a scope`)
759
- }
760
- const scopes = access.form === 'on'
761
- ? await scopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, input)
762
- : await listScopesOf(action, access.dimension)
763
- const from = access.form === 'on' ? access.from : null
764
- const other = await ask(
765
- row,
766
- holding(row, input, scopes.other.grants, scopes.other.chain),
767
- addressing(input, from, scopes.other),
768
- scopes.other.chain,
769
- )
770
- const answer = await ask(
771
- row,
772
- holding(row, input, scopes.own.grants, scopes.own.chain),
773
- addressing(input, from, scopes.own),
774
- scopes.own.chain,
775
- )
776
- return leakOutcome([answer], [...scopes.other.values, ...other.marks])
777
- },
778
- async own(endpoint, input, seed = {}) {
779
- const row = endpointOf(endpoint)
780
- const { action, access } = row
781
- if (access.form !== 'on') {
782
- throw new Error(`${endpoint} has the access form ${access.form}; only on addresses an object of its own`)
783
- }
784
- if (row.link !== null) {
785
- const holder = await linkHolder(row, row.link, seed, input)
786
- const { status } = await askAs(row, holder.fetch, { ...input, ...holder.rows })
884
+ if (access.form !== 'on' && access.form !== 'over') {
885
+ throw new Error(`${endpoint} has the access form ${access.form}; only on, in and over answer with rows of a scope`)
886
+ }
887
+ await seedAppRows(appRows)
888
+ const scopes = access.form === 'on'
889
+ ? await scopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, input, pinningOf(endpoint))
890
+ : await listScopesOf(action, access.dimension)
891
+ const from = access.form === 'on' ? access.from : null
892
+ // The other scope asks first, to fill whatever a handler keeps between requests; its pins differ from the own
893
+ // scope's, so a refusal the fixtures declare is its answer too. The own scope's answer is the one checked.
894
+ const other = await ask(
895
+ row,
896
+ holding(row, input, scopes.other.grants, scopes.other.chain),
897
+ addressing(input, from, scopes.other),
898
+ scopes.other.chain,
899
+ 'declared',
900
+ )
901
+ const answer = await ask(
902
+ row,
903
+ holding(row, input, scopes.own.grants, scopes.own.chain),
904
+ addressing(input, from, scopes.own),
905
+ scopes.own.chain,
906
+ )
907
+ return leakOutcome([answer], [...scopes.other.values, ...other.marks])
908
+ },
909
+ async own(endpoint, input, seed = {}, appRows = {}) {
910
+ const row = endpointOf(endpoint)
911
+ const { action, access } = row
912
+ if (access.form !== 'on') {
913
+ throw new Error(`${endpoint} has the access form ${access.form}; only on addresses an object of its own`)
914
+ }
915
+ await seedAppRows(appRows)
916
+ if (row.link !== null) {
917
+ const holder = await linkHolder(row, row.link, seed, input, pinningOf(endpoint))
918
+ const { status } = await askAs(row, holder.fetch, { ...input, ...holder.rows }, 'declared')
919
+ return { status }
920
+ }
921
+ const scopes = await scopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, input, pinningOf(endpoint))
922
+ const { status } = await ask(
923
+ row,
924
+ holding(row, input, scopes.own.grants, scopes.own.chain),
925
+ addressing(input, access.from, scopes.own),
926
+ scopes.own.chain,
927
+ 'declared',
928
+ )
787
929
  return { status }
930
+ },
931
+ async scoped(endpoint, input) {
932
+ const row = globalEndpointOf(endpoint)
933
+ const dimension = row.access.form === 'creates' ? row.access.dimension : scopeTypeOf(kit.artifact.dimensions)
934
+ const { status } = await ask(row, [{ action: row.action, scope: { type: dimension, value: freshValue(dimension, 'own', undefined) } }], input, [])
935
+ return { status }
936
+ },
937
+ async anyone(endpoint, input) {
938
+ const row = kit.artifact.endpoints.find((candidate) => candidate.id === endpoint)
939
+ if (row?.kind !== 'public') {
940
+ throw new Error(`${endpoint} is not a public procedure of the contract`)
941
+ }
942
+ const response = await kit.fetch(row.path, {
943
+ method: row.method,
944
+ headers: { 'Content-Type': 'application/json', Origin: kit.origin, 'Sec-Fetch-Site': 'same-origin' },
945
+ body: JSON.stringify(input),
946
+ })
947
+ const status = response.status
948
+ const challenged = status === 400 && errorType(await response.text()) === 'challenge_failed'
949
+ return status >= 500 || status === 401 || status === 403 || challenged ? { answered: false, status } : { answered: true }
950
+ },
951
+ async global(endpoint, input) {
952
+ const row = globalEndpointOf(endpoint)
953
+ const { status } = await askAs(row, callerFor(row, [{ action: row.action }]).fetch, input)
954
+ // Neither form refuses with 404, so a 404 is the handler's own answer (a row the sampled input names is missing).
955
+ return status >= 500 || status === 401 || status === 403 ? { answered: false, status } : { answered: true }
956
+ },
957
+ async capability(endpoint, capability, input, seed = {}) {
958
+ const { requirement, capabilities } = capabilitiesEndpointOf(endpoint)
959
+ const named = capabilities.get(capability)
960
+ if (named === undefined) {
961
+ throw new Error(`${endpoint} has no capability '${capability}' (capabilities: ${[...capabilities.keys()].join(', ')})`)
962
+ }
963
+ const { access } = named
964
+ const ruledOutBy = deniedCaseRuledOutBy(requirement.capabilities, capability, kit.artifact.dimensions)
965
+ if (ruledOutBy !== undefined) {
966
+ throw new Error(
967
+ `${endpoint}: capability '${capability}' has no denied case: '${ruledOutBy}' needs its action too, ${named.action}, in a related dimension, so every caller that passes it is answered the list`,
968
+ )
969
+ }
970
+ const grants: Grant[] = []
971
+ let asked = input
972
+ for (const [name, other] of capabilities) {
973
+ if (name === capability) continue
974
+ // Each other one in a scope of its own, apart from the named one's: a global grant would also meet the named
975
+ // capability when both share an action. An `over` one lists from any value it is held in, so a fresh uuid does,
976
+ // a valid key whether the dimension's is text or uuid, and no row of it is seeded.
977
+ if (other.access.form === 'over') {
978
+ grants.push({ action: other.action, scope: { type: other.access.dimension, value: crypto.randomUUID() } })
979
+ } else if (other.access.form === 'on' || other.access.form === 'in') {
980
+ const { own } = await scopesOf(other.action, other.access.dimension, fieldOf(other.input, other.access.from), {}, input)
981
+ asked = addressing(asked, other.access.from, own)
982
+ grants.push(...own.grants)
983
+ }
984
+ }
985
+ if (access.form === 'on' || access.form === 'in') {
986
+ const scopes = await scopesOf(named.action, access.dimension, fieldOf(named.input, access.from), seed, input, pinningOf(endpoint))
987
+ asked = addressing(asked, access.from, scopes.other)
988
+ grants.push(...scopes.own.grants)
989
+ }
990
+ const { status } = await askAs(named, callerFor(named, grants).fetch, asked)
991
+ return { status }
992
+ },
993
+ }
994
+ }
995
+ // Each case waits for the runs its requests kicked, so the suite's teardown never closes the database under one, and
996
+ // only then removes its application rows, which those runs may still read. Every step runs whatever failed before
997
+ // it, and the case's own error is thrown first.
998
+ const drained =
999
+ <A extends readonly unknown[], R>(method: (kit: EndpointAccessKit) => (...args: A) => Promise<R>) => async (...args: A): Promise<R> => {
1000
+ const removals: (() => Promise<void>)[] = []
1001
+ let outcome: { readonly ok: true; readonly value: R } | { readonly ok: false; readonly error: unknown }
1002
+ try {
1003
+ outcome = { ok: true, value: await method(accessKitOf(removals))(...args) }
1004
+ } catch (error) {
1005
+ outcome = { ok: false, error }
788
1006
  }
789
- const scopes = await scopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, input)
790
- const { status } = await ask(
791
- row,
792
- holding(row, input, scopes.own.grants, scopes.own.chain),
793
- addressing(input, access.from, scopes.own),
794
- scopes.own.chain,
795
- )
796
- return { status }
797
- },
798
- async scoped(endpoint, input) {
799
- const row = globalEndpointOf(endpoint)
800
- const dimension = row.access.form === 'creates' ? row.access.dimension : scopeTypeOf(kit.artifact.dimensions)
801
- const { status } = await ask(row, [{ action: row.action, scope: { type: dimension, value: freshValue(dimension, 'own', undefined) } }], input, [])
802
- return { status }
803
- },
804
- async anyone(endpoint, input) {
805
- const row = kit.artifact.endpoints.find((candidate) => candidate.id === endpoint)
806
- if (row?.kind !== 'public') {
807
- throw new Error(`${endpoint} is not a public procedure of the contract`)
808
- }
809
- const response = await kit.fetch(row.path, {
810
- method: row.method,
811
- headers: { 'Content-Type': 'application/json', Origin: kit.origin, 'Sec-Fetch-Site': 'same-origin' },
812
- body: JSON.stringify(input),
813
- })
814
- const status = response.status
815
- const challenged = status === 400 && errorType(await response.text()) === 'challenge_failed'
816
- return status >= 500 || status === 401 || status === 403 || challenged ? { answered: false, status } : { answered: true }
817
- },
818
- async global(endpoint, input) {
819
- const row = globalEndpointOf(endpoint)
820
- const { status } = await askAs(row, callerFor(row, [], [{ action: row.action }]).fetch, input)
821
- // Neither form refuses with 404, so a 404 is the handler's own answer (a row the sampled input names is missing).
822
- return status >= 500 || status === 401 || status === 403 ? { answered: false, status } : { answered: true }
823
- },
824
- async capability(endpoint, capability, input, seed = {}) {
825
- const capabilities = capabilitiesEndpointOf(endpoint)
826
- const named = capabilities.get(capability)
827
- if (named === undefined) {
828
- throw new Error(`${endpoint} has no capability '${capability}' (capabilities: ${[...capabilities.keys()].join(', ')})`)
829
- }
830
- const grants: Grant[] = []
831
- const global: { readonly action: string }[] = []
832
- let asked = input
833
- for (const [name, other] of capabilities) {
834
- if (name === capability) continue
835
- if (other.access.form === 'over') {
836
- global.push({ action: other.action })
837
- } else if (other.access.form === 'on' || other.access.form === 'in') {
838
- const { own } = await scopesOf(other.action, other.access.dimension, fieldOf(other.input, other.access.from), {}, input)
839
- asked = addressing(asked, other.access.from, own)
840
- grants.push(...own.grants)
1007
+ const failures: unknown[] = []
1008
+ for (const step of [() => kit.drain(), ...removals]) {
1009
+ try {
1010
+ await step()
1011
+ } catch (error) {
1012
+ failures.push(error)
841
1013
  }
842
1014
  }
843
- const { access } = named
844
- if (access.form === 'on' || access.form === 'in') {
845
- const scopes = await scopesOf(named.action, access.dimension, fieldOf(named.input, access.from), seed, input)
846
- asked = addressing(asked, access.from, scopes.other)
847
- grants.push(...scopes.own.grants)
1015
+ if (!outcome.ok) {
1016
+ if (failures.length === 0) throw outcome.error
1017
+ throw new AggregateError([outcome.error, ...failures], 'the case failed, and so did its cleanup')
848
1018
  }
849
- const { status } = await askAs(named, callerFor(named, grants, global).fetch, asked)
850
- return { status }
851
- },
852
- }
853
- // Each case waits for the runs its requests kicked, so the suite's teardown never closes the database under one.
854
- const drained = <A extends readonly unknown[], R>(method: (...args: A) => Promise<R>) => async (...args: A): Promise<R> => {
855
- try {
856
- return await method(...args)
857
- } finally {
858
- await kit.drain()
1019
+ if (failures.length === 1) throw failures[0]
1020
+ if (failures.length > 1) throw new AggregateError(failures, 'the cleanup of the case failed')
1021
+ return outcome.value
859
1022
  }
860
- }
861
1023
  return Object.freeze({
862
- denied: drained(accessKit.denied),
863
- leaked: drained(accessKit.leaked),
864
- own: drained(accessKit.own),
865
- scoped: drained(accessKit.scoped),
866
- global: drained(accessKit.global),
867
- anyone: drained(accessKit.anyone),
868
- capability: drained(accessKit.capability),
1024
+ denied: drained((cases) => cases.denied),
1025
+ leaked: drained((cases) => cases.leaked),
1026
+ own: drained((cases) => cases.own),
1027
+ scoped: drained((cases) => cases.scoped),
1028
+ global: drained((cases) => cases.global),
1029
+ anyone: drained((cases) => cases.anyone),
1030
+ capability: drained((cases) => cases.capability),
869
1031
  })
870
1032
  }