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

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 +73 -16
  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 +27 -4
  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 +493 -202
  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 +228 -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,
@@ -18,10 +19,14 @@ import {
18
19
  } from '@fabrika/auth-core'
19
20
  import type { Tables } from '@fabrika/db'
20
21
  import { tablePolicies } from '@fabrika/db/tables'
21
- import { type IsolationWorlds, type SampleValue, SEEDED_OBJECT_VERSION, type TestDatabase, type WorldRow } from '@fabrika/db/testing'
22
+ import { type IsolationWorlds, type SampleValue, type ScopeValues, SEEDED_OBJECT_VERSION, type TestDatabase } 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,
@@ -29,10 +34,12 @@ import {
29
34
  GENERATED_INVITATION,
30
35
  GENERATED_LINK,
31
36
  GENERATED_MEMBER,
37
+ GENERATED_ROW_CAPABILITY,
32
38
  GENERATED_ROW_PREFIX,
33
39
  } from '../contract/defaults'
34
40
  import type { AnyContract } from '../contract/define'
35
41
  import type { FileScanner, ScanVerdict } from '../files/scan'
42
+ import { bytesAreOfType, SNIFF_BYTES } from '../files/sniff'
36
43
  import type { ApplicationEnvironment, ContractImplementation } from '../implement/implement'
37
44
  import type { TestCaller, TestGrant } from './caller'
38
45
  import { standInIamKit } from './kit'
