@fabrika/app 0.9.0-dev.13 → 0.9.0-dev.15

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 (89) hide show
  1. package/package.json +14 -9
  2. package/skill/SKILL.md +3 -2
  3. package/skill/references/app-setup.md +17 -9
  4. package/skill/references/endpoint.md +15 -2
  5. package/skill/references/errors.md +7 -6
  6. package/skill/references/jobs.md +10 -0
  7. package/skill/references/relations.md +145 -21
  8. package/skill/references/table-and-migration.md +4 -1
  9. package/skill/references/webhooks-links-connectors.md +2 -1
  10. package/src/build-contract-child.ts +16 -0
  11. package/src/build.ts +48 -2
  12. package/src/bun.ts +10 -0
  13. package/src/client/contract.ts +6 -4
  14. package/src/cloudflare/application.ts +3 -0
  15. package/src/contract/artifact-schema.ts +367 -299
  16. package/src/contract/attachment.ts +4 -3
  17. package/src/contract/build.ts +76 -18
  18. package/src/contract/compile.ts +3 -2
  19. package/src/contract/context.ts +2 -3
  20. package/src/contract/define.ts +19 -6
  21. package/src/contract/group.ts +18 -8
  22. package/src/contract/index.ts +1 -1
  23. package/src/contract/kit.ts +4 -3
  24. package/src/contract/problems.ts +4 -0
  25. package/src/contract/schema-shape.ts +14 -2
  26. package/src/contract/token.ts +4 -3
  27. package/src/disk-assets.ts +15 -3
  28. package/src/from-row.ts +12 -6
  29. package/src/implement/approved.ts +57 -0
  30. package/src/implement/attachment.ts +2 -1
  31. package/src/implement/boot.ts +118 -17
  32. package/src/implement/capability.ts +82 -12
  33. package/src/implement/dispatch.ts +265 -45
  34. package/src/implement/egress.ts +410 -9
  35. package/src/implement/faults.ts +1 -0
  36. package/src/implement/implement.ts +23 -3
  37. package/src/implement/invocation.ts +10 -9
  38. package/src/implement/project.ts +3 -1
  39. package/src/implement/tokens.ts +3 -2
  40. package/src/implement/types.ts +33 -10
  41. package/src/implement/webhook.ts +8 -0
  42. package/src/jobs/runner.ts +7 -2
  43. package/src/react/hooks.ts +12 -11
  44. package/src/react/provider.tsx +2 -1
  45. package/src/react/types.ts +2 -2
  46. package/src/schema/builder.ts +146 -0
  47. package/src/schema/data-schema.ts +365 -0
  48. package/src/schema/index.ts +18 -0
  49. package/src/schema/replay.ts +623 -0
  50. package/src/source-map-path.ts +21 -0
  51. package/src/testing/caller.ts +20 -9
  52. package/src/testing/kit.ts +3 -3
  53. package/src/testing/membership.ts +9 -5
  54. package/types/src/build-contract-child.d.ts +1 -0
  55. package/types/src/build.d.ts +16 -1
  56. package/types/src/client/contract.d.ts +3 -4
  57. package/types/src/cloudflare/application.d.ts +2 -0
  58. package/types/src/contract/artifact-schema.d.ts +8 -0
  59. package/types/src/contract/attachment.d.ts +3 -2
  60. package/types/src/contract/context.d.ts +2 -3
  61. package/types/src/contract/define.d.ts +16 -6
  62. package/types/src/contract/group.d.ts +14 -7
  63. package/types/src/contract/index.d.ts +1 -1
  64. package/types/src/contract/kit.d.ts +4 -5
  65. package/types/src/contract/problems.d.ts +1 -0
  66. package/types/src/contract/schema-shape.d.ts +3 -2
  67. package/types/src/contract/token.d.ts +3 -3
  68. package/types/src/from-row.d.ts +9 -5
  69. package/types/src/implement/approved.d.ts +11 -0
  70. package/types/src/implement/boot.d.ts +12 -0
  71. package/types/src/implement/capability.d.ts +14 -5
  72. package/types/src/implement/dispatch.d.ts +9 -1
  73. package/types/src/implement/egress.d.ts +36 -1
  74. package/types/src/implement/faults.d.ts +1 -0
  75. package/types/src/implement/implement.d.ts +19 -3
  76. package/types/src/implement/invocation.d.ts +3 -3
  77. package/types/src/implement/project.d.ts +2 -1
  78. package/types/src/implement/types.d.ts +17 -8
  79. package/types/src/jobs/runner.d.ts +3 -0
  80. package/types/src/react/hooks.d.ts +4 -5
  81. package/types/src/react/types.d.ts +2 -2
  82. package/types/src/schema/builder.d.ts +45 -0
  83. package/types/src/schema/data-schema.d.ts +124 -0
  84. package/types/src/schema/index.d.ts +3 -0
  85. package/types/src/schema/replay.d.ts +27 -0
  86. package/types/src/source-map-path.d.ts +4 -0
  87. package/types/src/testing/caller.d.ts +6 -1
  88. package/types/src/testing/kit.d.ts +2 -3
  89. package/types/src/testing/membership.d.ts +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/app",
3
- "version": "0.9.0-dev.13",
3
+ "version": "0.9.0-dev.15",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -38,6 +38,11 @@
38
38
  "types": "./types/src/contract/index.d.ts",
39
39
  "default": "./src/contract/index.ts"
40
40
  },
41
+ "./schema": {
42
+ "bun": "./src/schema/index.ts",
43
+ "types": "./types/src/schema/index.d.ts",
44
+ "default": "./src/schema/index.ts"
45
+ },
41
46
  "./client": {
42
47
  "bun": "./src/client/index.ts",
43
48
  "types": "./types/src/client/index.d.ts",
@@ -109,14 +114,14 @@
109
114
  "test": "bun test --path-ignore-patterns='src/react/**' && bun test --isolate src/react"
110
115
  },
