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

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 (46) hide show
  1. package/package.json +10 -10
  2. package/skill/SKILL.md +7 -5
  3. package/skill/references/app-setup.md +8 -8
  4. package/skill/references/endpoint.md +12 -4
  5. package/skill/references/files.md +11 -1
  6. package/skill/references/relations.md +558 -0
  7. package/skill/references/table-and-migration.md +30 -0
  8. package/src/contract/artifact-schema.ts +94 -5
  9. package/src/contract/build.ts +127 -34
  10. package/src/contract/compile.ts +1 -0
  11. package/src/contract/declaration.ts +8 -2
  12. package/src/contract/define.ts +18 -1
  13. package/src/contract/group.ts +12 -10
  14. package/src/contract/index.ts +2 -0
  15. package/src/contract/kit.ts +1 -0
  16. package/src/contract/platform.ts +1 -0
  17. package/src/contract/vocabulary.ts +3 -0
  18. package/src/dev/launcher.ts +14 -15
  19. package/src/dev/output.ts +8 -11
  20. package/src/files/kinds.ts +1 -1
  21. package/src/files/sniff.ts +18 -1
  22. package/src/files/treatment.ts +12 -10
  23. package/src/implement/boot.ts +33 -2
  24. package/src/implement/capability.ts +19 -4
  25. package/src/implement/client-address.ts +5 -71
  26. package/src/implement/dispatch.ts +117 -14
  27. package/src/implement/egress.ts +30 -12
  28. package/src/implement/implement.ts +7 -0
  29. package/src/implement/public.ts +3 -3
  30. package/src/jobs/report.ts +32 -5
  31. package/src/jobs/scrub.ts +1 -1
  32. package/src/testing/caller.ts +9 -2
  33. package/src/testing/endpoint-access.ts +2 -1
  34. package/src/testing/sample-file.ts +4 -1
  35. package/types/src/contract/declaration.d.ts +9 -1
  36. package/types/src/contract/define.d.ts +20 -1
  37. package/types/src/contract/group.d.ts +5 -3
  38. package/types/src/contract/index.d.ts +1 -0
  39. package/types/src/contract/vocabulary.d.ts +4 -1
  40. package/types/src/dev/output.d.ts +7 -6
  41. package/types/src/files/treatment.d.ts +4 -3
  42. package/types/src/implement/capability.d.ts +4 -4
  43. package/types/src/implement/client-address.d.ts +0 -5
  44. package/types/src/implement/dispatch.d.ts +11 -0
  45. package/types/src/implement/implement.d.ts +7 -0
  46. package/types/src/testing/caller.d.ts +1 -1
