@fabrika/app 0.9.0-cloudflare.3 → 0.9.0-dev.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/package.json +9 -9
  2. package/skill/SKILL.md +6 -3
  3. package/skill/references/app-setup.md +8 -8
  4. package/skill/references/dev.md +3 -1
  5. package/skill/references/endpoint.md +9 -9
  6. package/skill/references/errors.md +42 -34
  7. package/skill/references/files.md +4 -2
  8. package/skill/references/jobs.md +18 -12
  9. package/skill/references/table-and-migration.md +31 -4
  10. package/skill/references/tests.md +22 -10
  11. package/src/bun.ts +0 -10
  12. package/src/cloudflare/import.ts +3 -212
  13. package/src/contract/artifact-schema.ts +1 -6
  14. package/src/contract/build.ts +10 -33
  15. package/src/contract/capability-cases.ts +30 -0
  16. package/src/contract/containers.ts +19 -0
  17. package/src/contract/group.ts +1 -10
  18. package/src/contract/index.ts +1 -0
  19. package/src/contract/kit.ts +1 -2
  20. package/src/files/handle.ts +2 -1
  21. package/src/files/kinds.ts +1 -1
  22. package/src/implement/boot.ts +12 -30
  23. package/src/implement/capability.ts +1 -4
  24. package/src/implement/dispatch.ts +8 -5
  25. package/src/implement/egress.ts +8 -367
  26. package/src/implement/failures.ts +42 -3
  27. package/src/implement/faults.ts +4 -1
  28. package/src/implement/invocation.ts +13 -11
  29. package/src/implement/tokens.ts +4 -2
  30. package/src/implement/types.ts +22 -4
  31. package/src/jobs/runner.ts +32 -20
  32. package/src/testing/endpoint-access.ts +30 -23
  33. package/src/testing/index.ts +1 -1
  34. package/src/testing/kit.ts +6 -2
  35. package/src/testing/policy-isolation.ts +2 -2
  36. package/types/src/cloudflare/import.d.ts +1 -12
  37. package/types/src/contract/capability-cases.d.ts +9 -0
  38. package/types/src/contract/containers.d.ts +3 -0
  39. package/types/src/contract/group.d.ts +1 -9
  40. package/types/src/contract/index.d.ts +1 -0
  41. package/types/src/contract/kit.d.ts +2 -2
  42. package/types/src/files/handle.d.ts +2 -1
  43. package/types/src/implement/boot.d.ts +6 -9
  44. package/types/src/implement/capability.d.ts +1 -3
  45. package/types/src/implement/dispatch.d.ts +1 -2
  46. package/types/src/implement/egress.d.ts +1 -36
  47. package/types/src/implement/failures.d.ts +21 -2
  48. package/types/src/implement/faults.d.ts +4 -1
  49. package/types/src/implement/invocation.d.ts +6 -5
  50. package/types/src/implement/types.d.ts +25 -5
  51. package/types/src/jobs/runner.d.ts +14 -8
  52. package/types/src/testing/endpoint-access.d.ts +4 -3
  53. package/types/src/testing/index.d.ts +1 -1
  54. package/types/src/testing/kit.d.ts +6 -2
@@ -5,6 +5,7 @@
5
5
 