111
116
  "dependencies": {
112
- "@fabrika/auth": "0.9.0-dev.13",
113
- "@fabrika/auth-core": "0.9.0-dev.13",
114
- "@fabrika/db": "0.9.0-dev.13",
115
- "@fabrika/email": "0.9.0-dev.13",
116
- "@fabrika/jwks": "0.9.0-dev.13",
117
- "@fabrika/platform": "0.9.0-dev.13",
118
- "@fabrika/platform-node": "0.9.0-dev.13",
119
- "@fabrika/proxy-core": "0.9.0-dev.13",
117
+ "@fabrika/auth": "0.9.0-dev.15",
118
+ "@fabrika/auth-core": "0.9.0-dev.15",
119
+ "@fabrika/db": "0.9.0-dev.15",
120
+ "@fabrika/email": "0.9.0-dev.15",
121
+ "@fabrika/jwks": "0.9.0-dev.15",
122
+ "@fabrika/platform": "0.9.0-dev.15",
123
+ "@fabrika/platform-node": "0.9.0-dev.15",
124
+ "@fabrika/proxy-core": "0.9.0-dev.15",
120
125
  "altcha-lib": "2.6.0",
121
126
  "jose": "^5.9.0"
122
127
  },
package/skill/SKILL.md CHANGED
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: fabrika-app
3
- version: 0.9.0-dev.13
3
+ version: 0.9.0-dev.15
4
4
  description: >
5
5
  How to write and change a Fabrika application: src/vocabulary.ts, db/migrations/, src/db/tables.ts, the
6
6
  slices' endpoints.ts with their handlers, fabrika.contract.ts, jobs, files, webhooks, share links, connectors
@@ -232,6 +232,7 @@ the access check. `references/spa.md` shows the stack.
232
232
  | e-mail (a cron job only) | `mailer: 'installation'` | `ctx.mail.send` |
233
233
  | a file from a public procedure | `file('<kind>')` input, `admission` with `bytesPerHour` | a reference the handler writes into a file column |
234
234
  | an outside HTTPS API | `egress: ['https://api.example.com']` | `fetch` to those (`https://*.<domain>`: one label) |
235
+ | any public website (a job) | `egress: 'public'` | `fetch` to public hosts, never the installation |
235
236
  | a signed link (unsubscribe) | `signs: ['<purpose>']` | `ctx.tokens.sign` |
236
237
  | a webhook binding | `binds: '<webhook>'` | `ctx.webhooks('<webhook>').bind` and `.unbind` |
237
238
  | a job run after the commit | `kicks: ['<job>']` | `ctx.kick('<job>')`, `ctx.kick('<job>', { at })` |
@@ -263,7 +264,7 @@ Which promise the types, the checker, boot, the runtime or the approver keeps, a
263
264
  no `package.json`. Its tests run in the platform build, so they test its logic, without a keychain or a network.
264
265
  - Never log an error object, a request, headers or the environment.
265
266
  - Never edit a generated file (`src/db/schema.generated.ts`, the generated tests, `fabrika/entry.generated.ts`,
266
- `fabrika/migrations.generated.ts`, `fabrika/connect/`) or a committed migration. Regenerate the file; write a new migration.
267
+ `fabrika/migrations.generated.ts`, `fabrika/contract.generated.ts`, `fabrika/connect/`) or a committed migration. Regenerate the file; write a new migration.
267
268
 
268
269
  ## Ask the human first
269
270
 
@@ -19,20 +19,20 @@ the SPA is added with it.
19
19
  "test": "bun test --isolate"
20
20
  },
21
21
  "dependencies": {
22
- "@fabrika/app": "0.9.0-dev.13",
23
- "@fabrika/db": "0.9.0-dev.13",
24
- "@fabrika/provider-zerops": "0.9.0-dev.13",
25
- "@fabrika/proxy-core": "0.9.0-dev.13",
26
- "@fabrika/ui": "0.9.0-dev.13",
22
+ "@fabrika/app": "0.9.0-dev.15",
23
+ "@fabrika/db": "0.9.0-dev.15",
24
+ "@fabrika/provider-zerops": "0.9.0-dev.15",
25
+ "@fabrika/proxy-core": "0.9.0-dev.15",
26
+ "@fabrika/ui": "0.9.0-dev.15",
27
27
  "kysely": "0.29.6",
28
28
  "react": "^19.0.0",
29
29
  "react-dom": "^19.0.0",
30
30
  "zod": "^3.25.76"
31
31
  },