@@ -6,12 +6,15 @@ import {
6
6
  type ArrayShape,
7
7
  type AttachmentShape,
8
8
  BUILTIN_ROLE_KEYS,
9
+ type ColumnTestArtifact,
10
+ type ConditionArtifact,
9
11
  CONTRACT_FORMAT,
10
12
  type ContractArtifact,
11
13
  CROSS_ORIGIN_KINDS,
12
14
  displayNameProblem,
13
15
  type EndpointRow,
14
16
  FILE_RESPONSE_KINDS,
17
+ fileKindsIn,
15
18
  isOwnWorkloadName,
16
19
  JOB_MAILERS,
17
20
  LOCALES,
@@ -20,14 +23,16 @@ import {
20
23
  type MessageKind,
21
24
  type NumberShape,
22
25
  type OutputShape,
26
+ parseEgressEntry,
23
27
  type RecordShape,
28
+ type RowsTestArtifact,
24
29
  type SchemaShape,
25
30
  type StringShape,
26
31
  type TablePolicyArtifact,
27
32
  terminalIdentifyProblem,
28
33
  type TupleShape,
29
34
  } from '@fabrika/auth-core'
30
- import { isPolicyOrigin, WORKER_BLOB_SOURCE } from '@fabrika/proxy-core/headers'
35
+ import { inlineFileTypes, WORKER_BLOB_SOURCE } from '@fabrika/proxy-core/headers'
31
36
  import { z } from 'zod/v4'
32
37
  import {
33
38
  ALTCHA_LIMITS,
@@ -172,7 +177,7 @@ const rowBase = {
172
177
  admission: z.strictObject({ contentTypes: z.tuple([name], name), maxBytes: z.int().positive().nullable() }).nullable(),
173
178
  input: schemaShapeSchema.nullable(),
174
179
  output: outputShapeSchema.nullable(),
175
- response: z.literal('file').optional(),
180
+ response: z.enum(['file', 'inline-file']).optional(),
176
181
  }
177
182
 
178
183
  const endpointRow: z.ZodType<EndpointRow> = z.union([
@@ -228,7 +233,7 @@ const endpointRow: z.ZodType<EndpointRow> = z.union([
228
233
  }),
229
234
  ]).refine(
230
235
  // Only a procedure answers a stored file, and exactly when its output is one.
231
- (row) => (row.response === 'file') === (row.output?.type === 'file') && (row.response === undefined || FILE_RESPONSE_KINDS.includes(row.kind)),
236
+ (row) => (row.response !== undefined) === (row.output?.type === 'file') && (row.response === undefined || FILE_RESPONSE_KINDS.includes(row.kind)),
232
237
  'only a procedure whose output is a file answers a stored file',
233
238
  ).refine(
234
239
  // Only an RPC procedure, a public procedure and a form open to another origin, and only the anonymous two to any (ADR-0022).
@@ -301,6 +306,45 @@ const tableAction = z.union([
301
306
  z.array(action).min(2).refine((list) => new Set(list).size === list.length, 'a table operation names each action once'),
302
307
  ])
303
308
 
309
+ const literal = z.union([z.string(), z.number().finite(), z.boolean()])
310
+ const ordered = z.union([literal, z.strictObject({ now: z.literal(true) })])
311
+
312
+ /** Exactly one operator per column test, as the policy parse reads it. */
313
+ const columnTest: z.ZodType<ColumnTestArtifact> = z.strictObject({
314
+ eq: literal.optional(),
315
+ notEq: literal.optional(),
316
+ in: z.array(literal).nonempty().optional(),
317
+ notIn: z.array(literal).nonempty().optional(),
318
+ isNull: z.boolean().optional(),
319
+ lt: ordered.optional(),
320
+ lte: ordered.optional(),
321
+ gt: ordered.optional(),
322
+ gte: ordered.optional(),
323
+ }).refine((test) => Object.values(test).filter((value) => value !== undefined).length === 1, 'a column test states exactly one operator')
324
+
325
+ /** `some` or `none` of one table's rows: a condition of its own, or the test at the end of a path. */
326
+ const rowsTest: z.ZodType<RowsTestArtifact> = z.lazy(() =>
327
+ z.union([
328
+ z.strictObject({ some: z.record(name, condition).refine((rows) => Object.keys(rows).length === 1, 'some names exactly one table') }),
329
+ z.strictObject({ none: z.record(name, condition).refine((rows) => Object.keys(rows).length === 1, 'none names exactly one table') }),
330
+ ])
331
+ )
332
+
333
+ const condition: z.ZodType<ConditionArtifact> = z.lazy(() =>
334
+ z.union([
335
+ z.strictObject({ allOf: z.array(condition).nonempty() }),
336
+ z.strictObject({ anyOf: z.array(condition).nonempty() }),
337
+ z.strictObject({ not: condition }),
338
+ rowsTest,
339
+ z.record(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*){0,3}$/), z.union([columnTest, rowsTest])).refine(
340
+ (tests) =>
341
+ Object.keys(tests).length > 0 && !('allOf' in tests) && !('anyOf' in tests) && !('not' in tests) && !('some' in tests)
342
+ && !('none' in tests),
343
+ 'a condition tests at least one column',
344
+ ),
345
+ ])
346
+ )
347
+
304
348
  const tablePolicy: z.ZodType<TablePolicyArtifact> = z.strictObject({
305
349
  scope: z.discriminatedUnion('mode', [
306
350
  z.strictObject({
@@ -328,6 +372,27 @@ const tablePolicy: z.ZodType<TablePolicyArtifact> = z.strictObject({
328
372
  createdBy: nullableName,
329
373
  columns: record(z.strictObject({ read: action.optional(), write: action.optional() })),
330
374
  files: z.record(name, name).optional(),
375
+ view: z.literal(true).optional(),
376
+ confers: record(z.strictObject({
377
+ principal: name,
378
+ node: name,
379
+ expires: nullableName,
380
+ when: condition.optional(),
381
+ assign: z.strictObject({ maxDays: z.int().positive().nullable(), self: z.boolean() }).nullable(),
382
+ })).optional(),
383
+ when: z.record(action, condition).optional(),
384
+ reveals: record(z.strictObject({
385
+ to: name,
386
+ actions: z.array(action).nonempty(),
387
+ when: condition.optional(),
388
+ assign: z.strictObject({ self: z.boolean() }).optional(),
389
+ })).optional(),
390
+ readThrough: z.record(name, name).optional(),
391
+ memberReveals: record(z.strictObject({
392
+ to: name,
393
+ actions: z.array(action).nonempty(),
394
+ when: condition.optional(),
395
+ })).optional(),
331
396
  })
332
397
 
333
398
  export const contractArtifactSchema: z.ZodType<ContractArtifact> = z.strictObject({
@@ -346,11 +411,16 @@ export const contractArtifactSchema: z.ZodType<ContractArtifact> = z.strictObjec
346
411
  grants: actions,
347
412
  member: z.strictObject({ scope: name, assignableBy: z.array(roleKey) }).nullable(),
348
413
  external: z.literal(true).optional(),
414
+ via: record(actions.nonempty()).optional(),
349
415
  }).refine((role) => role.external !== true || role.member !== null, {
350
416
  path: ['external'],
351
417
  message: 'only a membership role admits external principals',
418
+ }).refine((role) => role.via === undefined || (role.member === null && role.external !== true), {
419
+ path: ['via'],
420
+ message: 'a relation holds actions through an application-wide role only, never a membership or external one',
352
421
  }),
353
422
  ),
423
+ relations: record(z.strictObject({ dimension: name })).optional(),
354
424
  mounts: record(mount),
355
425
  files: record(z.strictObject({
356
426
  owner: name,
@@ -363,7 +433,13 @@ export const contractArtifactSchema: z.ZodType<ContractArtifact> = z.strictObjec
363
433
  link: z.union([z.boolean(), z.array(name).nonempty()]),
364
434
  scan: z.literal(true).optional(),
365
435
  })),
366
- fileKinds: z.record(fileKindName, z.strictObject({ types: names, maxBytes: z.int().positive(), scan: z.literal(true).optional() })).optional(),
436
+ fileKinds: z.record(
437
+ fileKindName,
438
+ z.strictObject({ types: names, maxBytes: z.int().positive(), scan: z.literal(true).optional(), inline: z.literal(true).optional() }).refine(
439
+ (kind) => kind.inline === undefined || kind.types.every((type) => inlineFileTypes('inline-file').includes(type)),
440
+ 'an inline kind admits only inert images and XML documents',
441
+ ),
442
+ ).optional(),
367
443
  jobs: record(z.strictObject({
368
444
  schedule: name,
369
445
  actions,
@@ -417,7 +493,7 @@ export const contractArtifactSchema: z.ZodType<ContractArtifact> = z.strictObjec
417
493
  kicks: z.array(name).nonempty().optional(),
418
494
  binds: name.optional(),
419
495
  signs: z.array(name).nonempty().optional(),
420
- egress: z.array(z.string().refine((origin) => isPolicyOrigin(origin))).nonempty().optional(),
496
+ egress: z.array(z.string().refine((origin) => parseEgressEntry(origin).ok)).nonempty().optional(),
421
497
  })).superRefine((declared, context) => {
422
498
  for (const [site, reach] of Object.entries(declared)) {
423
499
  if (reach.actions !== undefined && !isOwnWorkloadName('public', site)) {
@@ -448,6 +524,19 @@ export const contractArtifactSchema: z.ZodType<ContractArtifact> = z.strictObjec
448
524
  tokens: record(z.strictObject({ claims: schemaShapeSchema, maxDays: z.int().positive().max(TOKEN_MAX_DAYS) })).optional(),
449
525
  }).superRefine((artifact, context) => {
450
526
  for (const row of artifact.endpoints) {
527
+ // A row answering a file of an inline kind shows it, every other row that answers a file downloads it.
528
+ if (row.output?.type === 'file' && (row.response === 'inline-file') !== (artifact.fileKinds?.[row.output.kind]?.inline === true)) {
529
+ context.addIssue({ code: 'custom', path: ['endpoints'], message: `'${row.id}' is inline-file exactly when its file kind is inline` })
530
+ }
531
+ // Only the application writes a file of an inline kind: an uploaded document could render as a page.
532
+ const inline = row.input === null ? undefined : fileKindsIn(row.input).find((kind) => artifact.fileKinds?.[kind]?.inline === true)
533
+ if (inline !== undefined) {
534
+ context.addIssue({
535
+ code: 'custom',
536
+ path: ['endpoints', artifact.endpoints.indexOf(row)],
537
+ message: `'${row.id}' takes a file of the inline kind '${inline}', which only the application writes`,
538
+ })
539
+ }
451
540
  if (row.kind === 'public' && row.source.kind !== 'challenge' && artifact.declared?.[row.id]?.actions === undefined) {
452
541
  context.addIssue({ code: 'custom', path: ['declared', row.id], message: 'a public procedure declares its workload actions' })
453
542
  }
@@ -29,6 +29,7 @@ import {
29
29
  type EndpointSource,
30
30
  type ExportArtifact,
31
31
  type FileKindArtifact,
32
+ fileKindsIn,
32
33
  type FileShape,
33
34
  FORM_URLENCODED_TYPE,
34
35
  type ImportArtifact,
@@ -49,6 +50,7 @@ import {
49
50
  type MessageKind,
50
51
  type MountArtifact,
51
52
  type OutputShape,
53
+ parseEgressEntry,
52
54
  planEndpoint,
53
55
  type ProcedureArtifact,
54
56
  type ProcedureChallenge,
@@ -62,7 +64,7 @@ import {
62
64
  type TokenPurposeArtifact,
63
65
  type WebhookScheme,
64
66
  } from '@fabrika/auth-core'
65
- import { isPolicyOrigin, MAX_CSP_ORIGINS, WORKER_BLOB_SOURCE } from '@fabrika/proxy-core/headers'
67
+ import { inlineFileTypes, isPolicyOrigin, MAX_CSP_ORIGINS, WORKER_BLOB_SOURCE } from '@fabrika/proxy-core/headers'
66
68
  import { z } from 'zod/v4'
67
69
  import { CONTRACT_APP_ID_PATTERN as APP_ID } from './app-id'
68
70
  import { contractArtifactSchema, RESERVED_FILE_KIND_PREFIX } from './artifact-schema'
@@ -84,6 +86,7 @@ import {
84
86
  type MountDeclaration,
85
87
  type ProcedureDeclaration,
86
88
  type ProcedureTreeDeclaration,
89
+ type RoleDeclaration,
87
90
  type SpaAccessDeclaration,
88
91
  } from './declaration'
89
92
  import {
@@ -147,7 +150,7 @@ const FRAMEWORK_TABLE_PREFIX = 'fabrika_'
147
150
  /** The most origins one site calls: a site that reaches more is an integration hub, which a connector import serves. */
148
151
  const MAX_EGRESS_ORIGINS = 16
149
152
  const DECLARED_ALLOWED =
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
+ "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>' | 'https://*.<domain>']"
151
154
  const CSP_FIELDS = ['connectSrc', 'imgSrc', 'frameAncestors', 'scriptSrc', 'frameSrc', 'styleSrc', 'fontSrc']
152
155
  /** An environment variable an application reads; a challenge names its secret by one. */
153
156
  const APPLICATION_VARIABLE = /^[A-Z][A-Z0-9_]*$/
@@ -205,6 +208,7 @@ class ArtifactBuilder {
205
208
  }
206
209
  const actions = this.#actions()
207
210
  const dimensions = this.#dimensions()
211
+ const relations = this.#relations()
208
212
  const roles = this.#roles()
209
213
  const tokens = this.#tokens()
210
214
  this.#fileKinds = this.#readFileKinds()
@@ -223,6 +227,15 @@ class ArtifactBuilder {
223
227
  if (row.kind === 'webhook' && row.input !== null && containsFile(row.input)) {
224
228
  this.#problem(`mount '${row.id}'`, "takes a file in its input, which only a procedure's top-level field does (file('<kind>'))")
225
229
  }
230
+ // Only the application writes a file of an inline kind: an uploaded document could render as a page.
231
+ for (const kind of new Set(row.input === null ? [] : fileKindsIn(row.input))) {
232
+ if (Object.hasOwn(this.#fileKinds, kind) && this.#fileKinds[kind]?.inline === true) {
233
+ this.#problem(
234
+ `procedure '${row.id}'`,
235
+ `takes a file of the inline kind '${kind}' in its input, which only the application writes: an uploaded document could render as a page (allowed: a kind without inline for an upload; ctx.files.put of a document the application renders)`,
236
+ )
237
+ }
238
+ }
226
239
  }
227
240
  const jobs = this.#jobs()
228
241
  const exports = this.#exports()
@@ -245,6 +258,7 @@ class ArtifactBuilder {
245
258
  dimensions,
246
259
  actions,
247
260
  roles,
261
+ ...(Object.keys(relations).length === 0 ? {} : { relations }),
248
262
  mounts,
249
263
  files: {},
250
264
  ...(Object.keys(this.#fileKinds).length === 0 ? {} : { fileKinds: this.#fileKinds }),
@@ -445,8 +459,8 @@ class ArtifactBuilder {
445
459
  if (BUILTIN_ROLE_KEYS.includes(name)) {
446
460
  this.#problem(where, `is a role IAM defines itself for every application (reserved: ${BUILTIN_ROLE_KEYS.join(', ')}); choose another name`)
447
461
  }
448
- if (role.grants.length === 0) {
449
- this.#problem(where, 'grants nothing (allowed: grants: [<exact actions>])')
462
+ if (role.grants.length === 0 && Object.keys(role.via ?? {}).length === 0) {
463
+ this.#problem(where, 'grants nothing (allowed: grants: [<exact actions>], or via: { <relation>: [<exact actions>] })')
450
464
  }
451
465
  this.#unique(where, 'grants', role.grants)
452
466
  for (const action of role.grants) {
@@ -473,15 +487,81 @@ class ArtifactBuilder {
473
487
  if (role.external === true && role.member === undefined) {
474
488
  this.#problem(where, 'is declared external and is not a membership role: only a role with member: { scope, … } may admit externals')
475
489
  }
490
+ const via = this.#via(where, role)
476
491
  roles[name] = {
477
492
  grants: [...role.grants],
478
493
  member: role.member === undefined ? null : { scope: role.member.scope, assignableBy: [...role.member.assignableBy] },
479
494
  ...(role.external === true ? { external: true } : {}),
495
+ ...(via === undefined ? {} : { via }),
480
496
  }
481
497
  }
482
498
  return roles
483
499
  }
484
500
 
501
+ /** Each relation names a dimension of the contract, and exactly one table's rows confer it. */
502
+ #relations(): Record<string, { readonly dimension: string }> {
503
+ const relations: Record<string, { readonly dimension: string }> = {}
504
+ for (const [name, relation] of Object.entries(this.#contract.relations ?? {})) {
505
+ const where = `relation '${name}'`
506
+ this.#name(where, name)
507
+ if (!Object.hasOwn(this.#contract.dimensions, relation.dimension)) {
508
+ this.#problem(where, `names the dimension '${relation.dimension}', which is not a dimension of the contract`)
509
+ }
510
+ const sources = Object.entries(this.#tables).filter(([, table]) => table.confers !== undefined && Object.hasOwn(table.confers, name))
511
+ if (sources.length !== 1) {
512
+ this.#problem(where, `is conferred by ${sources.length} tables; exactly one table declares confers.${name}`)
513
+ }
514
+ relations[name] = { dimension: relation.dimension }
515
+ }
516
+ for (const [table, policy] of Object.entries(this.#tables)) {
517
+ for (const relation of Object.keys(policy.confers ?? {})) {
518
+ if (!Object.hasOwn(relations, relation)) {
519
+ this.#problem(`table '${table}'`, `confers '${relation}', which is not a relation of the vocabulary`)
520
+ }
521
+ }
522
+ }
523
+ return relations
524
+ }
525
+
526
+ /**
527
+ * A role's `via`: known relations and actions, on an application-wide internal role only (ADR-0051 keeps an
528
+ * external principal to its membership roles), and never an action that inserts a relation's rows, so a relation
529
+ * never delegates itself onward.
530
+ */
531
+ #via(where: string, role: RoleDeclaration): Record<string, readonly string[]> | undefined {
532
+ if (role.via === undefined) {
533
+ return undefined
534
+ }
535
+ if (role.member !== undefined || role.external === true) {
536
+ this.#problem(where, 'holds actions via a relation and is a membership or external role: only an application-wide role declares via')
537
+ }
538
+ const relations = this.#contract.relations ?? {}
539
+ const assigning = new Set<string>()
540
+ for (const policy of Object.values(this.#tables)) {
541
+ if (policy.confers === undefined) continue
542
+ const insert = policy.actions.insert
543
+ for (const action of insert === null ? [] : typeof insert === 'string' ? [insert] : insert) assigning.add(action)
544
+ }
545
+ const via: Record<string, readonly string[]> = {}
546
+ for (const [relation, actions] of Object.entries(role.via)) {
547
+ if (!Object.hasOwn(relations, relation)) {
548
+ this.#problem(where, `holds actions via '${relation}', which is not a relation of the vocabulary`)
549
+ }
550
+ if (actions.length === 0) {
551
+ this.#problem(where, `holds nothing via '${relation}' (allowed: via: { ${relation}: [<exact actions>] })`)
552
+ }
553
+ this.#unique(where, `via.${relation}`, actions)
554
+ for (const action of actions) {
555
+ this.#knownAction(where, action)
556
+ if (assigning.has(action)) {
557
+ this.#problem(where, `holds '${action}' via '${relation}', which inserts a relation's rows: a relation never delegates itself onward`)
558
+ }
559
+ }
560
+ via[relation] = [...actions]
561
+ }
562
+ return via
563
+ }
564
+
485
565
  // ── Mounts ──────────────────────────────────────────────────────────────────────────────────
486
566
 
487
567
  #mount(name: string, mount: MountDeclaration<SchemaShape>): MountArtifact | null {
@@ -1456,7 +1536,15 @@ class ArtifactBuilder {
1456
1536
  if (row.output !== null && isSchemaOutput(row.output)) {
1457
1537
  this.#tokenFields(`${where} output`, row.output, false)
1458
1538
  }
1459
- this.#endpoints.push(row.output?.type === 'file' ? { ...row, response: 'file' } : row)
1539
+ // A file of an inline kind is shown (`inline-file`), any other downloaded; the proxy reads which from the row.
1540
+ this.#endpoints.push(
1541
+ row.output?.type === 'file'
1542
+ ? {
1543
+ ...row,
1544
+ response: Object.hasOwn(this.#fileKinds, row.output.kind) && this.#fileKinds[row.output.kind]?.inline === true ? 'inline-file' : 'file',
1545
+ }
1546
+ : row,
1547
+ )
1460
1548
  }
1461
1549
 
1462
1550
  /**
@@ -1679,8 +1767,8 @@ class ArtifactBuilder {
1679
1767
 
1680
1768
  // ── Sections ────────────────────────────────────────────────────────────────────────────────
1681
1769
 
1682
- /** The media types and the scan of a file kind: exact types, and a scan that can vouch for each file. */
1683
- #fileTypes(where: string, declared: Pick<FileKindDeclaration, 'types' | 'maxBytes' | 'scan'>): void {
1770
+ /** The media types, the scan and the inline serving of a file kind: exact types, a scan that can vouch for each file. */
1771
+ #fileTypes(where: string, declared: Pick<FileKindDeclaration, 'types' | 'maxBytes' | 'scan' | 'inline'>): void {
1684
1772
  this.#unique(where, 'types', declared.types)
1685
1773
  for (const type of declared.types) {
1686
1774
  if (!MIME_TYPE.test(type)) {
@@ -1693,6 +1781,18 @@ class ArtifactBuilder {
1693
1781
  if (declared.scan !== undefined && typeof declared.scan !== 'boolean') {
1694
1782
  this.#problem(where, 'scan is true or false')
1695
1783
  }
1784
+ if (declared.inline !== undefined && typeof declared.inline !== 'boolean') {
1785
+ this.#problem(where, 'inline is true or false')
1786
+ }
1787
+ const shown = inlineFileTypes('inline-file')
1788
+ for (const type of declared.inline === true ? declared.types.filter((candidate) => !shown.includes(candidate)) : []) {
1789
+ this.#problem(
1790
+ where,
1791
+ `is served inline and admits '${type}', which a browser could run or render as a page (allowed: ${
1792
+ shown.join(', ')
1793
+ }; or leave out inline, so each file is an attachment)`,
1794
+ )
1795
+ }
1696
1796
  for (const type of declared.scan === true ? declared.types.filter((candidate) => FILE_LIMITS.unscannedTypes.includes(candidate)) : []) {
1697
1797
  this.#problem(
1698
1798
  where,
@@ -1707,7 +1807,7 @@ class ArtifactBuilder {
1707
1807
  }
1708
1808
  }
1709
1809
 
1710
- /** The file kinds (`c.files({ types, maxBytes, scan? })`), before the mounts that name them. */
1810
+ /** The file kinds (`c.files({ types, maxBytes, scan?, inline? })`), before the mounts that name them. */
1711
1811
  #readFileKinds(): Record<string, FileKindArtifact> {
1712
1812
  const kinds: Record<string, FileKindArtifact> = {}
1713
1813
  for (const [name, declared] of Object.entries(this.#contract.files)) {
@@ -1735,7 +1835,12 @@ class ArtifactBuilder {
1735
1835
  )
1736
1836
  }
1737
1837
  this.#fileTypes(where, declared)
1738
- kinds[name] = { types: [...declared.types], maxBytes: declared.maxBytes, ...(declared.scan === true ? { scan: true } : {}) }
1838
+ kinds[name] = {
1839
+ types: [...declared.types],
1840
+ maxBytes: declared.maxBytes,
1841
+ ...(declared.scan === true ? { scan: true } : {}),
1842
+ ...(declared.inline === true ? { inline: true } : {}),
1843
+ }
1739
1844
  }
1740
1845
  return kinds
1741
1846
  }
@@ -2163,8 +2268,13 @@ class ArtifactBuilder {
2163
2268
  if (readOnly && mode === 'write') {
2164
2269
  this.#problem(where, `declares unscoped '${table}': 'write', and it runs read-only (allowed: 'read')`)
2165
2270
  }
2166
- const scope = Object.hasOwn(this.#tables, table) ? this.#tables[table]?.scope.mode : undefined
2167
- if (mode === 'write' && scope === 'reference') {
2271
+ const policy = Object.hasOwn(this.#tables, table) ? this.#tables[table] : undefined
2272
+ if (mode === 'write' && policy?.confers !== undefined) {
2273
+ this.#problem(where, `declares unscoped '${table}': 'write', and its rows confer a relation: write them through a capability`)
2274
+ }
2275
+ if (mode === 'write' && policy?.view === true) {
2276
+ this.#problem(where, `declares unscoped '${table}': 'write', and no site writes a view: its rows come from the tables it reads (allowed: 'read')`)
2277
+ } else if (mode === 'write' && policy?.scope.mode === 'reference') {
2168
2278
  this.#problem(
2169
2279
  where,
2170
2280
  `declares unscoped '${table}': 'write', and no site writes a reference table: its rows come from a migration (allowed: 'read')`,
@@ -2309,8 +2419,8 @@ class ArtifactBuilder {
2309
2419
 
2310
2420
  /**
2311
2421
  * The HTTPS origins a site's code calls: a credentialed procedure of an RPC mount, a webhook or a job, never a public,
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.
2422
+ * export or link procedure. Each is an exact origin or a one-label pattern (`parseEgressEntry`), once; `[]` when it
2423
+ * declares none or after a problem.
2314
2424
  */
2315
2425
  #egress(where: string, value: unknown, place: DeclaringSite): string[] {
2316
2426
  if (value === undefined) {
@@ -2336,8 +2446,9 @@ class ArtifactBuilder {
2336
2446
  this.#problem(where, `${origins.length} egress origins exceed the limit of ${MAX_EGRESS_ORIGINS}`)
2337
2447
  }
2338
2448
  for (const origin of origins) {
2339
- if (!isPolicyOrigin(origin)) {
2340
- this.#problem(where, `egress '${origin}' is not an https origin (allowed: 'https://api.example.com', no path or wildcard)`)
2449
+ const parsed = parseEgressEntry(origin)
2450
+ if (!parsed.ok) {
2451
+ this.#problem(where, `egress '${origin}' ${parsed.problem} (allowed: 'https://api.example.com' or 'https://*.example.com')`)
2341
2452
  }
2342
2453
  }
2343
2454
  this.#unique(where, 'egress', origins)
@@ -2638,25 +2749,7 @@ function fileField(shape: SchemaShape): { readonly kind: string; readonly count:
2638
2749
 
2639
2750
  /** Whether a schema holds a file anywhere. */
2640
2751
  export function containsFile(shape: SchemaShape): boolean {
2641
- switch (shape.type) {
2642
- case 'file':
2643
- return true
2644
- case 'array':
2645
- return containsFile(shape.items)
2646
- case 'tuple':
2647
- return shape.items.some(containsFile) || (shape.rest !== null && containsFile(shape.rest))
2648
- case 'record':
2649
- return containsFile(shape.value)
2650
- case 'object':
2651
- return Object.values(shape.fields).some(containsFile)
2652
- case 'optional':
2653
- case 'nullable':
2654
- return containsFile(shape.inner)
2655
- case 'union':
2656
- return shape.options.some(containsFile)
2657
- default:
2658
- return false
2659
- }
2752
+ return fileKindsIn(shape).length > 0
2660
2753
  }
2661
2754
 
2662
2755
  /** The file fields of an input, by name: the parts a multipart body carries beside its JSON. */
@@ -69,6 +69,7 @@ export function describeContract(contract: AnyContract): ContractDeclaration<Sch
69
69
  dimensions: vocabulary.dimensions,
70
70
  actions: vocabulary.actions,
71
71
  roles: vocabulary.roles,
72
+ ...(vocabulary.relations === undefined ? {} : { relations: vocabulary.relations }),
72
73
  mounts,
73
74
  files: surface.files ?? {},
74
75
  jobs: surface.jobs ?? {},
@@ -9,6 +9,8 @@ export interface ContractDeclaration<S> {
9
9
  readonly dimensions: Readonly<Record<string, DimensionDeclaration>>
10
10
  readonly actions: Readonly<Record<string, string>>
11
11
  readonly roles: Readonly<Record<string, RoleDeclaration>>
12
+ /** The vocabulary's relations, by name; absent without any. */
13
+ readonly relations?: Readonly<Record<string, { readonly dimension: string }>>
12
14
  readonly mounts: Readonly<Record<string, MountDeclaration<S>>>
13
15
  readonly files: Readonly<Record<string, FileKindDeclaration>>
14
16
  readonly jobs: Readonly<Record<string, CronDeclaration>>
@@ -56,7 +58,7 @@ export const BUILDER_FIELDS: Readonly<Record<Builder, BuilderFields>> = {
56
58
  link: { options: ['spa', 'dimension', 'grants', 'issuedBy', 'maxDays', 'procedures'], owned: ['kind', 'prefix'] },
57
59
  spa: { options: ['dir', 'access', 'browserConfig'], owned: ['kind', 'prefix'] },
58
60
  webhook: { options: ['scheme', 'boundTo', 'actions', 'input', 'limits'], owned: ['kind', 'path'] },
59
- fileKind: { options: ['types', 'maxBytes', 'scan'], owned: ['kind'] },
61
+ fileKind: { options: ['types', 'maxBytes', 'scan', 'inline'], owned: ['kind'] },
60
62
  cron: { options: ['actions', 'limits', 'retries'], owned: ['kind', 'schedule'] },
61
63
  export: { options: ['version', 'consumers', 'audience', 'procedures'], owned: ['kind'] },
62
64
  attachment: { options: ['format', 'filename', 'row', 'maxBytes', 'maxRows'], owned: [] },
@@ -134,6 +136,8 @@ export interface RoleDeclaration {
134
136
  readonly member?: { readonly scope: string; readonly assignableBy: readonly string[] }
135
137
  /** `true` only; `buildArtifact` refuses another value, and refuses it on a role without `member`. */
136
138
  readonly external?: boolean
139
+ /** Relation → the actions a global holder of the role holds where a row of the relation names them. */
140
+ readonly via?: Readonly<Record<string, readonly string[]>>
137
141
  }
138
142
 
139
143
  export type AccessDeclaration =
@@ -283,7 +287,7 @@ export interface WebhookMountDeclaration<S> extends OptionsRecord {
283
287
  }
284
288
 
285
289
  /**
286
- * A file kind (`c.files({ types, maxBytes, scan? })`, no `owner`): a class of stored files a table's file column holds.
290
+ * A file kind (`c.files({ types, maxBytes, scan?, inline? })`, no `owner`): a class of stored files a table's file column holds.
287
291
  * It has no owner, no actions and no endpoint.
288
292
  */
289
293
  export interface FileKindDeclaration extends OptionsRecord {
@@ -292,6 +296,8 @@ export interface FileKindDeclaration extends OptionsRecord {
292
296
  readonly maxBytes: number
293
297
  /** Every file waits `quarantined` until the scan gives it a clean verdict; a byte consumer answers 409 until then. */
294
298
  readonly scan?: boolean
299
+ /** Its files are shown, not downloaded: only inert images and the XML documents a machine reads. */
300
+ readonly inline?: boolean
295
301
  }
296
302
 
297
303
  export interface CronDeclaration extends OptionsRecord {
@@ -95,6 +95,16 @@ export interface RoleDef<A extends string, D extends string, R extends string> {
95
95
  * only internal people hold it. Only a role with `member` may declare it; an internal person may hold it too.
96
96
  */
97
97
  readonly external?: true
98
+ /**
99
+ * Relation → actions: a holder of this role, granted globally, holds them at each node a row of the relation's
100
+ * source names them at (`via: { owner: ['projects.edit'] }`). A scoped grant of the role carries none of them.
101
+ */
102
+ readonly via?: { readonly [relation: string]: readonly A[] }
103
+ }
104
+
105
+ /** A relation of the vocabulary: a table's rows name a principal at a node of `dimension` (`confers` on that table). */
106
+ export interface RelationDef<D extends string> {
107
+ readonly dimension: D
98
108
  }
99
109
 
100
110
  export interface Vocabulary<A extends string, D extends string, R extends string> extends Presentation, AppPeople<A>, AppTerminal {
@@ -102,6 +112,7 @@ export interface Vocabulary<A extends string, D extends string, R extends string
102
112
  readonly dimensions: { readonly [K in D]: DimensionDef<A, D, R> }
103
113
  readonly actions: { readonly [K in A]: string }
104
114
  readonly roles: { readonly [K in R]: RoleDef<A, D, R> }
115
+ readonly relations?: { readonly [name: string]: RelationDef<D> }
105
116
  }
106
117
 
107
118
  /** The actions that manage and list the application's own people. */
@@ -295,7 +306,7 @@ export interface WebhookMount<B extends string, Acts extends string, I extends S
295
306
  readonly input: I
296
307
  }
297
308
 
298
- /** A file kind `c.files({ types, maxBytes, scan? })` declares: what a file column of that kind holds. */
309
+ /** A file kind `c.files({ types, maxBytes, scan?, inline? })` declares: what a file column of that kind holds. */
299
310
  export interface FileKind extends FileKindDeclaration {}
300
311
 
301
312
  export interface CronJob<Acts extends string> extends CronDeclaration {
@@ -427,6 +438,11 @@ export interface Kit<A extends string, D extends string, CD extends string> {
427
438
  readonly maxBytes: number
428
439
  /** Each file is scanned for malware and served only after a clean verdict; until then it answers 409. */
429
440
  readonly scan?: boolean
441
+ /**
442
+ * Each file is shown, not downloaded (`Content-Disposition: inline`): a feed or a sitemap a machine reads. Every
443
+ * type is an inert image or `application/xml`, `text/xml`, `application/rss+xml`, `application/atom+xml`.
444
+ */
445
+ readonly inline?: boolean
430
446
  }
431
447
  & Owned<'kind'>,
432
448
  ): FileKind
@@ -528,6 +544,7 @@ export function surfaceKit<A extends string, D extends string, CD extends string
528
544
  types: kind.types,
529
545
  maxBytes: kind.maxBytes,
530
546
  scan: kind.scan,
547
+ inline: kind.inline,
531
548
  unknownOptions: unknownOptions(kind, 'fileKind'),
532
549
  }),
533
550
  cron: (schedule, options) => ({
@@ -111,8 +111,8 @@ export type SignsField<Sg, Purposes extends string> =
111
111
  & ([Sg] extends [never] ? unknown : { readonly signs: Sg & NoInfer<KnownPurposes<Sg, Purposes>> })
112
112
 
113
113
  /**
114
- * The HTTPS origins a site's code calls (`fetch`): each an exact origin, no path or wildcard. A guard on the global
115
- * `fetch` refuses any other while the site runs; a public procedure declares none.
114
+ * The HTTPS origins a site's code calls (`fetch`): each an exact origin or `https://*.<domain>`, one label, no path. A
115
+ * guard on the global `fetch` refuses any other while the site runs; a public procedure declares none.
116
116
  */
117
117
  export interface EgressField {
118
118
  readonly egress?: readonly `https://${string}`[]
@@ -291,16 +291,18 @@ export interface Endpoint<T extends ProcedureType, I extends InputSchema | null,
291
291
  /**
292
292
  * An endpoint before `.handle`: a group refuses it. `Tk` are the kit's token purposes: a signed token field of the input
293
293
  * reaches the handler as the claims of its purpose.
294
+ * The parameters are declared invariant, stricter than their structure: measuring that variance through `ExactReturn`
295
+ * exceeds TypeScript 7's instantiation limit (TS2589), and the compiler does not check an `in out` annotation.
294
296
  */
295
297
  export interface EndpointBuilder<
296
- T extends ProcedureType,
297
- I extends InputSchema | null,
298
- O extends Schema,
299
- Acc,
300
- D,
301
- Ctx,
302
- X = unknown,
303
- Tk = Record<never, never>,
298
+ in out T extends ProcedureType,
299
+ in out I extends InputSchema | null,
300
+ in out O extends Schema,
301
+ in out Acc,
302
+ in out D,
303
+ in out Ctx,
304
+ in out X = unknown,
305
+ in out Tk = Record<never, never>,
304
306
  > extends PendingEndpoint {
305
307
  /** The endpoint's handler, typed by its access form and declaration; it may return only the output's fields. */
306
308
  handle<const F extends KitHandler<WithClaims<HandlerInput<I, Acc>, Tk>, Ctx, HandlerReturn<F, O>, X>>(
@@ -14,6 +14,8 @@ export {
14
14
  export { buildArtifact } from './build'
15
15
  export { deniedCaseRuledOutBy } from './capability-cases'
16
16
  export { compileContract, describeContract } from './compile'
17
+ // The type compileContract answers, so an application's declaration can name it (TS2883 otherwise).
18
+ export type { ContractArtifact } from '@fabrika/auth-core'
17
19
  export {
18
20
  type ConnectSnapshot,
19
21
  describeSnapshot,
@@ -555,6 +555,7 @@ function runtimeApp(vocabulary: AnyAppVocabulary, options: KitOptions | undefine
555
555
  dimensions: vocabulary.dimensions,
556
556
  actions: vocabulary.actions,
557
557
  roles: vocabulary.roles,
558
+ ...(vocabulary.relations === undefined ? {} : { relations: vocabulary.relations }),
558
559
  ...presentationOf(vocabulary),
559
560
  ...peopleOf(vocabulary),
560
561
  ...terminalOf(vocabulary),
@@ -96,6 +96,7 @@ function roleDef(key: string, role: RoleArtifact): RoleDef {
96
96
  permissions: [...role.grants],
97
97
  ...(role.member === null ? {} : { member: { scope: role.member.scope, assignableBy: [...role.member.assignableBy] } }),
98
98
  ...(role.external === true ? { external: true } : {}),
99
+ ...(role.via === undefined ? {} : { via: Object.fromEntries(Object.entries(role.via).map(([relation, actions]) => [relation, [...actions]])) }),
99
100
  }
100
101
  }
101
102