6
6
  import {
7
7
  decodeOpsDumpLine,
8
+ describeOpsDumpSchema,
8
9
  encodeOpsDumpRow,
9
10
  foldOpsTableHash,
10
11
  OPS_DATA_REFUSED_STATUS,
@@ -24,11 +25,7 @@ import {
24
25
  type OpsDumpManifest,
25
26
  opsDumpRowidSql,
26
27
  type OpsDumpSchema,
27
- type OpsDumpSchemaColumn,
28
28
  type OpsDumpSchemaEntry,
29
- type OpsDumpSchemaForeignKey,
30
- type OpsDumpSchemaIndex,
31
- type OpsDumpSchemaTable,
32
29
  type OpsDumpSource,
33
30
  type OpsDumpTable,
34
31
  type OpsDumpTablePlan,
@@ -761,200 +758,9 @@ function sameDdl(left: readonly OpsDumpSchemaEntry[], right: readonly OpsDumpSch
761
758
  return left.length === right.length && canonical(left) === canonical(right)
762
759
  }
763
760
 
764
- /**
765
- * The schema `planOpsDump` reads, from the PRAGMAs workerd admits, of every table a dump holds. An `INITIALLY DEFERRED`
766
- * clause is read from the table's SQL outside its quotes and comments, and marks every foreign key of its table; the
767
- * names a `CHECK` reads come from the same SQL (`checkNamesOf`).
768
- */
761
+ /** The schema `planOpsDump` reads, of every table a dump holds (`describeOpsDumpSchema`). */
769
762
  export function describeDumpSchema(storage: SqliteStorage): OpsDumpSchema {
770
- const tables: OpsDumpSchemaTable[] = []
771
- for (const row of storage.sql.exec('PRAGMA table_list').toArray()) {
772
- const name = text(row['name'])
773
- const type = text(row['type'])
774
- if (text(row['schema']) !== 'main' || type === 'view' || !dumped(name)) {
775
- continue
776
- }
777
- const virtual = type === 'virtual'
778
- const sql = storage.sql.exec(`SELECT sql FROM sqlite_schema WHERE type = 'table' AND name = ?`, name).toArray()[0]?.['sql']
779
- const clauses = typeof sql === 'string' ? unquotedSql(sql) : null
780
- tables.push({
781
- name,
782
- virtual,
783
- withoutRowid: flag(row['wr']),
784
- checkNames: typeof sql === 'string' ? checkNamesOf(sql) : null,
785
- // A virtual table is refused whatever it holds, and its module may not be loaded to describe it.
786
- columns: virtual ? [] : describeColumns(storage, name),
787
- indexes: virtual ? [] : describeIndexes(storage, name),
788
- foreignKeys: virtual ? [] : describeForeignKeys(storage, name, clauses === null || /\binitially\s+deferred\b/i.test(clauses)),
789
- })
790
- }
791
- return { tables }
792
- }
793
-
794
- function describeColumns(storage: SqliteStorage, table: string): OpsDumpSchemaColumn[] {
795
- return storage.sql.exec(`PRAGMA table_xinfo(${literal(table)})`).toArray().map((row) => {
796
- const hidden = integer(row['hidden'])
797
- return {
798
- name: text(row['name']),
799
- type: text(row['type']),
800
- notNull: flag(row['notnull']),
801
- primaryKey: integer(row['pk']),
802
- generated: hidden === 2 || hidden === 3,
803
- }
804
- })
805
- }
806
-
807
- function describeIndexes(storage: SqliteStorage, table: string): OpsDumpSchemaIndex[] {
808
- return storage.sql.exec(`PRAGMA index_list(${literal(table)})`).toArray().map((row) => {
809
- const origin = row['origin']
810
- if (origin !== 'c' && origin !== 'u' && origin !== 'pk') {
811
- throw new Error('PRAGMA index_list answered an origin SQLite does not write')
812
- }
813
- const columns = storage.sql.exec(`PRAGMA index_xinfo(${literal(text(row['name']))})`).toArray()
814
- .filter((column) => flag(column['key']))
815
- .sort((left, right) => integer(left['seqno']) - integer(right['seqno']))
816
- .map((column) => typeof column['name'] === 'string' ? column['name'] : null)
817
- return { unique: flag(row['unique']), origin, partial: flag(row['partial']), columns }
818
- })
819
- }
820
-
821
- function describeForeignKeys(storage: SqliteStorage, table: string, initiallyDeferred: boolean): OpsDumpSchemaForeignKey[] {
822
- const keys = new Map<number, { parent: string; rows: { seq: number; from: string; to: string | null }[] }>()
823
- for (const row of storage.sql.exec(`PRAGMA foreign_key_list(${literal(table)})`).toArray()) {
824
- const id = integer(row['id'])
825
- const to = row['to']
826
- const entry = { seq: integer(row['seq']), from: text(row['from']), to: typeof to === 'string' ? to : null }
827
- const key = keys.get(id)
828
- if (key === undefined) {
829
- keys.set(id, { parent: text(row['table']), rows: [entry] })
830
- } else {
831
- key.rows.push(entry)
832
- }
833
- }
834
- return [...keys.entries()].sort(([left], [right]) => left - right).map(([, key]) => {
835
- const rows = key.rows.sort((left, right) => left.seq - right.seq)
836
- const references = rows.flatMap((row) => row.to === null ? [] : [row.to])
837
- if (references.length !== 0 && references.length !== rows.length) {
838
- throw new Error('PRAGMA foreign_key_list named the parent columns of a key only in part')
839
- }
840
- return { parent: key.parent, columns: rows.map((row) => row.from), references: references.length === 0 ? null : references, initiallyDeferred }
841
- })
842
- }
843
-
844
- type SqlToken =
845
- | { readonly kind: 'name'; readonly text: string; readonly quoted: boolean }
846
- | { readonly kind: 'open' | 'close' | 'other' }
847
-
848
- const WORD_CHAR = /[A-Za-z0-9_$\u0080-\uffff]/
849
-
850
- /**
851
- * The names the `CHECK` clauses of a table's `sql` read: every word and quoted identifier between a `CHECK` keyword's
852
- * parentheses, ASCII-lowercase, keywords and numbers included, so it lists at least every column a `CHECK` reads. A
853
- * string literal and a comment name nothing; a double-quoted string, which SQLite may read as either, counts as a name.
854
- * `null` when the text does not scan (an unclosed quote, comment or parenthesis), which counts as naming every column.
855
- */
856
- export function checkNamesOf(sql: string): string[] | null {
857
- const tokens = sqlTokens(sql)
858
- if (tokens === null) return null
859
- const names: string[] = []
860
- for (let index = 0; index < tokens.length; index++) {
861
- const token = tokens[index]
862
- if (token?.kind !== 'name' || token.quoted || asciiLower(token.text) !== 'check' || tokens[index + 1]?.kind !== 'open') continue
863
- let depth = 0
864
- let end = index + 1
865
- for (; end < tokens.length; end++) {
866
- const inner = tokens[end]
867
- if (inner?.kind === 'open') depth++
868
- else if (inner?.kind === 'close' && --depth === 0) break
869
- else if (inner?.kind === 'name') names.push(asciiLower(inner.text))
870
- }
871
- if (end === tokens.length) return null
872
- index = end
873
- }
874
- return names
875
- }
876
-
877
- /** `sql` as words, quoted identifiers and parentheses; string literals, comments and whitespace dropped. */
878
- function sqlTokens(sql: string): SqlToken[] | null {
879
- const tokens: SqlToken[] = []
880
- let index = 0
881
- while (index < sql.length) {
882
- const char = sql.charAt(index)
883
- if (sql.startsWith('--', index)) {
884
- const end = sql.indexOf('\n', index)
885
- index = end < 0 ? sql.length : end + 1
886
- } else if (sql.startsWith('/*', index)) {
887
- const end = sql.indexOf('*/', index + 2)
888
- if (end < 0) return null
889
- index = end + 2
890
- } else if (char === "'" || char === '"' || char === '`' || char === '[') {
891
- const close = char === '[' ? ']' : char
892
- let end = index + 1
893
- let text = ''
894
- for (;;) {
895
- const next = sql.indexOf(close, end)
896
- if (next < 0) return null
897
- text += sql.slice(end, next)
898
- if (close !== ']' && sql.charAt(next + 1) === close) {
899
- text += close
900
- end = next + 2
901
- continue
902
- }
903
- end = next + 1
904
- break
905
- }
906
- if (char !== "'") tokens.push({ kind: 'name', text, quoted: true })
907
- index = end
908
- } else if (WORD_CHAR.test(char)) {
909
- let end = index + 1
910
- while (end < sql.length && WORD_CHAR.test(sql.charAt(end))) end++
911
- tokens.push({ kind: 'name', text: sql.slice(index, end), quoted: false })
912
- index = end
913
- } else {
914
- if (char === '(') tokens.push({ kind: 'open' })
915
- else if (char === ')') tokens.push({ kind: 'close' })
916
- else if (!/\s/.test(char)) tokens.push({ kind: 'other' })
917
- index++
918
- }
919
- }
920
- return tokens
921
- }
922
-
923
- /** SQLite compares identifiers case-insensitively in ASCII only. */
924
- function asciiLower(value: string): string {
925
- return value.replace(/[A-Z]/g, (letter) => letter.toLowerCase())
926
- }
927
-
928
- /** `sql` with its string literals, quoted identifiers and comments blanked, so a keyword search finds only clauses. */
929
- function unquotedSql(sql: string): string {
930
- let out = ''
931
- let index = 0
932
- while (index < sql.length) {
933
- const char = sql.charAt(index)
934
- const close = char === "'" ? "'" : char === '"' ? '"' : char === '`' ? '`' : char === '[' ? ']' : null
935
- if (close !== null) {
936
- let end = index + 1
937
- for (;;) {
938
- end = sql.indexOf(close, end)
939
- if (end < 0 || close === ']' || sql.charAt(end + 1) !== close) break
940
- end += 2
941
- }
942
- index = end < 0 ? sql.length : end + 1
943
- out += ' '
944
- } else if (sql.startsWith('--', index)) {
945
- const end = sql.indexOf('\n', index)
946
- index = end < 0 ? sql.length : end + 1
947
- out += ' '
948
- } else if (sql.startsWith('/*', index)) {
949
- const end = sql.indexOf('*/', index + 2)
950
- index = end < 0 ? sql.length : end + 2
951
- out += ' '
952
- } else {
953
- out += char
954
- index++
955
- }
956
- }
957
- return out
763
+ return describeOpsDumpSchema((query, ...bindings) => storage.sql.exec(query, ...bindings).toArray())
958
764
  }
959
765
 
960
766
  /** The import marker, parsed strictly; `null` when the object holds none. A marker that does not parse is a corrupt object. */
@@ -1056,10 +862,6 @@ function quote(identifier: string): string {
1056
862
  return `"${identifier.replaceAll('"', '""')}"`
1057
863
  }
1058
864
 
1059
- function literal(value: string): string {
1060
- return `'${value.replaceAll("'", "''")}'`
1061
- }
1062
-
1063
865
  /** Code-unit order, which no locale changes; the migration runner orders files the same way. */
1064
866
  function compareNames(left: string, right: string): number {
1065
867
  return left < right ? -1 : left > right ? 1 : 0
@@ -1084,14 +886,3 @@ function text(value: SqliteValue | undefined): string {
1084
886
  }
1085
887
  return value
1086
888
  }
1087
-
1088
- function integer(value: SqliteValue | undefined): number {
1089
- if (typeof value !== 'number' || !Number.isSafeInteger(value)) {
1090
- throw new Error('SQLite answered a schema number that is not an integer')
1091
- }
1092
- return value
1093
- }
1094
-
1095
- function flag(value: SqliteValue | undefined): boolean {
1096
- return integer(value) !== 0
1097
- }
@@ -14,14 +14,12 @@ import {
14
14
  FILE_RESPONSE_KINDS,
15
15
  isOwnWorkloadName,
16
16
  JOB_MAILERS,
17
- JOB_SITE_PREFIX,
18
17
  LOCALES,
19
18
  mailTemplateProblems,
20
19
  MAX_CACHE_AGE_SECONDS,
21
20
  type MessageKind,
22
21
  type NumberShape,
23
22
  type OutputShape,
24
- PUBLIC_EGRESS,
25
23
  type RecordShape,
26
24
  type SchemaShape,
27
25
  type StringShape,
@@ -419,12 +417,9 @@ export const contractArtifactSchema: z.ZodType<ContractArtifact> = z.strictObjec
419
417
  kicks: z.array(name).nonempty().optional(),
420
418
  binds: name.optional(),
421
419
  signs: z.array(name).nonempty().optional(),
422
- egress: z.union([z.array(z.string().refine((origin) => isPolicyOrigin(origin))).nonempty(), z.literal(PUBLIC_EGRESS)]).optional(),
420
+ egress: z.array(z.string().refine((origin) => isPolicyOrigin(origin))).nonempty().optional(),
423
421
  })).superRefine((declared, context) => {
424
422
  for (const [site, reach] of Object.entries(declared)) {
425
- if (reach.egress === PUBLIC_EGRESS && !site.startsWith(JOB_SITE_PREFIX)) {
426
- context.addIssue({ code: 'custom', path: [site, 'egress'], message: "egress: 'public' belongs to a cron job, keyed by job:<name>" })
427
- }
428
423
  if (reach.actions !== undefined && !isOwnWorkloadName('public', site)) {
429
424
  context.addIssue({ code: 'custom', path: [site, 'actions'], message: 'workload actions belong to a public procedure, keyed by its endpoint id' })
430
425
  }
@@ -18,7 +18,6 @@ import {
18
18
  type ContractArtifact,
19
19
  type CspExtensions,
20
20
  type CspSource,
21
- type DeclaredEgress,
22
21
  type DeclaredReach,
23
22
  type DimensionArtifact,
24
23
  directoryReach,
@@ -53,7 +52,6 @@ import {
53
52
  planEndpoint,
54
53
  type ProcedureArtifact,
55
54
  type ProcedureChallenge,
56
- PUBLIC_EGRESS,
57
55
  type RoleArtifact,
58
56
  type SchemaShape,
59
57
  type ScopeBinding,
@@ -149,7 +147,7 @@ const FRAMEWORK_TABLE_PREFIX = 'fabrika_'
149
147
  /** The most origins one site calls: a site that reaches more is an integration hub, which a connector import serves. */
150
148
  const MAX_EGRESS_ORIGINS = 16
151
149
  const DECLARED_ALLOWED =
152
- "sql: 'read' | 'write', unscoped: { <table>: 'read' | 'write' }, connect: ['<import>'], issues: '<link mount>', mailer: 'installation' | 'own', kicks: ['<cron job>'], binds: '<webhook>', signs: ['<token purpose>'], egress: ['https://<host>'] | 'public' (a cron job)"
150
+ "sql: 'read' | 'write', unscoped: { <table>: 'read' | 'write' }, connect: ['<import>'], issues: '<link mount>', mailer: 'installation' | 'own', kicks: ['<cron job>'], binds: '<webhook>', signs: ['<token purpose>'], egress: ['https://<host>']"
153
151
  const CSP_FIELDS = ['connectSrc', 'imgSrc', 'frameAncestors', 'scriptSrc', 'frameSrc', 'styleSrc', 'fontSrc']
154
152
  /** An environment variable an application reads; a challenge names its secret by one. */
155
153
  const APPLICATION_VARIABLE = /^[A-Z][A-Z0-9_]*$/
@@ -2112,7 +2110,7 @@ class ArtifactBuilder {
2112
2110
  ...(kicks.length === 0 ? {} : { kicks }),
2113
2111
  ...(binds === undefined ? {} : { binds }),
2114
2112
  ...(signs.length === 0 ? {} : { signs }),
2115
- ...(egress === null ? {} : { egress }),
2113
+ ...(egress.length === 0 ? {} : { egress }),
2116
2114
  }
2117
2115
  if (place.kind !== 'rpc') {
2118
2116
  this.#rpcOnly(where, 'connect', value['connect'])
@@ -2311,13 +2309,12 @@ class ArtifactBuilder {
2311
2309
 
2312
2310
  /**
2313
2311
  * The HTTPS origins a site's code calls: a credentialed procedure of an RPC mount, a webhook or a job, never a public,
2314
- * export or link procedure. Each is an exact origin with no path or wildcard, once. Or `'public'`, every public host
2315
- * (ADR-0071), which only a cron job declares: it calls outside any transaction, and its schedule, not a caller,
2316
- * decides when. `null` when it declares none or after a problem.
2312
+ * export or link procedure. Each is an exact origin with no path or wildcard, once; `[]` when it declares none or after
2313
+ * a problem.
2317
2314
  */
2318
- #egress(where: string, value: unknown, place: DeclaringSite): DeclaredEgress | null {
2315
+ #egress(where: string, value: unknown, place: DeclaringSite): string[] {
2319
2316
  if (value === undefined) {
2320
- return null
2317
+ return []
2321
2318
  }
2322
2319
  const refusedBy = place.kind === 'export'
2323
2320
  ? 'an export procedure'
@@ -2328,35 +2325,15 @@ class ArtifactBuilder {
2328
2325
  : null
2329
2326
  if (refusedBy !== null) {
2330
2327
  this.#problem(where, `declares egress, which ${refusedBy} never does: a credentialed procedure, a webhook or a job calls out`)
2331
- return null
2332
- }
2333
- if (value === PUBLIC_EGRESS) {
2334
- if (place.kind !== 'job') {
2335
- this.#problem(
2336
- where,
2337
- `declares egress: '${PUBLIC_EGRESS}', which only a cron job declares: a procedure or a webhook names its origins (allowed: egress: ['https://api.example.com'])`,
2338
- )
2339
- return null
2340
- }
2341
- return PUBLIC_EGRESS
2328
+ return []
2342
2329
  }
2343
2330
  if (!Array.isArray(value) || value.length === 0 || !value.every((origin) => typeof origin === 'string')) {
2344
- this.#problem(
2345
- where,
2346
- place.kind === 'job'
2347
- ? "egress is not a list of origins or 'public' (allowed: egress: ['https://api.example.com'] or egress: 'public')"
2348
- : "egress is not a list of origins (allowed: egress: ['https://api.example.com'])",
2349
- )
2350
- return null
2331
+ this.#problem(where, "egress is not a list of origins (allowed: egress: ['https://api.example.com'])")
2332
+ return []
2351
2333
  }
2352
2334
  const origins: string[] = value.filter((origin) => typeof origin === 'string')
2353
2335
  if (origins.length > MAX_EGRESS_ORIGINS) {
2354
- this.#problem(
2355
- where,
2356
- `${origins.length} egress origins exceed the limit of ${MAX_EGRESS_ORIGINS}${
2357
- place.kind === 'job' ? " (a cron job that calls the websites its operators name declares egress: 'public')" : ''
2358
- }`,
2359
- )
2336
+ this.#problem(where, `${origins.length} egress origins exceed the limit of ${MAX_EGRESS_ORIGINS}`)
2360
2337
  }
2361
2338
  for (const origin of origins) {
2362
2339
  if (!isPolicyOrigin(origin)) {
@@ -0,0 +1,30 @@
1
+ // Which capability of an endpoint of several has no denied case: the rule both the scaffold and the endpoint access kit
2
+ // read, so the generated tests never ask the kit for a case it refuses.
3
+
4
+ import type { CapabilityRequirement, DimensionArtifact } from '@fabrika/auth-core'
5
+ import { containersOf } from './containers'
6
+
7
+ /**
8
+ * The capability that rules out `name`'s denied case, or `undefined` when `name` has one. Only an `over` capability
9
+ * loses it: to another capability that needs the same action on its dimension, on a container of it or on a dimension
10
+ * inside it. Every caller that passes that other one holds the action where the runtime lists the `over` dimension from
11
+ * (a value of it, of a container, or of a dimension inside it, through the same `containersOf`), so none is refused the
12
+ * list. Another one on an unrelated dimension leaves the case: a caller holding the action only there is refused (403).
13
+ */
14
+ export function deniedCaseRuledOutBy(
15
+ capabilities: Readonly<Record<string, CapabilityRequirement>>,
16
+ name: string,
17
+ dimensions: Readonly<Record<string, DimensionArtifact>>,
18
+ ): string | undefined {
19
+ const named = capabilities[name]
20
+ if (named?.access.form !== 'over') return undefined
21
+ const listed = named.access.dimension
22
+ const containers = containersOf(dimensions)
23
+ return Object.entries(capabilities).find(([other, { action, access }]) =>
24
+ other !== name
25
+ && action === named.action
26
+ && (access.dimension === listed
27
+ || (containers.get(listed) ?? []).includes(access.dimension)
28
+ || (containers.get(access.dimension) ?? []).includes(listed))
29
+ )?.[0]
30
+ }
@@ -0,0 +1,19 @@
1
+ // The containment chains of a contract's dimensions: what the runtime's `over` reads a caller's grants through, and
2
+ // what decides which capability of several has a denied case (`capability-cases.ts`).
3
+
4
+ import type { DimensionArtifact } from '@fabrika/auth-core'
5
+
6
+ /** Every dimension's containers, nearest first (`note → [workspace, organization]`); `buildArtifact` refuses a cycle. */
7
+ export function containersOf(dimensions: Readonly<Record<string, DimensionArtifact>>): ReadonlyMap<string, readonly string[]> {
8
+ const containers = new Map<string, readonly string[]>()
9
+ for (const dimension of Object.keys(dimensions)) {
10
+ const chain: string[] = []
11
+ let next = dimensions[dimension]?.in ?? null
12
+ while (next !== null && !chain.includes(next)) {
13
+ chain.push(next)
14
+ next = dimensions[next]?.in ?? null
15
+ }
16
+ containers.set(dimension, chain)
17
+ }
18
+ return containers
19
+ }
@@ -115,16 +115,7 @@ export type SignsField<Sg, Purposes extends string> =
115
115
  * `fetch` refuses any other while the site runs; a public procedure declares none.
116
116
  */
117
117
  export interface EgressField {
118
- readonly egress?: readonly `https://${string}`[] | Unavailable<"egress: 'public' is a cron job's only: record a row and kick a job that declares it">
119
- }
120
-
121
- /**
122
- * A cron job's `egress`: its exact HTTPS origins, or `'public'`, every public host over HTTPS or HTTP on its default
123
- * port, for a job that calls the websites its operators name (ADR-0071). The guard refuses IP addresses, local and
124
- * internal names and the installation's own hosts, checks each redirect, and bounds each request's time and body.
125
- */
126
- export interface JobEgressField {
127
- readonly egress?: readonly `https://${string}`[] | 'public'
118
+ readonly egress?: readonly `https://${string}`[]
128
119
  }
129
120
 
130
121
  /** Each purpose `signs` names is one of `defineApp`'s `tokens`. */
@@ -12,6 +12,7 @@ export {
12
12
  attachmentOutput,
13
13
  } from './attachment'
14
14
  export { buildArtifact } from './build'
15
+ export { deniedCaseRuledOutBy } from './capability-cases'
15
16
  export { compileContract, describeContract } from './compile'
16
17
  export {
17
18
  type ConnectSnapshot,
@@ -57,7 +57,6 @@ import type {
57
57
  GroupBuild,
58
58
  GroupInput,
59
59
  GroupKit,
60
- JobEgressField,
61
60
  KicksField,
62
61
  LimitsOption,
63
62
  LinkGroupKit,
@@ -97,7 +96,7 @@ export type CronOptions<Acts, S, U, Is, Ix extends AnyDbIndex, M = never, Ks = n
97
96
  & MailerField<M>
98
97
  & KicksField<Ks>
99
98
  & SignsField<Sg, Purposes>
100
- & JobEgressField
99
+ & EgressField
101
100
 
102
101
  /** The mail transport a job reaches, inferred from its optional field and then required, like a declared field. */
103
102
  type MailerField<M> =
@@ -102,7 +102,8 @@ export type StoredFileBody = Uint8Array | ReadableStream<Uint8Array> | Blob
102
102
  /**
103
103
  * `ctx.files.put` and `ctx.files.open`: the stored files of a site (`c.files` kinds). A put stages a file this request
104
104
  * holds; writing its reference into a file column is what keeps it. `open` reads a live file whose reference this
105
- * request holds and may read: an input file, a put, or a file column read under its table's read action.
105
+ * request holds and may read: an input file, a put, or a file column read under its table's read action (or claimed by
106
+ * a job that holds it).
106
107
  */
107
108
  export interface StoredFilesHandle {
108
109
  /** A file of `kind` with these bytes, which must be of `type`; it is pending until a column references it. */
@@ -270,7 +270,7 @@ export class StoredFileKinds {
270
270
  if (holding === undefined || !holdsFile(work.holder, holding.id)) {
271
271
  throw new CapabilityRefusedError(
272
272
  'wrong_capability',
273
- `${where} takes a file reference this request holds and may read: an input file, a put, or a file column read under its table's read action`,
273
+ `${where} takes a file reference this request holds and may read: an input file, a put, or a file column read under its table's read action (or claimed by a job that holds it)`,
274
274
  )
275
275
  }
276
276
  const file = await this.#files.find(holding.id)
@@ -40,6 +40,7 @@ import { TokenVerifier } from '@fabrika/jwks'
40
40
  import type { FileObjectStore } from '@fabrika/platform'
41
41
  import { compileContract } from '../contract/compile'
42
42
  import { exportDescription } from '../contract/connect'
43
+ import { containersOf } from '../contract/containers'
43
44
  import { isProcedure, type ProcedureDeclaration, type ProcedureTreeDeclaration, SURFACE_SECTIONS } from '../contract/declaration'
44
45
  import { challengeRowId, exportBase, spaPrefixRowId } from '../contract/defaults'
45
46
  import type { AnyContract, Schema } from '../contract/define'
@@ -50,7 +51,7 @@ import { FILE_SWEEP_JOB, FILE_SWEEP_SCHEDULE, FILE_SWEEP_TIMEOUT_MS, storedFileK
50
51
  import { FILE_SCAN_JOB, FILE_SCAN_SCHEDULE, type FileScanner, SCAN_LIMITS } from '../files/scan'
51
52
  import { type MailStandIn, resolveMailTransports } from '../jobs/mail'
52
53
  import { logReporter, type OperationsReporter, operationsReporter, operationsSettings, type ReportSource } from '../jobs/report'
53
- import { bindJobs, type ContractJobs, type HandlerErrorSink } from '../jobs/runner'
54
+ import { bindJobs, type ContractJobs } from '../jobs/runner'
54
55
  import { environmentScrubber } from '../jobs/scrub'
55
56
  import { browserConfigs } from './browser-config'
56
57
  import { createCapabilityIssuer, requestIsReadOnly } from './capability'
@@ -66,9 +67,9 @@ import {
66
67
  type ServedSite,
67
68
  type SpaAssets,
68
69
  } from './dispatch'
69
- import { type HostResolver, installEgressGuard, platformCall, platformFacility, publicEgressRules, type SiteEgress, siteEgress } from './egress'
70
+ import { installEgressGuard, platformCall, platformFacility } from './egress'
70
71
  import type { CapturedEnvironment } from './environment'
71
- import { FailureReports } from './failures'
72
+ import { FailureReports, type HandlerErrorSink } from './failures'
72
73
  import { applicationPolicy } from './headers'
73
74
  import type { ContractDatabase, ContractImplementation, ImplementationDatabase } from './implement'
74
75
  import { approvedDeclaration, approvedReach, isSiteHandler, type SiteDeclaration } from './invocation'
@@ -130,11 +131,6 @@ export interface BootOptions {
130
131
  * with a job or a webhook does not boot.
131
132
  */
132
133
  readonly workloadTokens?: WorkloadTokenSource
133
- /**
134
- * Resolves a host name to its addresses, which the Bun adapter supplies (`node:dns`): a cron job's public egress then
135
- * refuses a public name of a private address before each hop. A Worker exposes no resolution and passes none.
136
- */
137
- readonly resolveHost?: HostResolver
138
134
  /** What posts a report to Operations' ingest; `fetch` by default. */
139
135
  readonly operationsFetch?: (request: Request) => Promise<Response>
140
136
  /** What asks a public procedure's challenge provider to verify a token; `fetch` by default. */
@@ -150,8 +146,10 @@ export interface BootOptions {
150
146
  */
151
147
  readonly challengeWork?: ChallengeWork
152
148
  /**
153
- * The developer's own machine only (`fabrika app dev`): what a job's handler threw, which every log of a deployed
154
- * application withholds because it may carry a credential.
149
+ * The author's own run only (`fabrika app dev`, a test that passes it to the kit): what a request's 5xx or a job
150
+ * attempt threw, whole, beside the code and reason its log line names: a handler's own error, or a framework failure
151
+ * (a refusal of the data layer or of a capability, a `ServerFault`) with its message. Every log of a deployed
152
+ * application withholds both, because either may carry request data or a credential (ADR-0059).
155
153
  */
156
154
  readonly revealHandlerErrors?: HandlerErrorSink
157
155
  /** The providers `FABRIKA_EMAIL_PROVIDER` may name for the jobs that declare `mailer: 'installation'`; the built-in ones by default. */
@@ -257,21 +255,6 @@ function checkContractDigest(framework: Readonly<Record<string, string>>, artifa
257
255
  }
258
256
  }
259
257
 
260
- /** Every dimension's containers, nearest first (`note → [workspace, organization]`); `buildArtifact` refuses a cycle. */
261
- function containersOf(artifact: ContractArtifact): ReadonlyMap<string, readonly string[]> {
262
- const containers = new Map<string, readonly string[]>()
263
- for (const dimension of Object.keys(artifact.dimensions)) {
264
- const chain: string[] = []
265
- let next = artifact.dimensions[dimension]?.in ?? null
266
- while (next !== null && !chain.includes(next)) {
267
- chain.push(next)
268
- next = artifact.dimensions[next]?.in ?? null
269
- }
270
- containers.set(dimension, chain)
271
- }
272
- return containers
273
- }
274
-
275
258
  /** The shortest secret accepted; Control generates 32 random bytes. */
276
259
  const MIN_PROXY_SECRET_LENGTH = 32
277
260
 
@@ -477,8 +460,8 @@ function boundHandler(
477
460
  }
478
461
 
479
462
  /** The origins a staged-kit site's handler reaches, a kit without tables included; nothing for a bare handler. */
480
- function egressOf(bound: BoundHandler): { readonly egress?: SiteEgress } {
481
- return !bound.site || bound.declaration === null ? {} : { egress: siteEgress(bound.declaration.egress, null) }
463
+ function egressOf(bound: BoundHandler): { readonly egress?: readonly string[] } {
464
+ return !bound.site || bound.declaration === null ? {} : { egress: bound.declaration.egress }
482
465
  }
483
466
 
484
467
  /** A staged-kit contract's endpoint gets `ctx.links` only for the link mount it declares it `issues`. */
@@ -737,7 +720,7 @@ function bootOnce(app: ContractImplementation, options: BootOptions, binding: Bi
737
720
  ? null
738
721
  : operationsReporter({ ...operations, source, scrubber, ...(options.operationsFetch === undefined ? {} : { fetch: options.operationsFetch }) })
739
722
  const owned = new Set(Object.values(artifact.tables).flatMap((table) => table.scope.mode === 'dimension' ? [table.scope.dimension] : []))
740
- const containers = containersOf(artifact)
723
+ const containers = containersOf(artifact.dimensions)
741
724
  unservable(artifact, options.assets, owned, containers, problems)
742
725
  sqliteProblems(artifact, options.database, problems)
743
726
  // This runtime's own: what another `boot` call mints, application code's included, its stores refuse.
@@ -916,7 +899,6 @@ function bootOnce(app: ContractImplementation, options: BootOptions, binding: Bi
916
899
  mail,
917
900
  tokens,
918
901
  url,
919
- publicEgress: publicEgressRules(options.environment.framework, options.resolveHost ?? null),
920
902
  }, problems)
921
903
  for (const id of jobs.declared) {
922
904
  declared.add(id)
@@ -999,7 +981,7 @@ function bootOnce(app: ContractImplementation, options: BootOptions, binding: Bi
999
981
  capabilities: issuer.authority,
1000
982
  data,
1001
983
  fileKinds,
1002
- failures: new FailureReports(reporterFor('fabrika.requests')),
984
+ failures: new FailureReports(reporterFor('fabrika.requests'), { reveal: options.revealHandlerErrors ?? null }),
1003
985
  kick: jobs.kick,
1004
986
  actions: Object.freeze(Object.keys(artifact.actions).sort()),
1005
987
  publicShare: new InFlightShare(publicShareOf(options.connections ?? DEFAULT_CONNECTIONS)),
@@ -34,9 +34,6 @@ export const CAPABILITY_REFUSALS = {
34
34
  undeclared_binding: 'the site named a webhook it does not declare in binds',
35
35
  undeclared_signs: 'the site signed a token of a purpose it does not declare in signs, or for longer than the purpose allows',
36
36
  undeclared_egress: 'the site called an origin it does not declare in egress',
37
- refused_egress:
38
- "the site's public egress refused the host: an IP address, a local or internal name, a non-default port, a host of this installation, or a name that resolves to a private address",
39
- oversized_egress: "a response to the site's public egress was larger than it reads",
40
37
  wrong_binding: 'a webhook binding was handed a capability of another kind or dimension than the webhook is bound to',
41
38
  missing_id: 'the job named an object without an id',
42
39
  wrong_capability: 'an operation was handed a capability of another dimension or action than it needs',
@@ -47,7 +44,7 @@ export type CapabilityRefusal = keyof typeof CAPABILITY_REFUSALS
47
44
  /** A capability that is forged, from a request that has ended, or from another request than the current one. */
48
45
  export class CapabilityRefusedError extends Error {
49
46
  override readonly name = 'CapabilityRefusedError'
50
- /** What a log may say; the message is for the author's own run. */
47
+ /** What a log may say; the message is for the author's own run (`revealHandlerErrors`). */
51
48
  readonly reason: CapabilityRefusal
52
49
 
53
50
  constructor(reason: CapabilityRefusal, message: string) {