32
32
  "devDependencies": {
33
- "@fabrika/check": "0.9.0-dev.13",
34
- "@fabrika/cli": "0.9.0-dev.13",
35
- "@fabrika/platform": "0.9.0-dev.13",
33
+ "@fabrika/check": "0.9.0-dev.15",
34
+ "@fabrika/cli": "0.9.0-dev.15",
35
+ "@fabrika/platform": "0.9.0-dev.15",
36
36
  "@happy-dom/global-registrator": "^20.11.2",
37
37
  "@types/bun": "^1.4.3",
38
38
  "@types/react": "^19.0.0",
@@ -245,6 +245,13 @@ zerops:
245
245
  - bun run build:web
246
246
  ```
247
247
 
248
+ `build.base` must be a Bun that reads the committed `bun.lock`: the build installs with `--frozen-lockfile`, and an
249
+ older Bun fails it with `Unknown lockfile version`. A `bun.lock` that Bun 1.4 creates or regenerates has
250
+ `"lockfileVersion": 2`, which needs `alpine/bun@1.4`; versions 0 and 1 build on `alpine/bun@1.3`, which is also the
251
+ base without `build.base`. Raise `build.base` to `alpine/bun@1.4` rather than regenerate the lockfile with Bun 1.3, which
252
+ resolves every dependency afresh. `fabrika app build` refuses a base that cannot read the lockfile and names the one to
253
+ use.
254
+
248
255
  The platform's build runs the tests, writes the entrypoint, runs `fabrika-check` and the type check. Its init commands
249
256
  run `fabrika db migrate`, `fabrika db codegen --verify` and `fabrika db test-isolation` before the server starts: a
250
257
  version does not go live until every generated test passes. It writes every `FABRIKA_*` variable; never set one.
@@ -428,4 +435,5 @@ await Bun.write(
428
435
  ## Ignored files
429
436
 
430
437
  `.gitignore`: `node_modules/`, `fabrika.manifest.json`, `/fabrika/entry.generated.ts`, `/dist/`, and on Cloudflare
431
- `/fabrika/assets/`, where a deploy stages the SPA's files.
438
+ `/fabrika/assets/`, where a deploy stages the SPA's files, and `/fabrika/contract.generated.ts`, which every build
439
+ rewrites from the contract.
@@ -28,11 +28,18 @@ export const WorkloadRow = z.strictObject({
28
28
 
29
29
  - `z` comes from `zod/v4`. Objects are `z.strictObject`, never `z.object`. No `transform`, `refine`, `pipe`,
30
30
  `preprocess`, `passthrough`, `lazy` or `custom`: the shell is read without running it.
31
+ - A large contract (hundreds of endpoints) imports `z` from `@fabrika/app/schema` instead. It is the same subset with the
32
+ same names and types, and the same artifact. It holds each schema as data and builds the zod only when it validates,
33
+ so the runtime does not hold the zod of every endpoint at once. Such a schema keeps `.shape`, `.extend`, `.pick`, `.omit`,
34
+ `.partial` (objects), `.options`, `.enum`, `.exclude`, `.extract` (enums), `.parse` and `.safeParse`. For anything
35
+ else of zod's API, call `zodOf(schema)` from `@fabrika/app/schema`. `@fabrika/app/schema`'s factories take a
36
+ zod schema as a child, but `zod/v4`'s do not take a schema held as data. Wrap one with the builder that made it:
37
+ `z.array(Row)`, where this `z` is the one that built `Row`.
31
38
  - `src/schemas.ts` holds what several slices, or a slice and the SPA, share, as literal consts only. A slice declares
32
39
  its own schemas in its `endpoints.ts` (`Task`, `NewTask` in `SKILL.md`), and may declare other consts there too.
33
40
  - A pure function both the server and the SPA run (a template fill, a label) lives in `src/shared/<name>.ts`, once: a
34
41
  handler and a `web/` module import the same function, so the preview and the e-mail cannot drift. A shared module
35
- imports only `zod/v4` and other modules of `src/shared/` (`shared-import`); no slice, no `src/db/`, no `@fabrika/*`,
42
+ imports only `zod/v4`, `@fabrika/app/schema` and other modules of `src/shared/` (`shared-import`); no slice, no `src/db/`, no `@fabrika/*`,
36
43
  no global object, no environment.
37
44
  - `z.iso.datetime()` takes UTC (`…Z`) only; `z.iso.date()` is `YYYY-MM-DD`.
38
45
  - Optional or nullable: on a create, a field the caller may leave out is `.optional()`, never a required
@@ -671,6 +678,11 @@ On Cloudflare a procedure waits for its outside call inside the object's transac
671
678
  with it (`SKILL.md`). A mutation records a row and kicks a job, which declares the `egress` and calls outside
672
679
  `ctx.transaction` (`references/jobs.md`).
673
680
 
681
+ A cron job that calls hosts nobody knows when the contract is written (the websites its operators enter: a crawler, an
682
+ auditor, a link checker) declares `egress: 'public'` instead of a list (`references/jobs.md`). Only a cron job may: a
683
+ procedure, a mutation and a webhook name their origins. Never keep `fetch` from before boot or open sockets to get past
684
+ the list; that is hidden reach.
685
+
674
686
  ## Links to your own procedures: `ctx.url`
675
687
 
676
688
  `ctx.url('<endpoint id>', { input?, query? })` builds an absolute URL of one of the application's own procedures, on
@@ -698,7 +710,8 @@ containing it, that declares `members`: a task endpoint reads its org's. A dimen
698
710
  `member.principalId` and `member.label`, never a label from the input.
699
711
  - `disabled` is a person an operator disabled in IAM: still a member, but unable to sign in. Refuse to assign one
700
712
  (`assign` in `SKILL.md`), and leave them out of a picker.
701
- - The approver sees each endpoint that reads a directory ("looks up one member of `org`"): a new one widens.
713
+ - The approver sees each endpoint that can read a directory ("can look up one member of `org`"): the first one of an
714
+ action and its callers widens; another endpoint of the same action and callers is shown as unchanged.
702
715
  - With the directory's `members.list` action (`tasks.read` here) also `ctx.members.list()`, answering
703
716
  `{ principalId, label, roles, disabled }` per member, for an assignee picker. IAM checks that action on the org
704
717
  itself too.
@@ -31,7 +31,8 @@ The refusals agents meet most, and their fix:
31
31
  | `skipped-test` | `.skip`, `.only`, `.todo` | run the test |
32
32
  | `file-column-migration` | a file column without `REFERENCES fabrika_files (id)` or without an index it leads | both, in a new migration (`references/table-and-migration.md`) |
33
33
  | `on-conflict-index` | `insert(…, { onConflict: { columns } })` whose columns are no unique index the migrations create | a `UNIQUE` constraint or a `CREATE UNIQUE INDEX` without `WHERE` on exactly those columns |
34
- | `cross-app-fetch` | a `fetch` of an absolute URL under no origin a site declares in `egress` | `egress: ['https://…']` on the site that calls it (`references/endpoint.md`) |
34
+ | `access-view-key` | a table that names an access view has no single-column primary or unique key on its key | a `PRIMARY KEY` or `UNIQUE` on that column alone (`references/relations.md`) |
35
+ | `cross-app-fetch` | a `fetch` of an absolute URL under no origin a site declares in `egress`, or one a job's `egress: 'public'` refuses (an IP address, `localhost`) | `egress: ['https://…']` on the site that calls it (`references/endpoint.md`) |
35
36
  | `url-endpoint` | `ctx.url('<id>')` names no procedure of the contract | the endpoint id `<mount>.<group>.<procedure>` |
36
37
  | `cloudflare-scan` | on Cloudflare, a file kind with `scan: true` | the kind without `scan`, and no public procedure that takes its files |
37
38
  | `cloudflare-job-segment` | on Cloudflare, a job whose `limits.timeoutMs` exceeds one 14-minute segment | at most 14 minutes: claim a bounded batch per run, and the next run takes the rest |
@@ -112,11 +113,11 @@ message. The refusal's own message names the place (`'sqlite_master' at line 2`,
112
113
  (`references/tests.md`). The codes
113
114
  you meet most:
114
115
 
115
- | Code | Means |
116
- | -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
117
- | `query_refused` | the data layer refused a statement or an operation: `undeclared_reach`, `sql_read_only`, `unknown_column`, `read_only`, `sql_outside_transaction`, `sql_scope`, `sql_name` …; the reason's text names the rule |
118
- | `capability_refused` | a capability of another kind, dimension or action than the call takes (`wrong_capability`, `wrong_action`, `out_of_reach`), or one kept past its request (`ended`, `foreign_work`) |
119
- | `handler_failed` | your handler threw something else; the log has no more: the Operations issue has the stack, `app dev` prints it |
116
+ | Code | Means |
117
+ | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
118
+ | `query_refused` | the data layer refused a statement or an operation: `undeclared_reach`, `sql_read_only`, `unknown_column`, `read_only`, `sql_outside_transaction`, `sql_scope`, `sql_name` …; the reason's text names the rule |
119
+ | `capability_refused` | a capability of another kind, dimension or action than the call takes (`wrong_capability`, `wrong_action`, `out_of_reach`), one kept past its request (`ended`, `foreign_work`), or a `fetch` its `egress` refuses (`undeclared_egress`, `refused_egress`, `oversized_egress`, `encoded_egress`) |
120
+ | `handler_failed` | your handler threw something else; the log has no more: the Operations issue has the stack, `app dev` prints it |
120
121
 
121
122
  With an Operations DSN the same 500 is a `RequestFailed` issue in Operations. Its event also carries what your handler
122
123
  threw: the error's type, its message, its stack and its `cause` chain. Read the stack there, not in the log. A crash
@@ -144,6 +144,16 @@ export const contract = app.contract((c) => ({
144
144
  - A job may also declare `kicks` (another job; the edges never form a cycle), `signs` (`ctx.tokens.sign`),
145
145
  `egress` (the HTTPS origins its `fetch` calls) and `issues` (`references/endpoint.md`). `ctx.url('<endpoint id>', …)`
146
146
  builds an absolute link to one of the application's procedures, for an e-mail.
147
+ - A job that calls the websites its operators enter (a crawler, an auditor) declares `egress: 'public'`:
148
+ `app.cron('*/5 * * * *', { actions: ['sites.read'], egress: 'public' })`. Its `fetch` reaches any public host over
149
+ HTTPS or HTTP on the default port. It is refused (`capability_refused: refused_egress`) for an IP address, a name of
150
+ one label (`localhost`, an internal service), a name under `.local`, `.internal`, `.workers.dev`, `.zerops.app` and similar, a port,
151
+ the installation's own hosts (IAM, Control, Operations, every application's domain) and, on Bun (Zerops), a name
152
+ that resolves to a private address. Every redirect is checked again: `redirect: 'manual'` gets the redirect, the default
153
+ follows at most 10. A request has 60 s, a response body at most 16 MiB (`oversized_egress`), read whole before `fetch` answers; a
154
+ compressed answer is refused (`encoded_egress`: the guard asks for `identity`); pass `ctx.signal`, or
155
+ `AbortSignal.any([ctx.signal, AbortSignal.timeout(8_000)])` for a shorter bound per page. The approver reviews it
156
+ closely, as reach to anywhere public. Keep the sites operators enter in a table the job reads.
147
157
  - `ctx.signal` aborts when the attempt ends (its timeout, a lost lease). Call `ctx.signal.throwIfAborted()` before