@@ -58,6 +65,13 @@ export type ReachOutcome = { readonly answered: true } | { readonly answered: fa
58
65
  /** Column → value of the row of the table that owns the endpoint's dimension, in both scopes: the author's seed. */
59
66
  export type Seed = Readonly<Record<string, SampleValue>>
60
67
 
68
+ /**
69
+ * Table → column → value: one row of each application table the handler reads for the caller's own scope, seeded
70
+ * 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
71
+ * finds it. Both scopes may see it, so its values are never counted as the other scope's.
72
+ */
73
+ export type AppRows = Readonly<Record<string, Seed>>
74
+
61
75
  export interface EndpointAccessKit {
62
76
  /**
63
77
  * A caller holding the endpoint's action in one scope names an object (`on`) or a scope value (`in`) of another;
@@ -66,16 +80,18 @@ export interface EndpointAccessKit {
66
80
  denied(endpoint: string, input: Readonly<Record<string, unknown>>, seed?: Seed): Promise<DeniedOutcome>
67
81
  /**
68
82
  * 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`).
83
+ * (`over`) or, for every table that lies in the dimension, its scope value (`in`). `appRows` are seeded first, as
84
+ * for `own`.
70
85
  */
71
- leaked(endpoint: string, input: Readonly<Record<string, unknown>>, seed?: Seed): Promise<LeakOutcome>
86
+ leaked(endpoint: string, input: Readonly<Record<string, unknown>>, seed?: Seed, appRows?: AppRows): Promise<LeakOutcome>
72
87
  /**
73
88
  * 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
89
  * a link mount, the holder of a link bound to the object. A write action reads its own target. Where IAM requires more
75
90
  * 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.
91
+ * issuer the actions the link grants. `appRows` are the rows of application tables its handler reads (the guide a link
92
+ * holder downloads), each seeded first.
77
93
  */
78
- own(endpoint: string, input: Readonly<Record<string, unknown>>, seed?: Seed): Promise<DeniedOutcome>
94
+ own(endpoint: string, input: Readonly<Record<string, unknown>>, seed?: Seed, appRows?: AppRows): Promise<DeniedOutcome>
79
95
  /**
80
96
  * An `app` or a `creates` endpoint asked by a caller who holds its action in one value of a dimension only, never
81
97
  * globally: refused (403), by the proxy for `app` and by IAM for `creates`, since both need a global grant.
@@ -88,9 +104,10 @@ export interface EndpointAccessKit {
88
104
  global(endpoint: string, input: Readonly<Record<string, unknown>>): Promise<ReachOutcome>
89
105
  /**
90
106
  * 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.
107
+ * action in a scope of its own and addresses its object or value there. For an `on` or `in` capability it also holds
108
+ * the named one's action in its own scope and addresses the other's object (404) or value (403); for `over` it holds
109
+ * the named action only where the others need it (403). An `over` capability without a denied case
110
+ * (`deniedCaseRuledOutBy`) throws. `seed` is the named one's.
94
111
  */
95
112
  capability(endpoint: string, capability: string, input: Readonly<Record<string, unknown>>, seed?: Seed): Promise<DeniedOutcome>
96
113
  /**
@@ -101,6 +118,53 @@ export interface EndpointAccessKit {
101
118
  anyone(endpoint: string, input: Readonly<Record<string, unknown>>): Promise<ReachOutcome>
102
119
  }
103
120
 
121
+ export interface EndpointAccessOptions {
122
+ /**
123
+ * The file every case of an endpoint sends in a file field instead of the kit's sample, by endpoint id and input
124
+ * field: a file of the application's repository that a handler inspecting the content accepts (a valid package). Its
125
+ * type is the first of the field's kind that its bytes are; a file of none of them throws. `files` of the fixtures.
126
+ */
127
+ readonly files?: Readonly<Record<string, Readonly<Record<string, URL>>>>
128
+ /**
129
+ * The error types of the refusals (400) an endpoint's handler answers its own object with when the case's input meets
130
+ * no domain rule the kit can satisfy, by endpoint id: such a 400 is the handler's own answer, so the request passed
131
+ * the access form, and the endpoint's own case gets it as `{ status: 400 }` instead of failing; so does the other
132
+ * scope's request a leak case makes first. The own scope's answer of a leak case, and a global or capability case,
133
+ * still throw on it (an answer that holds nothing proves no isolation), so does any other 400, and an input the schema
134
+ * refuses (`validation`) always does. `refusals` of the fixtures.
135
+ */
136
+ readonly refusals?: Readonly<Record<string, readonly string[]>>
137
+ /**
138
+ * Known values for text columns of the row the endpoint addresses (the row of the table that owns its dimension), by
139
+ * endpoint id: the value in the own scope's row, and `<value>-other` in the other scope's, which counts among the
140
+ * other scope's values a leak shows. For a handler whose rule ties a column to the input or a file fixture (a package
141
+ * that names the skill's slug). `pins` of the fixtures.
142
+ */
143
+ readonly pins?: Readonly<Record<string, Readonly<Record<string, string>>>>
144
+ }
145
+
146
+ /**
147
+ * Whether a request takes a refusal the fixtures declare for its endpoint as the handler's answer: an own case's, and the
148
+ * other scope's request a leak case makes first, whose answer is not the one checked.
149
+ */
150
+ type Refusals = 'declared' | 'none'
151
+
152
+ /**
153
+ * The pins of a case's endpoint (column → the own scope's value of a text column), and the removals of the case: rows
154
+ * seeded with pins or known scope values are removed once the case is over, so the next case can seed the same values
155
+ * under a unique index.
156
+ */
157
+ interface Pinning {
158
+ readonly pins: Readonly<Record<string, string>>
159
+ readonly removals: (() => Promise<void>)[]
160
+ }
161
+
162
+ /** Seeded worlds, their removal taken by the case when they hold pinned values or known scope values. */
163
+ const pinned = <W extends { readonly remove: () => Promise<void> }>(worlds: W, pinning: Pinning, scopes: ScopeValues): W => {
164
+ if (Object.keys(pinning.pins).length > 0 || Object.keys(scopes).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. */
@@ -139,11 +203,19 @@ interface Scopes {
139
203
  readonly other: Side & { readonly values: readonly string[] }
140
204
  }
141
205
 
142
- /** The input fields that name a row the kit seeds in the case's object (`rows`), with the row's table. */
143
- function rowFields(input: Readonly<Record<string, unknown>>): readonly { readonly field: string; readonly table: string }[] {
144
- return Object.entries(input).flatMap(([field, value]) =>
145
- typeof value === 'string' && value.startsWith(GENERATED_ROW_PREFIX) ? [{ field, table: value.slice(GENERATED_ROW_PREFIX.length) }] : []
146
- )
206
+ /**
207
+ * The input fields that name a row the kit seeds in the case's scopes (`rows`), with the row's table and, on an endpoint
208
+ * of several capabilities, the capability whose scope it lies in.
209
+ */
210
+ function rowFields(
211
+ input: Readonly<Record<string, unknown>>,
212
+ ): readonly { readonly field: string; readonly table: string; readonly capability: string | null }[] {
213
+ return Object.entries(input).flatMap(([field, value]) => {
214
+ if (typeof value !== 'string' || !value.startsWith(GENERATED_ROW_PREFIX)) return []
215
+ const named = value.slice(GENERATED_ROW_PREFIX.length)
216
+ const at = named.indexOf(GENERATED_ROW_CAPABILITY)
217
+ return [at === -1 ? { field, table: named, capability: null } : { field, table: named.slice(0, at), capability: named.slice(at + 1) }]
218
+ })
147
219
  }
148
220
 
149
221
  /** A case's input, and the values it named that only its own scope may see in an answer: a generated member's id and label. */
@@ -152,12 +224,16 @@ interface Addressed {
152
224
  readonly marks: readonly string[]
153
225
  }
154
226
 
155
- /** One target of an `in` report, with its chain from the target outward. */
227
+ /** One target of an `in` report, with its chain from the target outward, and the key of each row `rows` names in it. */
156
228
  interface InTarget {
157
229
  readonly target: string
158
230
  readonly chain: Chain
231
+ readonly rows: Readonly<Record<string, string>>
159
232
  }
160
233
 
234
+ /** An input field that names a row the kit seeds (`rows`), with the row's table. */
235
+ type RowField = ReturnType<typeof rowFields>[number]
236
+
161
237
  export type Grant =
162
238
  | { readonly action: string; readonly scope: { readonly type: string; readonly value: string } }
163
239
  | { readonly role: string; readonly scope: { readonly type: string; readonly value: string } }
@@ -188,6 +264,40 @@ function errorType(text: string): string | undefined {
188
264
  }
189
265
  }
190
266
 
267
+ /** The values a field admits when they are a fixed set: an enum, a string literal or a union of them; else `undefined`. */
268
+ function fixedValues(field: SchemaShape | undefined): readonly string[] | undefined {
269
+ switch (field?.type) {
270
+ case 'enum':
271
+ return field.values
272
+ case 'literal':
273
+ return typeof field.value === 'string' ? [field.value] : undefined
274
+ case 'union': {
275
+ const options = field.options.map(fixedValues)
276
+ return options.every((values) => values !== undefined) ? [...new Set(options.flat())] : undefined
277
+ }
278
+ default:
279
+ return undefined
280
+ }
281
+ }
282
+
283
+ /**
284
+ * The values of `dimension` a case's two scopes take when the input field it is read from admits a fixed set: its first
285
+ * two, which a stored row of the table that owns it may already hold. None otherwise, so each scope gets a fresh value.
286
+ */
287
+ function knownScopes(dimension: string, field: SchemaShape | undefined): ScopeValues {
288
+ const values = fixedValues(field)
289
+ if (values === undefined) return {}
290
+ const [own, other] = values
291
+ if (own === undefined || other === undefined) {
292
+ throw new Error(
293
+ `the input field a ${dimension} is read from admits only ${
294
+ values.map((value) => `'${value}'`).join(', ')
295
+ }, so no case can ask from two scopes of it; admit two values or more`,
296
+ )
297
+ }
298
+ return { [dimension]: { own, other } }
299
+ }
300
+
191
301
  /** A scope value no table holds, in the format of the input field it is sent in. */
192
302
  function freshValue(dimension: string, world: 'own' | 'other', field: SchemaShape | undefined): string {
193
303
  const format = field?.type === 'string' ? field.format : null
@@ -201,10 +311,23 @@ function fieldOf(input: SchemaShape | null, from: string | null): SchemaShape |
201
311
  return input?.type === 'object' && from !== null ? input.fields[from] : undefined
202
312
  }
203
313
 
204
- /** Every value of the other world a leak shows: its key, parent, every dimension value it lies in, and its markers. */
205
- function worldValues(worlds: IsolationWorlds, world: 'own' | 'other'): string[] {
314
+ /**
315
+ * Every value of the other world a leak shows: its key, parent, every dimension value it lies in, and its markers. A
316
+ * known scope value, and a text of a row the table already held, other rows may share, and a short word is part of
317
+ * unrelated text: each counts only as a whole JSON string (`"eu"`). A stored text the own row holds too is no leak.
318
+ */
319
+ function worldValues(worlds: IsolationWorlds, world: 'own' | 'other', scopes: ScopeValues): string[] {
206
320
  const row = worlds[world]
207
- return [...new Set([row.key, row.scope, ...(row.parent === null ? [] : [row.parent]), ...row.chain.map((link) => link.value), ...row.markers])]
321
+ const shared = new Set(world === 'other' ? worlds.own.stored : worlds.other.stored)
322
+ const values = [row.key, row.scope, ...(row.parent === null ? [] : [row.parent]), ...row.chain.map((link) => link.value), ...row.markers]
323
+ const stored = row.stored.filter((value) => !shared.has(value))
324
+ return [...new Set([...values.map((value) => shownValue(value, scopes)), ...stored.map((value) => JSON.stringify(value))])]
325
+ }
326
+
327
+ /** A value of a scope as a leak shows it: a known scope value as a whole JSON string, any other as it is. */
328
+ function shownValue(value: string, scopes: ScopeValues): string {
329
+ const known = Object.values(scopes).some((values) => values.own === value || values.other === value)
330
+ return known ? JSON.stringify(value) : value
208
331
  }
209
332
 
210
333
  /** The cases' scanner: a file it reads in full is clean, so a seeded upload of a `scan: true` collection is served. */
@@ -276,7 +399,12 @@ export const managerGrants = (
276
399
  * The endpoint access kit of `app`, whose data layer is `scoped(tables)`, over `postgres`. It boots `app` once, so the
277
400
  * application's layer is bound here and nowhere else in the process.
278
401
  */
279
- export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract>, tables: Tables<DB, P>, postgres: TestDatabase): EndpointAccessKit {
402
+ export function endpointAccessKit<DB, P>(
403
+ app: ContractImplementation<AnyContract>,
404
+ tables: Tables<DB, P>,
405
+ postgres: TestDatabase,
406
+ options: EndpointAccessOptions = {},
407
+ ): EndpointAccessKit {
280
408
  // The objects of the files the cases seed live in memory; their rows are the application's own tables.
281
409
  const objects = new MemoryFileObjects()
282
410
  const { kit, standIn } = standInIamKit(app, {
@@ -327,14 +455,16 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
327
455
  )
328
456
  }
329
457
 
330
- /** An endpoint of several capabilities, as one `ActionEndpoint` per capability, by its name. */
331
- const capabilitiesEndpointOf = (id: string): ReadonlyMap<string, ActionEndpoint> => {
458
+ /** An endpoint of several capabilities: its requirement, and one `ActionEndpoint` per capability, by its name. */
459
+ const capabilitiesEndpointOf = (
460
+ id: string,
461
+ ): { readonly requirement: CapabilitiesRequirement; readonly capabilities: ReadonlyMap<string, ActionEndpoint> } => {
332
462
  const row = kit.artifact.endpoints.find((candidate) => candidate.id === id)
333
463
  const requirement = row?.requirement
334
464
  if (row === undefined || requirement?.kind !== 'capabilities') {
335
465
  throw new Error(`${id} is not an endpoint of the contract with several capabilities`)
336
466
  }
337
- return new Map(
467
+ const capabilities = new Map(
338
468
  Object.entries(requirement.capabilities).map(([name, capability]) => [name, {
339
469
  id: row.id,
340
470
  link: null,
@@ -349,6 +479,7 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
349
479
  links: [],
350
480
  }]),
351
481
  )
482
+ return { requirement, capabilities }
352
483
  }
353
484
 
354
485
  const globalEndpointOf = (id: string): ActionEndpoint => {
@@ -368,21 +499,14 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
368
499
  return parent?.mode === 'dimension' ? (parent.container?.dimension ?? parent.dimension) : undefined
369
500
  }
370
501
 
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
- ]
502
+ /** A new caller holding `grants`; an action without a scope is held globally. */
503
+ const callerFor = (row: ActionEndpoint, grants: readonly TestGrant<AnyContract>[]): { readonly caller: TestCaller; readonly fetch: RpcFetch } => {
380
504
  if (row.callers.some((caller) => caller === 'human')) {
381
- const caller = kit.testCaller(asGrants)
505
+ const caller = kit.testCaller(grants)
382
506
  return { caller, fetch: kit.browser(caller) }
383
507
  }
384
508
  if (row.callers.some((caller) => caller === 'machine')) {
385
- const caller = kit.testCaller(asGrants, { kind: 'machine' })
509
+ const caller = kit.testCaller(grants, { kind: 'machine' })
386
510
  return {
387
511
  caller,
388
512
  fetch: (input, init) => {
@@ -395,16 +519,20 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
395
519
  throw new Error(`${row.id} admits neither a human nor a machine caller`)
396
520
  }
397
521
 
398
- /** A case's request by a new caller holding `grants`, its generated fields filled for `chain` and that caller. */
522
+ /**
523
+ * A case's request by a new caller holding `grants`, its generated fields filled for `chain` and that caller. Only an
524
+ * own case passes `refusals: 'declared'`.
525
+ */
399
526
  const ask = async (
400
527
  row: ActionEndpoint,
401
528
  grants: readonly Grant[],
402
529
  input: Readonly<Record<string, unknown>>,
403
530
  chain: Chain,
531
+ refusals: Refusals = 'none',
404
532
  ): Promise<{ readonly status: number; readonly text: string; readonly marks: readonly string[] }> => {
405
533
  const asker = callerFor(row, grants)
406
534
  const asked = withGenerated(row, input, chain, asker.caller)
407
- return { ...(await askAs(row, asker.fetch, asked.input)), marks: asked.marks }
535
+ return { ...(await askAs(row, asker.fetch, asked.input, refusals)), marks: asked.marks }
408
536
  }
409
537
 
410
538
  // A seeded file column references an empty object, which a handler that serves or opens the file reads here.
@@ -418,7 +546,7 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
418
546
  }
419
547
 
420
548
  /** 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] => {
549
+ const requestOf = async (row: ActionEndpoint, body: Readonly<Record<string, unknown>>): Promise<readonly [string, RequestInit]> => {
422
550
  if (row.method === 'GET') {
423
551
  const params = new URLSearchParams(Object.entries(body).map(([name, value]) => [name, value === null ? 'null' : String(value)]))
424
552
  return [params.size === 0 ? row.path : `${row.path}?${params}`, { method: 'GET' }]
@@ -437,7 +565,7 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
437
565
  for (const item of Array.isArray(value) ? value : [value]) {
438
566
  const kind = fileKindOf(item)
439
567
  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)])
568
+ files.push([name, await generatedFile(row.id, name, kind)])
441
569
  }
442
570
  }
443
571
  const form = new FormData()
@@ -446,68 +574,111 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
446
574
  return [row.path, { method: 'POST', body: form }]
447
575
  }
448
576
 
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 })
577
+ /** The file a case sends in `field`: the author's file fixture of the endpoint's field, else a sample of `kind`. */
578
+ const generatedFile = async (endpoint: string, field: string, kind: string): Promise<File> => {
579
+ const types = kit.artifact.fileKinds?.[kind]?.types ?? []
580
+ const fixture = options.files?.[endpoint]?.[field]
581
+ if (fixture === undefined) {
582
+ const sample = sampleFile(kind, types)
583
+ return new File([sample.bytes], `generated-${kind}`, { type: sample.type })
584
+ }
585
+ const path = fileURLToPath(fixture)
586
+ const bytes = await fixtureBytes(endpoint, field, path)
587
+ const type = types.find((candidate) => bytesAreOfType(candidate, bytes.subarray(0, SNIFF_BYTES)))
588
+ if (type === undefined) {
589
+ throw new Error(`${endpoint}: the file of ${field}, ${path}, is none of the types of files.${kind} (${types.join(', ')})`)
590
+ }
591
+ return new File([bytes], basename(path), { type })
592
+ }
593
+
594
+ // A file fixture is read once; every case sends the same bytes.
595
+ const fixtureFiles = new Map<string, Uint8Array<ArrayBuffer>>()
596
+ const fixtureBytes = async (endpoint: string, field: string, path: string): Promise<Uint8Array<ArrayBuffer>> => {
597
+ const known = fixtureFiles.get(path)
598
+ if (known !== undefined) return known
599
+ let bytes: Uint8Array<ArrayBuffer>
600
+ try {
601
+ bytes = new Uint8Array(await readFile(path))
602
+ } catch {
603
+ throw new Error(`${endpoint}: the file of ${field} in the fixtures, ${path}, cannot be read; add it to the repository or correct its path`)
604
+ }
605
+ fixtureFiles.set(path, bytes)
606
+ return bytes
452
607
  }
453
608
 
454
609
  const askAs = async (
455
610
  row: ActionEndpoint,
456
611
  fetch: RpcFetch,
457
612
  body: Readonly<Record<string, unknown>>,
613
+ refusals: Refusals = 'none',
458
614
  ): Promise<{ readonly status: number; readonly text: string }> => {
459
615
  stockSeededObjects()
460
- const [url, init] = requestOf(row, body)
616
+ const [url, init] = await requestOf(row, body)
461
617
  const response = await fetch(url, init)
462
618
  const text = await response.text()
463
619
  // A 400 hides what the case is about: input is parsed before the access form runs, and a handler's refusal of
464
620
  // the input it was given is no answer to another scope. Either is what the generator could not build.
465
621
  if (response.status === 400) {
466
622
  const type = errorType(text)
623
+ const declared = type !== undefined && type !== 'validation' && options.refusals?.[row.id]?.includes(type) === true
624
+ // The own case may take it: it shows the access form let the caller through. The answer a leak case checks, or a
625
+ // global case's, would pass holding nothing, which proves nothing.
626
+ if (declared && refusals === 'declared') {
627
+ return { status: response.status, text }
628
+ }
629
+ if (declared) {
630
+ throw new Error(
631
+ `${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})`,
632
+ )
633
+ }
467
634
  throw new Error(
468
635
  type === 'validation'
469
636
  ? `${row.id}: the case's input does not match the endpoint's input schema; correct its fixture (${text})`
470
637
  : `${row.id}: the handler refused the case's input (400 ${
471
638
  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})`,
639
+ }); 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
640
  )
474
641
  }
475
642
  return { status: response.status, text }
476
643
  }
477
644
 
478
645
  /**
479
- * Two scopes of `dimension`: rows of the table that owns it when one does, with `seed`, otherwise two fresh scope
480
- * values. Each row `input` names in the object (`rows`) is seeded in each scope's row.
646
+ * Two scopes of `dimension`: rows of the table that owns it when one does, with `seed`, otherwise two scope values;
647
+ * each fresh, or the known values of a field that admits a fixed set (`knownScopes`). Each row `named` (`rows`) is
648
+ * seeded in each scope's object.
481
649
  */
482
650
  const scopesOf = async (
483
651
  action: string,
484
652
  dimension: string,
485
653
  field: SchemaShape | undefined,
486
654
  seed: Seed,
487
- input: Readonly<Record<string, unknown>>,
655
+ named: readonly RowField[],
656
+ pinning: Pinning,
488
657
  ): Promise<Scopes> => {
489
- const named = rowFields(input)
490
658
  const owner = ownerOf(dimension)
491
659
  if (named.length > 0 && owner === undefined) {
492
660
  throw new Error(`no table owns ${dimension}, so the kit seeds no ${named.map((row) => row.table).join(', ')} row in one`)
493
661
  }
662
+ const scopes = knownScopes(dimension, field)
494
663
  if (owner === undefined) {
495
- const own = freshValue(dimension, 'own', field)
496
- const other = freshValue(dimension, 'other', field)
664
+ const own = scopes[dimension]?.own ?? freshValue(dimension, 'own', field)
665
+ const other = scopes[dimension]?.other ?? freshValue(dimension, 'other', field)
497
666
  return {
498
667
  own: { target: own, grants: [{ action, scope: { type: dimension, value: own } }], chain: [{ type: dimension, value: own }], rows: {} },
499
668
  other: {
500
669
  target: other,
501
670
  grants: [{ action, scope: { type: dimension, value: other } }],
502
- values: [other],
671
+ values: [shownValue(other, scopes)],
503
672
  chain: [{ type: dimension, value: other }],
504
673
  rows: {},
505
674
  },
506
675
  }
507
676
  }
508
- const worlds = await postgres.seedWorlds(tables, owner, seed)
509
- const own = await rowsIn(worlds.own, named)
510
- const other = await rowsIn(worlds.other, named)
677
+ const worlds = pinned(await postgres.seedWorlds(tables, owner, seed, pinning.pins, scopes), pinning, scopes)
678
+ // A row under a stored scope value outlives the worlds' removal, so the case removes it itself.
679
+ const removals = Object.keys(scopes).length > 0 ? pinning.removals : []
680
+ const own = await rowsIn(worlds.own.chain, named, removals)
681
+ const other = await rowsIn(worlds.other.chain, named, removals)
511
682
  return {
512
683
  own: {
513
684
  target: worlds.own.key,
@@ -518,27 +689,34 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
518
689
  other: {
519
690
  target: worlds.other.key,
520
691
  grants: [{ action, scope: { type: worlds.dimension, value: worlds.other.scope } }],
521
- values: [...worldValues(worlds, 'other'), ...other.values],
692
+ values: [...worldValues(worlds, 'other', scopes), ...other.values],
522
693
  chain: worlds.other.chain,
523
694
  rows: other.rows,
524
695
  },
525
696
  }
526
697
  }
527
698
 
528
- /** One row of each named table seeded in `object`: its key by input field, and every key and marker it holds. */
529
- const rowsIn = async (object: WorldRow, named: ReturnType<typeof rowFields>) => {
699
+ /**
700
+ * One row of each named table seeded in the object `chain` starts at: its key by input field, and every key and marker
701
+ * it holds. Each row's removal goes to `removals`.
702
+ */
703
+ const rowsIn = async (chain: Chain, named: readonly RowField[], removals: (() => Promise<void>)[]) => {
530
704
  const rows: Record<string, string> = {}
531
705
  const values: string[] = []
532
706
  for (const { field, table } of named) {
533
- const seeded = await postgres.seedUnder(tables, table, object)
707
+ const seeded = await postgres.seedUnder(tables, table, { chain })
708
+ removals.push(seeded.remove)
534
709
  rows[field] = seeded.key
535
710
  values.push(seeded.key, ...seeded.markers)
536
711
  }
537
712
  return { rows, values }
538
713
  }
539
714
 
540
- /** For a list of `dimension`: one row in each scope of every table listed by it; each caller holds every scope of its side. */
541
- const listScopesOf = async (action: string, dimension: string): Promise<Scopes> => {
715
+ /**
716
+ * For a list of `dimension`: one row in each scope of every table listed by it, and of each table `named` (`rows`),
717
+ * whose key goes in its field; each caller holds every scope of its side.
718
+ */
719
+ const listScopesOf = async (action: string, dimension: string, named: readonly RowField[], pinning: Pinning): Promise<Scopes> => {
542
720
  const own: Grant[] = []
543
721
  const other: Grant[] = []
544
722
  const values: string[] = []
@@ -547,39 +725,86 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
547
725
  const worlds = await postgres.seedWorlds(tables, name)
548
726
  own.push({ action, scope: { type: dimension, value: worlds.own.scope } })
549
727
  other.push({ action, scope: { type: dimension, value: worlds.other.scope } })
550
- values.push(...worldValues(worlds, 'other'))
728
+ values.push(...worldValues(worlds, 'other', {}))
551
729
  }
552
730
  }
553
731
  if (own.length === 0) {
554
- return scopesOf(action, dimension, undefined, {}, {})
732
+ return scopesOf(action, dimension, undefined, {}, named, pinning)
733
+ }
734
+ const listed = await listedRows(action, dimension, named)
735
+ return {
736
+ own: { target: '', grants: [...own, ...listed.own.grants], chain: [], rows: listed.own.rows },
737
+ other: { target: '', grants: [...other, ...listed.other.grants], values: [...values, ...listed.values], chain: [], rows: listed.other.rows },
555
738
  }
556
- return { own: { target: '', grants: own, chain: [], rows: {} }, other: { target: '', grants: other, values, chain: [], rows: {} } }
739
+ }
740
+
741
+ /**
742
+ * One row of each table `named` (`rows`) in each of two scopes of `dimension`, which lists it: the grants of `action`
743
+ * that reach it, its key by input field, and every value of the other scope's rows.
744
+ */
745
+ const listedRows = async (action: string, dimension: string, named: readonly RowField[]) => {
746
+ const ownGrants: Grant[] = []
747
+ const otherGrants: Grant[] = []
748
+ const ownRows: Record<string, string> = {}
749
+ const otherRows: Record<string, string> = {}
750
+ const values: string[] = []
751
+ for (const { field, table } of named) {
752
+ if (listDimensionOf(table) !== dimension) {
753
+ throw new Error(`a list of ${dimension} reaches no ${table} row, so the kit seeds none for ${field}`)
754
+ }
755
+ const worlds = await postgres.seedWorlds(tables, table)
756
+ ownGrants.push({ action, scope: { type: dimension, value: worlds.own.scope } })
757
+ otherGrants.push({ action, scope: { type: dimension, value: worlds.other.scope } })
758
+ ownRows[field] = worlds.own.key
759
+ otherRows[field] = worlds.other.key
760
+ values.push(...worldValues(worlds, 'other', {}))
761
+ }
762
+ return { own: { grants: ownGrants, rows: ownRows }, other: { grants: otherGrants, rows: otherRows }, values }
557
763
  }
558
764
 
559
765
  /**
560
766
  * For a report `in` `dimension`: one row in each scope of every table that lies in it, the table that owns it with
561
767
  * `seed`. Each side's targets are its rows' values of `dimension`, and each caller holds all of them.
562
768
  */
563
- const inScopesOf = async (action: string, dimension: string, field: SchemaShape | undefined, seed: Seed) => {
769
+ const inScopesOf = async (
770
+ action: string,
771
+ dimension: string,
772
+ field: SchemaShape | undefined,
773
+ seed: Seed,
774
+ named: readonly RowField[],
775
+ pinning: Pinning,
776
+ ) => {
564
777
  const own: InTarget[] = []
565
778
  const other: InTarget[] = []
566
779
  const values: string[] = []
567
- for (const name of tableNames) {
780
+ const scopes = knownScopes(dimension, field)
781
+ const unpinned = { pins: {}, removals: pinning.removals }
782
+ // The owner first: a row of a known value another table's seed inserted would pass for a stored one, which takes no seed.
783
+ const owner = ownerOf(dimension)
784
+ for (const name of [...(owner === undefined ? [] : [owner]), ...tableNames.filter((candidate) => candidate !== owner)]) {
568
785
  const mode = policies[name]?.scope.mode
569
786
  if (mode !== 'dimension' && mode !== 'child') continue
570
- const worlds = await postgres.seedWorlds(tables, name, name === ownerOf(dimension) ? seed : {})
787
+ const owned = name === owner
788
+ const worlds = owned
789
+ ? pinned(await postgres.seedWorlds(tables, name, seed, pinning.pins, scopes), pinning, scopes)
790
+ : pinned(await postgres.seedWorlds(tables, name, {}, {}, scopes), unpinned, scopes)
571
791
  const ownAt = worlds.own.chain.findIndex((link) => link.type === dimension)
572
792
  const otherAt = worlds.other.chain.findIndex((link) => link.type === dimension)
573
793
  const ownValue = worlds.own.chain[ownAt]?.value
574
794
  const otherValue = worlds.other.chain[otherAt]?.value
575
795
  if (ownValue !== undefined && otherValue !== undefined) {
576
- own.push({ target: ownValue, chain: worlds.own.chain.slice(ownAt) })
577
- other.push({ target: otherValue, chain: worlds.other.chain.slice(otherAt) })
578
- values.push(...worldValues(worlds, 'other'))
796
+ const ownChain = worlds.own.chain.slice(ownAt)
797
+ const otherChain = worlds.other.chain.slice(otherAt)
798
+ const removals = Object.keys(scopes).length > 0 ? pinning.removals : []
799
+ const ownRows = await rowsIn(ownChain, named, removals)
800
+ const otherRows = await rowsIn(otherChain, named, removals)
801
+ own.push({ target: ownValue, chain: ownChain, rows: ownRows.rows })
802
+ other.push({ target: otherValue, chain: otherChain, rows: otherRows.rows })
803
+ values.push(...worldValues(worlds, 'other', scopes), ...otherRows.values)
579
804
  }
580
805
  }
581
806
  if (own.length === 0) {
582
- const scopes = await scopesOf(action, dimension, field, seed, {})
807
+ const scopes = await scopesOf(action, dimension, field, seed, named, pinning)
583
808
  return { own: [scopes.own], other: [scopes.other], values: scopes.other.values }
584
809
  }
585
810
  return { own, other, values }
@@ -702,6 +927,7 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
702
927
  mount: string,
703
928
  seed: Seed,
704
929
  input: Readonly<Record<string, unknown>>,
930
+ pinning: Pinning,
705
931
  ): Promise<{ readonly fetch: RpcFetch; readonly rows: Readonly<Record<string, string>> }> => {
706
932
  const access = row.access
707
933
  if (access.form !== 'on') {
@@ -711,7 +937,7 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
711
937
  if (owner === undefined) {
712
938
  throw new Error(`${row.id}: no table owns ${access.dimension}, so no link can be bound to one`)
713
939
  }
714
- const { own } = await postgres.seedWorlds(tables, owner, seed)
940
+ const { own } = pinned(await postgres.seedWorlds(tables, owner, seed, pinning.pins), pinning, {})
715
941
  const holder = kit.testCaller([{ action: row.action, scope: { type: access.dimension, value: own.key } }], {
716
942
  kind: 'link',
717
943
  link: { mount, chain: own.chain },
@@ -721,150 +947,215 @@ export function endpointAccessKit<DB, P>(app: ContractImplementation<AnyContract
721
947
  headers.set('Authorization', `Bearer ${holder.key ?? ''}`)
722
948
  return kit.fetch(request, { ...init, headers })
723
949
  }
724
- return { fetch, rows: (await rowsIn(own, rowFields(input))).rows }
950
+ return { fetch, rows: (await rowsIn(own.chain, rowFields(input), [])).rows }
725
951
  }
726
952
 
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)
953
+ // The cases of one call: `removals` takes the removal of the application rows it seeds, which `drained` runs once
954
+ // the call and the runs it kicked are over. A list per call, so a concurrent case never removes the rows another
955
+ // was given; the generated cases run one after another, since a row a required foreign key needed is shared.
956
+ const accessKitOf = (removals: (() => Promise<void>)[]): EndpointAccessKit => {
957
+ /** The pins of `endpoint`, whose seeded rows this call removes once it is over. */
958
+ const pinningOf = (endpoint: string): Pinning => ({ pins: options.pins?.[endpoint] ?? {}, removals })
959
+ /** No pins, and the removals of this call: for a scope a case seeds beside its endpoint's own. */
960
+ const unpinned: Pinning = { pins: {}, removals }
961
+
962
+ /** One row of each application table `appRows` names, for this call only. */
963
+ const seedAppRows = async (appRows: AppRows): Promise<void> => {
964
+ if (Object.keys(appRows).length === 0) return
965
+ removals.push((await postgres.seedApplicationRows(tables, appRows)).remove)
966
+ }
967
+
968
+ return {
969
+ async denied(endpoint, input, seed = {}) {
970
+ const row = endpointOf(endpoint)
971
+ const { action, access } = row
972
+ if (access.form !== 'on' && access.form !== 'in') {
973
+ throw new Error(`${endpoint} has the access form ${access.form}; only on and in name an object or a scope value`)
750
974
  }
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))
975
+ const scopes = await scopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, rowFields(input), pinningOf(endpoint))
976
+ const asked = addressing(input, access.from, scopes.other)
977
+ const { status } = await ask(row, holding(row, input, scopes.own.grants, scopes.own.chain), asked, scopes.own.chain)
978
+ return { status }
979
+ },
980
+ async leaked(endpoint, input, seed = {}, appRows = {}) {
981
+ const row = endpointOf(endpoint)
982
+ const { action, access } = row
983
+ if (access.form === 'in') {
984
+ await seedAppRows(appRows)
985
+ const scopes = await inScopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, rowFields(input), pinningOf(endpoint))
986
+ const grants = (targets: readonly InTarget[]): Grant[] =>
987
+ targets.flatMap(({ target, chain }) => holding(row, input, [{ action, scope: { type: access.dimension, value: target } }], chain))
988
+ const marks: string[] = []
989
+ for (const side of scopes.other) {
990
+ const answer = await ask(row, grants(scopes.other), addressing(input, access.from, side), side.chain, 'declared')
991
+ marks.push(...answer.marks)
992
+ }
993
+ const answers = []
994
+ for (const side of scopes.own) {
995
+ answers.push(await ask(row, grants(scopes.own), addressing(input, access.from, side), side.chain))
996
+ }
997
+ return leakOutcome(answers, [...scopes.values, ...marks])
754
998
  }
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 })
999
+ if (access.form !== 'on' && access.form !== 'over') {
1000
+ throw new Error(`${endpoint} has the access form ${access.form}; only on, in and over answer with rows of a scope`)
1001
+ }
1002
+ await seedAppRows(appRows)
1003
+ const scopes = access.form === 'on'
1004
+ ? await scopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, rowFields(input), pinningOf(endpoint))
1005
+ : await listScopesOf(action, access.dimension, rowFields(input), unpinned)
1006
+ const from = access.form === 'on' ? access.from : null
1007
+ // The other scope asks first, to fill whatever a handler keeps between requests; its pins differ from the own
1008
+ // scope's, so a refusal the fixtures declare is its answer too. The own scope's answer is the one checked.
1009
+ const other = await ask(
1010
+ row,
1011
+ holding(row, input, scopes.other.grants, scopes.other.chain),
1012
+ addressing(input, from, scopes.other),
1013
+ scopes.other.chain,
1014
+ 'declared',
1015
+ )
1016
+ const answer = await ask(
1017
+ row,
1018
+ holding(row, input, scopes.own.grants, scopes.own.chain),
1019
+ addressing(input, from, scopes.own),
1020
+ scopes.own.chain,
1021
+ )
1022
+ return leakOutcome([answer], [...scopes.other.values, ...other.marks])
1023
+ },
1024
+ async own(endpoint, input, seed = {}, appRows = {}) {
1025
+ const row = endpointOf(endpoint)
1026
+ const { action, access } = row
1027
+ if (access.form !== 'on') {
1028
+ throw new Error(`${endpoint} has the access form ${access.form}; only on addresses an object of its own`)
1029
+ }
1030
+ await seedAppRows(appRows)
1031
+ if (row.link !== null) {
1032
+ const holder = await linkHolder(row, row.link, seed, input, pinningOf(endpoint))
1033
+ const { status } = await askAs(row, holder.fetch, { ...input, ...holder.rows }, 'declared')
1034
+ return { status }
1035
+ }
1036
+ const scopes = await scopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, rowFields(input), pinningOf(endpoint))
1037
+ const { status } = await ask(
1038
+ row,
1039
+ holding(row, input, scopes.own.grants, scopes.own.chain),
1040
+ addressing(input, access.from, scopes.own),
1041
+ scopes.own.chain,
1042
+ 'declared',
1043
+ )
787
1044
  return { status }
1045
+ },
1046
+ async scoped(endpoint, input) {
1047
+ const row = globalEndpointOf(endpoint)
1048
+ const dimension = row.access.form === 'creates' ? row.access.dimension : scopeTypeOf(kit.artifact.dimensions)
1049
+ const { status } = await ask(row, [{ action: row.action, scope: { type: dimension, value: freshValue(dimension, 'own', undefined) } }], input, [])
1050
+ return { status }
1051
+ },
1052
+ async anyone(endpoint, input) {
1053
+ const row = kit.artifact.endpoints.find((candidate) => candidate.id === endpoint)
1054
+ if (row?.kind !== 'public') {
1055
+ throw new Error(`${endpoint} is not a public procedure of the contract`)
1056
+ }
1057
+ const response = await kit.fetch(row.path, {
1058
+ method: row.method,
1059
+ headers: { 'Content-Type': 'application/json', Origin: kit.origin, 'Sec-Fetch-Site': 'same-origin' },
1060
+ body: JSON.stringify(input),
1061
+ })
1062
+ const status = response.status
1063
+ const challenged = status === 400 && errorType(await response.text()) === 'challenge_failed'
1064
+ return status >= 500 || status === 401 || status === 403 || challenged ? { answered: false, status } : { answered: true }
1065
+ },
1066
+ async global(endpoint, input) {
1067
+ const row = globalEndpointOf(endpoint)
1068
+ const { status } = await askAs(row, callerFor(row, [{ action: row.action }]).fetch, input)
1069
+ // Neither form refuses with 404, so a 404 is the handler's own answer (a row the sampled input names is missing).
1070
+ return status >= 500 || status === 401 || status === 403 ? { answered: false, status } : { answered: true }
1071
+ },
1072
+ async capability(endpoint, capability, input, seed = {}) {
1073
+ const { requirement, capabilities } = capabilitiesEndpointOf(endpoint)
1074
+ const named = capabilities.get(capability)
1075
+ if (named === undefined) {
1076
+ throw new Error(`${endpoint} has no capability '${capability}' (capabilities: ${[...capabilities.keys()].join(', ')})`)
1077
+ }
1078
+ const { access } = named
1079
+ const ruledOutBy = deniedCaseRuledOutBy(requirement.capabilities, capability, kit.artifact.dimensions)
1080
+ if (ruledOutBy !== undefined) {
1081
+ throw new Error(
1082
+ `${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`,
1083
+ )
1084
+ }
1085
+ const fields = rowFields(input)
1086
+ for (const { field, capability: placed } of fields) {
1087
+ if (placed === null || !capabilities.has(placed)) {
1088
+ throw new Error(`${endpoint}: ${field} names a row in the scope of no capability of it, so the kit does not know where to seed it`)
1089
+ }
1090
+ }
1091
+ const rowsOf = (name: string): RowField[] => fields.filter((field) => field.capability === name)
1092
+ const grants: Grant[] = []
1093
+ let asked = input
1094
+ // The named one first: a known value another one's seed inserted would pass for a stored row, which takes no seed.
1095
+ if (access.form === 'on' || access.form === 'in') {
1096
+ const scopes = await scopesOf(named.action, access.dimension, fieldOf(named.input, access.from), seed, rowsOf(capability), pinningOf(endpoint))
1097
+ asked = addressing(asked, access.from, scopes.other)
1098
+ grants.push(...scopes.own.grants)
1099
+ }
1100
+ for (const [name, other] of capabilities) {
1101
+ if (name === capability) continue
1102
+ // Each other one in a scope of its own, apart from the named one's: a global grant would also meet the named
1103
+ // capability when both share an action. An `over` one lists from any value it is held in, so a fresh uuid does,
1104
+ // a valid key whether the dimension's is text or uuid; it also holds the scope of each row it names.
1105
+ if (other.access.form === 'over') {
1106
+ const listed = await listedRows(other.action, other.access.dimension, rowsOf(name))
1107
+ grants.push({ action: other.action, scope: { type: other.access.dimension, value: crypto.randomUUID() } }, ...listed.own.grants)
1108
+ asked = { ...asked, ...listed.own.rows }
1109
+ } else if (other.access.form === 'on' || other.access.form === 'in') {
1110
+ const { own } = await scopesOf(other.action, other.access.dimension, fieldOf(other.input, other.access.from), {}, rowsOf(name), unpinned)
1111
+ asked = addressing(asked, other.access.from, own)
1112
+ grants.push(...own.grants)
1113
+ }
1114
+ }
1115
+ if (access.form === 'over') {
1116
+ // The caller holds the named action nowhere it lists, so its rows lie in a scope of their own.
1117
+ asked = { ...asked, ...(await listedRows(named.action, access.dimension, rowsOf(capability))).other.rows }
1118
+ }
1119
+ const { status } = await askAs(named, callerFor(named, grants).fetch, asked)
1120
+ return { status }
1121
+ },
1122
+ }
1123
+ }
1124
+ // Each case waits for the runs its requests kicked, so the suite's teardown never closes the database under one, and
1125
+ // only then removes its application rows, which those runs may still read. Every step runs whatever failed before
1126
+ // it, and the case's own error is thrown first.
1127
+ const drained =
1128
+ <A extends readonly unknown[], R>(method: (kit: EndpointAccessKit) => (...args: A) => Promise<R>) => async (...args: A): Promise<R> => {
1129
+ const removals: (() => Promise<void>)[] = []
1130
+ let outcome: { readonly ok: true; readonly value: R } | { readonly ok: false; readonly error: unknown }
1131
+ try {
1132
+ outcome = { ok: true, value: await method(accessKitOf(removals))(...args) }
1133
+ } catch (error) {
1134
+ outcome = { ok: false, error }
788
1135
  }
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)
1136
+ const failures: unknown[] = []
1137
+ for (const step of [() => kit.drain(), ...removals]) {
1138
+ try {
1139
+ await step()
1140
+ } catch (error) {
1141
+ failures.push(error)
841
1142
  }
842
1143
  }
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)
1144
+ if (!outcome.ok) {
1145
+ if (failures.length === 0) throw outcome.error
1146
+ throw new AggregateError([outcome.error, ...failures], 'the case failed, and so did its cleanup')
848
1147
  }
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()
1148
+ if (failures.length === 1) throw failures[0]
1149
+ if (failures.length > 1) throw new AggregateError(failures, 'the cleanup of the case failed')
1150
+ return outcome.value
859
1151
  }
860
- }
861
1152
  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),
1153
+ denied: drained((cases) => cases.denied),
1154
+ leaked: drained((cases) => cases.leaked),
1155
+ own: drained((cases) => cases.own),
1156
+ scoped: drained((cases) => cases.scoped),
1157
+ global: drained((cases) => cases.global),
1158
+ anyone: drained((cases) => cases.anyone),
1159
+ capability: drained((cases) => cases.capability),
869
1160
  })
870
1161
  }