148
158
  each external effect and pass the signal to `fetch`, so a stale attempt starts nothing after its replacement.
149
159
  - A failed attempt names its failure in `kit.runJob`'s answer and the log: `handler_failed`, a framework failure
@@ -8,7 +8,10 @@ statement. This file is an application of its own (`tasks` with assistants); its
8
8
 
9
9
  Ask the human before you add a relation, a role's `via`, a table's `confers` or its `assign`: each lets someone reach
10
10
  more, and the approver sees each as a widening. A `when` only narrows; removing or changing one widens. They need
11
- `@fabrika/app` `0.9.0-dev.13` or later: Control refuses to publish them for an application pinned to an earlier release.
11
+ `@fabrika/app` `0.9.0-dev.13` or later, and a `relationWhen` `0.9.0-dev.14` or later: Control refuses to publish them for
12
+ an application pinned to an earlier release. A relation held inside the node of a scoped grant needs `0.9.0-dev.14`;
13
+ an earlier release holds nothing through it. A table's `access` needs `0.9.0-dev.14` or later, which Control
14
+ checks the same way.
12
15
 
13
16
  ## The vocabulary: a relation and a role's `via`
14
17
 
@@ -30,6 +33,7 @@ export const vocabulary = defineVocabulary({
30
33
  },
31
34
  relations: {
32
35
  assisting: { dimension: 'project' },
36
+ auditing: { dimension: 'org' },
33
37
  },
34
38
  roles: {
35
39
  owner: {
@@ -44,6 +48,10 @@ export const vocabulary = defineVocabulary({
44
48
  grants: [],
45
49
  via: { assisting: ['tasks.read', 'tasks.write'] },
46
50
  },
51
+ auditor: {
52
+ grants: [],
53
+ via: { auditing: ['tasks.read'] },
54
+ },
47
55
  },
48
56
  })
49
57
  ```
@@ -51,9 +59,15 @@ export const vocabulary = defineVocabulary({
51
59
  - `relations: { <name>: { dimension } }` names a relation and the dimension of the node its rows name.
52
60
  - `via: { <relation>: [<action>, …] }` on a role: a holder of the role holds those actions at each node where a source
53
61
  row names them, and nowhere else. Its `grants` still hold globally, so an assistant's are empty.
54
- - `via` is only for a global, internal role without `member`: IAM grants `assistant` application-wide (an operator,
55
- in IAM's console), and the rows say where it applies. A grant of the role in a scope value carries no relation, so
56
- the proxy refuses its holder (403). A person from outside the organization (`external: true`) holds no relation.
62
+ - `via` is for an internal role. A global grant of it (an operator gives `assistant` application-wide, in IAM's
63
+ console) holds the relation wherever the rows name its holder. A grant of it in a scope value, a membership role in
64
+ the value it is held in included, holds the relation only inside that value: a member row in another organization
65
+ reaches nothing, and a table or a reveal above the value gets nothing through it. A membership role's `via` names a
66
+ relation whose dimension is the role's own or lies inside it (`project` inside `org`), and the build refuses any
67
+ other. A person from outside the organization (`external: true`) holds no relation, and an external role takes no
68
+ `via`.
69
+ - Whoever gives a membership role with `via` holds every action of the role, its `via` actions included, at that value
70
+ through a grant; an action they hold only through a relation does not count.
57
71
  - The token says only that the role holds those actions through `assisting`. The data layer reads the source rows on
58
72
  every statement, so an inserted row grants at the next request and a deleted one stops access at the next request.
59
73
  Nothing caches it.
@@ -97,6 +111,10 @@ CREATE TABLE project_assistants (
97
111
  FOREIGN KEY (project_id, org_id) REFERENCES projects (id, org_id) ON UPDATE CASCADE ON DELETE CASCADE
98
112
  );
99
113
  CREATE INDEX project_assistants_principal ON project_assistants (principal_id, project_id);
114
+
115
+ -- An access view: the finished tasks of each organization, for whoever audits it there.
116
+ CREATE VIEW finished_tasks AS
117
+ SELECT id AS task_id, org_id FROM tasks WHERE done;
100
118
  ```
101
119
 
102
120
  - A source table is an ordinary child or dimension table with a principal column (`TEXT`, an IAM principal id), the
@@ -137,6 +155,9 @@ export const tables = defineTables(vocabulary, columns)({
137
155
  ],
138
156
  },
139
157
  },
158
+ access: {
159
+ auditing: { view: 'finished_tasks', row: 'task_id', member: 'org_id' },
160
+ },
140
161
  },
141
162
  project_assistants: {
142
163
  scope: { child: 'projects' },
@@ -231,6 +252,38 @@ export const tables = defineTables(vocabulary, columns)({
231
252
  nothing names the new row yet, and the last would count the new task itself, since the condition is judged after
232
253
  the write. An upsert's conflict update is judged on the stored row.
233
254
 
255
+ ### `relationWhen`: a condition on what one relation reaches
256
+
257
+ - `relationWhen: { <relation>: { <action>: <condition> } }` narrows only what that relation reaches of the table for
258
+ the action: through `assisting`, only open tasks, while the owner's IAM grant still reaches every task. The table's
259
+ own `when` still applies to every grant; a member reveal and an IAM grant are not narrowed by it.
260
+ - The condition is a `when` in every rule above: the same operators, paths, `not` rule and insert rules. The relation
261
+ must be one the vocabulary declares and the action one the table names, and the relation must reach the table for
262
+ it (its dimension in the table's chain, a `readThrough`, or a reveal of it for that action); otherwise the policy is
263
+ refused. A view checks the relation against its parent, and its own `relationWhen` narrows its rows; the parent's
264
+ does not apply to it.
265
+ - An `on` endpoint whose `Ref` the relation holds sees a row the condition does not admit as absent (404). An insert
266
+ through the relation that the condition refuses, with no other relation to hold it, is a 409 with nothing written.
267
+ - A relation narrowed for an action does not count as holding it when a `writeThrough` column's writer is checked.
268
+
269
+ ### `access`: a view decides what a relation reaches
270
+
271
+ When no declaration above says who reaches a row (a published row of another organization, a grant that is active only
272
+ under a join, several paths to one row), write the rule as SQL in a view and name it under the relation (ADR-0076):
273
+
274
+ - `access: { <relation>: { view, row, principal?, member? } }`. `row` is the view's column with the table's key.
275
+ `member` is compared with the nodes the relation is held inside (a grant of the role in a scope value, at the
276
+ relation's own dimension); `principal` with the caller's principal id. At least one is required.
277
+ - The data layer adds `key in (select <row> from <view> where …)` to every statement under the relation, beside the
278
+ action's other grants. `when` and `relationWhen` still narrow it. A `member`-bound view is not narrowed to the node:
279
+ it may list rows of other organizations, and that is how a cross-tenant rule is written.
280
+ - The view takes no policy, and a table's key needs a single-column primary or unique key (`access-view-key`).
281
+ - The view's SQL is the access rule. The approver reads it as database code that decides the relation, and nothing
282
+ checks what it selects: a `cross join` or a missing tenant join widens access to everyone. Whoever writes the rows
283
+ it reads changes who reaches the table, with no bound. Prefer `confers` when a row per grant fits.
284
+ - Test what each principal reads through it, as `an auditor` below does: one inside the node, one outside it, through
285
+ an endpoint that filters nothing itself, so the test fails when the view's filter is wrong.
286
+
234
287
  ### A key that holds the tenant needs its ancestors NOT NULL
235
288
 
236
289
  A path into another scoped table, other than the container or parent, and a `readThrough` follow a foreign key of
@@ -244,18 +297,33 @@ one is refused and names the column: add a migration that sets it `NOT NULL`, th
244
297
 
245
298
  - `readThrough: { <dimension>: <column> }` lets a `Within` of a dimension outside the table's chain, or a relation at
246
299
  it, read the row through that column's tenant-holding key: a task in a project, read by the members of the team its
247
- `team_id` names. Every write still follows the task's containment, and no update writes the column. When the key
300
+ `team_id` names. No update writes the column. When the key
248
301
  lives on the row's container, name the container's path from the row's own containment column:
249
302
  `readThrough: { team: 'task_id.team_id' }` on a task's comments. The container declares `readThrough.team` through
250
303
  a column of its own; the row follows it wherever the container's column points now. Such a table takes no reveal
251
304
  matched through that path: declare the reveal on the container.
305
+ - `writeThrough: { <dimension>: [<actions>] }` beside `readThrough` lets the path hold those actions for an `on` or `in`
306
+ endpoint too, writes included: a member of the team a task names updates the task. A path holds reads only without
307
+ it. Whoever inserts a row naming a team must hold every listed action at that team (a grant there or above it, a
308
+ relation row there, or a member-revealing row), or the insert answers 409; so must the container's writer for the actions its rows' paths list.
309
+ A job or a webhook holds nothing there. A `Ref` held through the path never moves a row, the table is never written
310
+ `unscoped` or by `ctx.sql`, and `ctx.sql.scope` refuses such a `Ref`.
252
311
  - `reveals: { <relation>: { to, actions, when? } }` on a table the relation reaches: such a row also gives the
253
312
  relation `actions` (those its roles name in `via`) at its ancestor node in `to` while `when` admits the row: an
254
313
  assignee of an open task reads its project. A reveal matched through `readThrough` on a table with an insert needs
255
314
  `assign: {}` (or `{ self: true }`), because the writer picks the node.
256
315
  - `memberReveals: { <own dimension>: { to, actions, when? } }`: a grant at the row's own node holds `actions` at its
257
- ancestor in `to` too, for an `over` list's reads. Such a row is never written unscoped or by `ctx.sql`, and never
258
- moves.
316
+ ancestor in `to` too, while `when` admits the row: an `over` list reads through it, and an `on` or `in` endpoint of a
317
+ listed action gets a `Ref` of the ancestor, writes included. A member of an open task renames its project; once the
318
+ task closes, the next statement answers 404. Such a row is never written unscoped or by `ctx.sql`, and never moves.
319
+ `ctx.sql.scope` refuses a `Ref` held this way: read it through `ctx.db`.
320
+ - `memberReveals` may also be keyed by a dimension the table reads through: `memberReveals: { team: { to: 'project',
321
+ actions: ['projects.read'], assign: {} } }` on tasks that name a team in `readThrough.team`: a grant at that team
322
+ reads the project of each open task naming it. A link row (a child of the task naming a team) reveals its task the
323
+ same way. Through a path `to` is the row's nearest container, and a table with an insert states `assign`: without
324
+ `self`, inserting a row that names a team where the writer holds one of the listed actions answers 409, and a job or
325
+ a webhook names no team there. An `on` or `in` endpoint gets a `Ref` through it only for an action the path's
326
+ `writeThrough` also lists.
259
327
  - A view under a parent takes none of them: it is read through its parent row, so a relation, a reveal, a member
260
328
  reveal or a secondary path that reaches the parent reaches the view's rows of that parent.
261
329
 
@@ -356,6 +424,20 @@ export const tasks = app.group({ callers: ['human'] }, (r) => ({
356
424
  }),
357
425
  )
358
426
  ),
427
+ reachable: r.query({
428
+ input: MyTasks,
429
+ output: TaskPage,
430
+ access: { action: 'tasks.read', over: 'project' },
431
+ })
432
+ .handle(async ({ input, ctx }) =>
433
+ fromPage(
434
+ Task,
435
+ await ctx.db.within.tasks.list({
436
+ orderBy: [['title', 'asc']],
437
+ after: input.after,
438
+ }),
439
+ )
440
+ ),
359
441
  mine: r.query({
360
442
  input: MyTasks,
361
443
  output: TaskPage,
@@ -411,7 +493,8 @@ export const contract = app.contract((c) => ({
411
493
 
412
494
  ## Tests
413
495
 
414
- Grant the role app-wide (`{ role: 'assistant' }`, no scope), as IAM does, and let the endpoints write the rows:
496
+ Grant the role app-wide (`{ role: 'assistant' }`, no scope), as IAM does, or in an organization to hold it only there, and let
497
+ the endpoints write the rows:
415
498
 
416
499
  ```ts src/__tests__/assistants.test.ts
417
500
  import { createClient } from '@fabrika/app/client'
@@ -498,26 +581,68 @@ if (postgres !== null) {
498
581
  ).toBe(409)
499
582
  })
500
583
 
501
- test('a grant of the role in a scope value reaches nothing through the relation', async () => {
584
+ test('a grant of the role in an organization reaches only its projects', async () => {
502
585
  const project = await ownerApi.projects.create({
503
586
  orgId: 'acme',
504
587
  name: 'Scoped',
505
588
  })
506
- const scoped = kit.testCaller([{ role: 'assistant', scope: acme }])
507
- await coordinatorApi.projects.assign({
508
- id: project.id,
509
- assistant: scoped.id,
510
- days: 1,
511
- })
512
- const scopedApi = createClient(contract, 'api', {
513
- fetch: kit.browser(scoped),
589
+ const inAcme = kit.testCaller([{ role: 'assistant', scope: acme }])
590
+ const inGlobex = kit.testCaller([
591
+ { role: 'assistant', scope: kit.scope('org', 'globex') },
592
+ ])
593
+ for (const scoped of [inAcme, inGlobex]) {
594
+ await coordinatorApi.projects.assign({
595
+ id: project.id,
596
+ assistant: scoped.id,
597
+ days: 1,
598
+ })
599
+ }
600
+ const acmeApi = createClient(contract, 'api', { fetch: kit.browser(inAcme) })
601
+ const globexApi = createClient(contract, 'api', {
602
+ fetch: kit.browser(inGlobex),
514
603
  })
515
- expect(await statusOf(scopedApi.tasks.list({ projectId: project.id }))).toBe(
604
+ expect((await acmeApi.tasks.list({ projectId: project.id })).items).toEqual(
605
+ [],
606
+ )
607
+ expect(await statusOf(globexApi.tasks.list({ projectId: project.id }))).toBe(
516
608
  403,
517
609
  )
518
610
  })
519
611
  })
520
612
 
613
+ describe('an auditor', () => {
614
+ test('reads the finished tasks of the organization it audits, and only those', async () => {
615
+ const project = await ownerApi.projects.create({
616
+ orgId: 'acme',
617
+ name: 'Audited',
618
+ })
619
+ const open = await ownerApi.tasks.create({
620
+ projectId: project.id,
621
+ title: 'Open',
622
+ })
623
+ const done = await ownerApi.tasks.create({
624
+ projectId: project.id,
625
+ title: 'Done',
626
+ })
627
+ await ownerApi.tasks.finish({ id: done.id, expectVersion: 1 })
628
+ const auditorApi = createClient(contract, 'api', {
629
+ fetch: kit.browser(kit.testCaller([{ role: 'auditor', scope: acme }])),
630
+ })
631
+ const outsiderApi = createClient(contract, 'api', {
632
+ fetch: kit.browser(
633
+ kit.testCaller([{ role: 'auditor', scope: kit.scope('org', 'globex') }]),
634
+ ),
635
+ })
636
+ // `reachable` filters nothing itself: only the view keeps the open task from the auditor.
637
+ const audited = (await auditorApi.tasks.reachable({})).items.map((item) =>
638
+ item.id
639
+ )
640
+ expect(audited).toContain(done.id)
641
+ expect(audited).not.toContain(open.id)
642
+ expect((await outsiderApi.tasks.reachable({})).items).toEqual([])
643
+ })
644
+ })
645
+
521
646
  describe('a project past its end', () => {
522
647
  test('is read, and takes no new task from anyone', async () => {
523
648
  const ended = await ownerApi.projects.create({
@@ -550,9 +675,8 @@ if (postgres !== null) {
550
675
  ## Not built yet
551
676
 
552
677
  - No widening condition (`admits`): a `when` only narrows. A row that some other rule should open to more people is
553
- reached by a grant, a relation or an off-road declaration, never by a condition.
554
- - A relation holds only through a global grant of an internal role without `member`. A relation inside the node of a
555
- scoped grant, and a relation for a person from outside the organization, are not built.
678
+ reached by a grant, a relation or an access view, never by a condition.
679
+ - A relation for a person from outside the organization is not built.
556
680
  - A view is never a relation source: write the source rows to a table, under `assign`.
557
681
  - An assignment never changes in place: delete the row and insert a new one.
558
682
  - No raw SQL and no JSON column in a condition, and no path longer than three foreign keys.
@@ -167,7 +167,10 @@ INSERT INTO priorities (code, label, rank) VALUES ('low', 'Low', 1), ('normal',
167
167
  `SET`, transaction control, `SECURITY DEFINER`, a domain, `serial` and sequences (use `GENERATED ALWAYS AS IDENTITY`),
168
168
  a function overload, and calls outside the reviewed built-ins.
169
169
  - Never edit, rename or delete a committed migration; add a new one. Change a schema by expand, switch, contract, and
170
- ask before you drop or rename anything.
170
+ ask before you drop or rename anything. A migration statement that is not known to keep every stored value (it
171
+ drops a table or a column, empties, deletes, updates or upserts rows, changes a column's type, renames, or calls its
172
+ own database code) shows a separate line that says it deletes, overwrites or may change data. That line waits for a
173
+ person on a protected environment, and the platform backs the database up before the migration runs.
171
174
 
172
175
  ## On Cloudflare: SQLite migrations
173
176
 
@@ -52,7 +52,8 @@ export const integrations = app.group({ callers: ['human'] }, (r) => ({
52
52
  `POST /hooks/github/:bindingId`.
53
53
  - A binding is made by a procedure that declares `binds: '<webhook>'` and calls `ctx.webhooks('<webhook>').bind(ref,
54
54
  account)` with a capability on the bound value (`ctx.target`, an org here), in its transaction; `unbind(ref, id)`
55
- removes one. A GitHub account is `installation:<id>` or `repository:<id>`. The answer carries the secret and the URL
55
+ removes one. The `Ref` must come from an IAM grant: one held through a relation, a member reveal or a secondary
56
+ path is refused, because the binding would outlive the rows that hold it. A GitHub account is `installation:<id>` or `repository:<id>`. The answer carries the secret and the URL
56
57
  once. The generated tests need a fixture for its input (`references/tests.md`).
57
58
  - The framework checks the signature, the account and the input (undeclared fields are dropped).
58
59
  `ctx.refs['<action>']` is a `Ref` of the bound org for each declared action.
@@ -0,0 +1,16 @@
1
+ // The child of `writeGeneratedContract`: it runs in the application root with no credential in its environment, loads
2
+ // the application module, and prints its compiled contract in the shared encoding, which the build bundles.
3
+
4
+ import { encodedArtifactJson } from '@fabrika/auth-core'
5
+ import { join } from 'node:path'
6
+ import { IMPLEMENTATION_FILE } from './build.js'
7
+ import { compileContract } from './contract/compile.js'
8
+ import { isContractImplementation } from './implement/implement.js'
9
+
10
+ const module: unknown = await import(join(process.cwd(), IMPLEMENTATION_FILE))
11
+ const app = typeof module === 'object' && module !== null ? Reflect.get(module, 'default') : undefined
12
+ if (!isContractImplementation(app)) {
13
+ console.error(`${IMPLEMENTATION_FILE} does not default-export serve(contract, { … })`)
14
+ process.exit(1)
15
+ }
16
+ process.stdout.write(encodedArtifactJson(compileContract(app.contract, app.database?.tables ?? {})))
package/src/build.ts CHANGED
@@ -4,6 +4,7 @@
4
4
 
5
5
  import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises'
6
6
  import { dirname, join } from 'node:path'
7
+ import { fileURLToPath } from 'node:url'
7
8
 
8
9
  /** An application root with this file is a contract application. The paths equal `@fabrika/check`'s layout. */
9
10
  export const CONTRACT_FILE = 'fabrika.contract.ts'
@@ -17,6 +18,12 @@ export const IMPLEMENTATION_FILE = 'src/app.ts'
17
18
  /** The application's migrations as a module, relative to the application root: a Worker reads no file system. */
18
19
  export const GENERATED_MIGRATIONS_FILE = 'fabrika/migrations.generated.ts'
19
20
 
21
+ /**
22
+ * The compiled contract as a module, relative to the application root: the Cloudflare entrypoint hands it to boot, which
23
+ * checks its digest and reads it instead of compiling the contract inside the isolate.
24
+ */
25
+ export const GENERATED_CONTRACT_FILE = 'fabrika/contract.generated.ts'
26
+
20
27
  /** Where an application keeps its migrations, relative to its root; `fabrika db new` writes there. */
21
28
  export const MIGRATIONS_DIRECTORY = 'db/migrations'
22
29
 
@@ -51,29 +58,68 @@ export function generatedEntry(runtime: EntryRuntime): string {
51
58
  return [
52
59
  HEADER,
53
60
  "import { createContractWorker, markProductionProcess } from '@fabrika/app/cloudflare'",
61
+ "import { approvedContract } from './contract.generated'",
54
62
  "import { migrations } from './migrations.generated'",
55
63
  '',
56
64
  "export { FabrikaApplication } from '@fabrika/app/cloudflare'",
57
65
  '',
58
66
  '// The test kits refuse to load from here on; the object imports the application only after the framework took its variables.',
59
67
  'markProductionProcess()',
60
- "export default createContractWorker(() => import('../src/app'), { migrations })",
68
+ "export default createContractWorker(() => import('../src/app'), { migrations, approvedContract })",
61
69
  '',
62
70
  ].join('\n')
63
71
  }
64
72
  }
65
73
 
66
- /** Writes the entrypoint under `root` and returns its path; the Cloudflare one also writes the migrations module it imports. */
74
+ /**
75
+ * Writes the entrypoint under `root` and returns its path; the Cloudflare one also writes the migrations and the compiled
76
+ * contract modules it imports.
77
+ */
67
78
  export async function writeGeneratedEntry(root: string, runtime: EntryRuntime): Promise<string> {
68
79
  const path = join(root, GENERATED_ENTRY_FILE)
69
80
  await mkdir(dirname(path), { recursive: true })
70
81
  await writeFile(path, generatedEntry(runtime))
71
82
  if (runtime === 'cloudflare') {
72
83
  await writeGeneratedMigrations(root)
84
+ await writeGeneratedContract(root)
73
85
  }
74
86
  return path
75
87
  }
76
88
 
89
+ const CONTRACT_CHILD = fileURLToPath(new URL('./build-contract-child.ts', import.meta.url))
90
+
91
+ /** The compiled contract module source: the artifact's shared encoding (`encodeArtifact`) as one string, verbatim. */
92
+ export function generatedContract(encoded: string): string {
93
+ return [
94
+ `// @generated by \`fabrika app build\` from ${IMPLEMENTATION_FILE}. Do not edit: every build rewrites it.`,
95
+ '',
96
+ `export const approvedContract: string = ${JSON.stringify(encoded)}`,
97
+ '',
98
+ ].join('\n')
99
+ }
100
+
101
+ /**
102
+ * Compiles the application's contract in a child process, which loads `src/app.ts` with no variable but `PATH` and
103
+ * `HOME`, writes the module under `root` and returns its path. A contract that does not compile fails the build.
104
+ */
105
+ export async function writeGeneratedContract(root: string): Promise<string> {
106
+ const child = Bun.spawn([process.execPath, CONTRACT_CHILD], {
107
+ cwd: root,
108
+ env: { PATH: process.env['PATH'] ?? '', HOME: process.env['HOME'] ?? '' },
109
+ stdin: 'ignore',
110
+ stdout: 'pipe',
111
+ stderr: 'pipe',
112
+ })
113
+ const [encoded, stderr] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited])
114
+ if (child.exitCode !== 0) {
115
+ throw new Error(`the contract of ${root} does not compile:\n${stderr.trim()}`)
116
+ }
117
+ const path = join(root, GENERATED_CONTRACT_FILE)
118
+ await mkdir(dirname(path), { recursive: true })
119
+ await writeFile(path, generatedContract(encoded))
120
+ return path
121
+ }
122
+
77
123
  /** The application's migrations under `root`, every `.sql` file of `db/migrations` by name; none without the directory. */
78
124
  export async function applicationMigrations(root: string): Promise<readonly { readonly name: string; readonly sql: string }[]> {
79
125
  const directory = join(root, MIGRATIONS_DIRECTORY)