@fabrika/app 0.9.0-dev.10 → 0.9.0-dev.12

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.
@@ -19,7 +19,7 @@ import {
19
19
  } from '@fabrika/auth-core'
20
20
  import type { Tables } from '@fabrika/db'
21
21
  import { tablePolicies } from '@fabrika/db/tables'
22
- import { type IsolationWorlds, type SampleValue, SEEDED_OBJECT_VERSION, type TestDatabase, type WorldRow } from '@fabrika/db/testing'
22
+ import { type IsolationWorlds, type SampleValue, type ScopeValues, SEEDED_OBJECT_VERSION, type TestDatabase } from '@fabrika/db/testing'
23
23
  import { MemoryFileObjects } from '@fabrika/platform/testing'
24
24
  import { readFile } from 'node:fs/promises'
25
25
  import { basename } from 'node:path'
@@ -34,6 +34,7 @@ import {
34
34
  GENERATED_INVITATION,
35
35
  GENERATED_LINK,
36
36
  GENERATED_MEMBER,
37
+ GENERATED_ROW_CAPABILITY,
37
38
  GENERATED_ROW_PREFIX,
38
39
  } from '../contract/defaults'
39
40
  import type { AnyContract } from '../contract/define'
@@ -150,18 +151,17 @@ type Refusals = 'declared' | 'none'
150
151
 
151
152
  /**
152
153
  * The pins of a case's endpoint (column → the own scope's value of a text column), and the removals of the case: rows
153
- * seeded with pins are removed once the case is over, so the next case can pin the same values under a unique index.
154
+ * seeded with pins or known scope values are removed once the case is over, so the next case can seed the same values
155
+ * under a unique index.
154
156
  */
155
157
  interface Pinning {
156
158
  readonly pins: Readonly<Record<string, string>>
157
159
  readonly removals: (() => Promise<void>)[]
158
160
  }
159
161
 
160
- const NO_PINNING: Pinning = { pins: {}, removals: [] }
161
-
162
- /** Seeded worlds, their removal taken by the case when they hold pinned values. */
163
- const pinned = <W extends { readonly remove: () => Promise<void> }>(worlds: W, pinning: Pinning): W => {
164
- if (Object.keys(pinning.pins).length > 0) pinning.removals.push(worlds.remove)
162
+ /** Seeded worlds, their removal taken by the case when they hold pinned values or known scope values. */
163
+ const pinned = <W extends { readonly remove: () => Promise<void> }>(worlds: W, pinning: Pinning, scopes: ScopeValues): W => {
164
+ if (Object.keys(pinning.pins).length > 0 || Object.keys(scopes).length > 0) pinning.removals.push(worlds.remove)
165
165
  return worlds
166
166
  }
167
167
 
@@ -203,11 +203,19 @@ interface Scopes {
203
203
  readonly other: Side & { readonly values: readonly string[] }
204
204
  }
205
205
 
206
- /** The input fields that name a row the kit seeds in the case's object (`rows`), with the row's table. */
207
- function rowFields(input: Readonly<Record<string, unknown>>): readonly { readonly field: string; readonly table: string }[] {
208
- return Object.entries(input).flatMap(([field, value]) =>
209
- typeof value === 'string' && value.startsWith(GENERATED_ROW_PREFIX) ? [{ field, table: value.slice(GENERATED_ROW_PREFIX.length) }] : []
210
- )
206
+ /**
207
+ * The input fields that name a row the kit seeds in the case's scopes (`rows`), with the row's table and, on an endpoint
208
+ * of several capabilities, the capability whose scope it lies in.
209
+ */
210
+ function rowFields(
211
+ input: Readonly<Record<string, unknown>>,
212
+ ): readonly { readonly field: string; readonly table: string; readonly capability: string | null }[] {
213
+ return Object.entries(input).flatMap(([field, value]) => {
214
+ if (typeof value !== 'string' || !value.startsWith(GENERATED_ROW_PREFIX)) return []
215
+ const named = value.slice(GENERATED_ROW_PREFIX.length)
216
+ const at = named.indexOf(GENERATED_ROW_CAPABILITY)
217
+ return [at === -1 ? { field, table: named, capability: null } : { field, table: named.slice(0, at), capability: named.slice(at + 1) }]
218
+ })
211
219
  }
212
220
 
213
221
  /** A case's input, and the values it named that only its own scope may see in an answer: a generated member's id and label. */
@@ -216,12 +224,16 @@ interface Addressed {
216
224
  readonly marks: readonly string[]
217
225
  }
218
226
 
219
- /** One target of an `in` report, with its chain from the target outward. */
227
+ /** One target of an `in` report, with its chain from the target outward, and the key of each row `rows` names in it. */
220
228
  interface InTarget {
221
229
  readonly target: string
222
230
  readonly chain: Chain
231
+ readonly rows: Readonly<Record<string, string>>
223
232
  }
224
233
 
234
+ /** An input field that names a row the kit seeds (`rows`), with the row's table. */
235
+ type RowField = ReturnType<typeof rowFields>[number]
236
+
225
237
  export type Grant =
226
238
  | { readonly action: string; readonly scope: { readonly type: string; readonly value: string } }
227
239
  | { readonly role: string; readonly scope: { readonly type: string; readonly value: string } }
@@ -252,6 +264,40 @@ function errorType(text: string): string | undefined {
252
264
  }
253
265
  }
254
266
 
267
+ /** The values a field admits when they are a fixed set: an enum, a string literal or a union of them; else `undefined`. */
268
+ function fixedValues(field: SchemaShape | undefined): readonly string[] | undefined {
269
+ switch (field?.type) {
270
+ case 'enum':
271
+ return field.values
272
+ case 'literal':
273
+ return typeof field.value === 'string' ? [field.value] : undefined
274
+ case 'union': {
275
+ const options = field.options.map(fixedValues)
276
+ return options.every((values) => values !== undefined) ? [...new Set(options.flat())] : undefined
277
+ }
278
+ default:
279
+ return undefined
280
+ }
281
+ }
282
+
283
+ /**
284
+ * The values of `dimension` a case's two scopes take when the input field it is read from admits a fixed set: its first
285
+ * two, which a stored row of the table that owns it may already hold. None otherwise, so each scope gets a fresh value.
286
+ */
287
+ function knownScopes(dimension: string, field: SchemaShape | undefined): ScopeValues {
288
+ const values = fixedValues(field)
289
+ if (values === undefined) return {}
290
+ const [own, other] = values
291
+ if (own === undefined || other === undefined) {
292
+ throw new Error(
293
+ `the input field a ${dimension} is read from admits only ${
294
+ values.map((value) => `'${value}'`).join(', ')
295
+ }, so no case can ask from two scopes of it; admit two values or more`,
296
+ )
297
+ }
298
+ return { [dimension]: { own, other } }
299
+ }
300
+
255
301
  /** A scope value no table holds, in the format of the input field it is sent in. */
256
302
  function freshValue(dimension: string, world: 'own' | 'other', field: SchemaShape | undefined): string {
257
303
  const format = field?.type === 'string' ? field.format : null
@@ -265,10 +311,23 @@ function fieldOf(input: SchemaShape | null, from: string | null): SchemaShape |
265
311
  return input?.type === 'object' && from !== null ? input.fields[from] : undefined
266
312
  }
267
313
 
268
- /** Every value of the other world a leak shows: its key, parent, every dimension value it lies in, and its markers. */
269
- function worldValues(worlds: IsolationWorlds, world: 'own' | 'other'): string[] {
314
+ /**
315
+ * Every value of the other world a leak shows: its key, parent, every dimension value it lies in, and its markers. A
316
+ * known scope value, and a text of a row the table already held, other rows may share, and a short word is part of
317
+ * unrelated text: each counts only as a whole JSON string (`"eu"`). A stored text the own row holds too is no leak.
318
+ */
319
+ function worldValues(worlds: IsolationWorlds, world: 'own' | 'other', scopes: ScopeValues): string[] {
270
320
  const row = worlds[world]
271
- return [...new Set([row.key, row.scope, ...(row.parent === null ? [] : [row.parent]), ...row.chain.map((link) => link.value), ...row.markers])]
321
+ const shared = new Set(world === 'other' ? worlds.own.stored : worlds.other.stored)
322
+ const values = [row.key, row.scope, ...(row.parent === null ? [] : [row.parent]), ...row.chain.map((link) => link.value), ...row.markers]
323
+ const stored = row.stored.filter((value) => !shared.has(value))
324
+ return [...new Set([...values.map((value) => shownValue(value, scopes)), ...stored.map((value) => JSON.stringify(value))])]
325
+ }
326
+
327
+ /** A value of a scope as a leak shows it: a known scope value as a whole JSON string, any other as it is. */
328
+ function shownValue(value: string, scopes: ScopeValues): string {
329
+ const known = Object.values(scopes).some((values) => values.own === value || values.other === value)
330
+ return known ? JSON.stringify(value) : value
272
331
  }
273
332
 
274
333
  /** The cases' scanner: a file it reads in full is clean, so a seeded upload of a `scan: true` collection is served. */
@@ -356,7 +415,8 @@ export function endpointAccessKit<DB, P>(
356
415
  challengeFetch: () => Promise.resolve(Response.json({ success: false, 'error-codes': ['invalid-input-response'] })),
357
416
  })
358
417
  const policies = tablePolicies(tables)
359
- const tableNames = Object.keys(policies).sort()
418
+ // A view's rows come from the tables it reads, which the kit seeds instead.
419
+ const tableNames = Object.keys(policies).filter((name) => policies[name]?.view !== true).sort()
360
420
 
361
421
  const ownerOf = (dimension: string): string | undefined =>
362
422
  tableNames.find((name) => {
@@ -584,39 +644,42 @@ export function endpointAccessKit<DB, P>(
584
644
  }
585
645
 
586
646
  /**
587
- * Two scopes of `dimension`: rows of the table that owns it when one does, with `seed`, otherwise two fresh scope
588
- * values. Each row `input` names in the object (`rows`) is seeded in each scope's row.
647
+ * Two scopes of `dimension`: rows of the table that owns it when one does, with `seed`, otherwise two scope values;
648
+ * each fresh, or the known values of a field that admits a fixed set (`knownScopes`). Each row `named` (`rows`) is
649
+ * seeded in each scope's object.
589
650
  */
590
651
  const scopesOf = async (
591
652
  action: string,
592
653
  dimension: string,
593
654
  field: SchemaShape | undefined,
594
655
  seed: Seed,
595
- input: Readonly<Record<string, unknown>>,
596
- pinning: Pinning = NO_PINNING,
656
+ named: readonly RowField[],
657
+ pinning: Pinning,
597
658
  ): Promise<Scopes> => {
598
- const named = rowFields(input)
599
659
  const owner = ownerOf(dimension)
600
660
  if (named.length > 0 && owner === undefined) {
601
661
  throw new Error(`no table owns ${dimension}, so the kit seeds no ${named.map((row) => row.table).join(', ')} row in one`)
602
662
  }
663
+ const scopes = knownScopes(dimension, field)
603
664
  if (owner === undefined) {
604
- const own = freshValue(dimension, 'own', field)
605
- const other = freshValue(dimension, 'other', field)
665
+ const own = scopes[dimension]?.own ?? freshValue(dimension, 'own', field)
666
+ const other = scopes[dimension]?.other ?? freshValue(dimension, 'other', field)
606
667
  return {
607
668
  own: { target: own, grants: [{ action, scope: { type: dimension, value: own } }], chain: [{ type: dimension, value: own }], rows: {} },
608
669
  other: {
609
670
  target: other,
610
671
  grants: [{ action, scope: { type: dimension, value: other } }],
611
- values: [other],
672
+ values: [shownValue(other, scopes)],
612
673
  chain: [{ type: dimension, value: other }],
613
674
  rows: {},
614
675
  },
615
676
  }
616
677
  }
617
- const worlds = pinned(await postgres.seedWorlds(tables, owner, seed, pinning.pins), pinning)
618
- const own = await rowsIn(worlds.own, named)
619
- const other = await rowsIn(worlds.other, named)
678
+ const worlds = pinned(await postgres.seedWorlds(tables, owner, seed, pinning.pins, scopes), pinning, scopes)
679
+ // A row under a stored scope value outlives the worlds' removal, so the case removes it itself.
680
+ const removals = Object.keys(scopes).length > 0 ? pinning.removals : []
681
+ const own = await rowsIn(worlds.own.chain, named, removals)
682
+ const other = await rowsIn(worlds.other.chain, named, removals)
620
683
  return {
621
684
  own: {
622
685
  target: worlds.own.key,
@@ -627,27 +690,34 @@ export function endpointAccessKit<DB, P>(
627
690
  other: {
628
691
  target: worlds.other.key,
629
692
  grants: [{ action, scope: { type: worlds.dimension, value: worlds.other.scope } }],
630
- values: [...worldValues(worlds, 'other'), ...other.values],
693
+ values: [...worldValues(worlds, 'other', scopes), ...other.values],
631
694
  chain: worlds.other.chain,
632
695
  rows: other.rows,
633
696
  },
634
697
  }
635
698
  }
636
699
 
637
- /** One row of each named table seeded in `object`: its key by input field, and every key and marker it holds. */
638
- const rowsIn = async (object: WorldRow, named: ReturnType<typeof rowFields>) => {
700
+ /**
701
+ * One row of each named table seeded in the object `chain` starts at: its key by input field, and every key and marker
702
+ * it holds. Each row's removal goes to `removals`.
703
+ */
704
+ const rowsIn = async (chain: Chain, named: readonly RowField[], removals: (() => Promise<void>)[]) => {
639
705
  const rows: Record<string, string> = {}
640
706
  const values: string[] = []
641
707
  for (const { field, table } of named) {
642
- const seeded = await postgres.seedUnder(tables, table, object)
708
+ const seeded = await postgres.seedUnder(tables, table, { chain })
709
+ removals.push(seeded.remove)
643
710
  rows[field] = seeded.key
644
711
  values.push(seeded.key, ...seeded.markers)
645
712
  }
646
713
  return { rows, values }
647
714
  }
648
715
 
649
- /** For a list of `dimension`: one row in each scope of every table listed by it; each caller holds every scope of its side. */
650
- const listScopesOf = async (action: string, dimension: string): Promise<Scopes> => {
716
+ /**
717
+ * For a list of `dimension`: one row in each scope of every table listed by it, and of each table `named` (`rows`),
718
+ * whose key goes in its field; each caller holds every scope of its side.
719
+ */
720
+ const listScopesOf = async (action: string, dimension: string, named: readonly RowField[], pinning: Pinning): Promise<Scopes> => {
651
721
  const own: Grant[] = []
652
722
  const other: Grant[] = []
653
723
  const values: string[] = []
@@ -656,42 +726,86 @@ export function endpointAccessKit<DB, P>(
656
726
  const worlds = await postgres.seedWorlds(tables, name)
657
727
  own.push({ action, scope: { type: dimension, value: worlds.own.scope } })
658
728
  other.push({ action, scope: { type: dimension, value: worlds.other.scope } })
659
- values.push(...worldValues(worlds, 'other'))
729
+ values.push(...worldValues(worlds, 'other', {}))
660
730
  }
661
731
  }
662
732
  if (own.length === 0) {
663
- return scopesOf(action, dimension, undefined, {}, {})
733
+ return scopesOf(action, dimension, undefined, {}, named, pinning)
734
+ }
735
+ const listed = await listedRows(action, dimension, named)
736
+ return {
737
+ own: { target: '', grants: [...own, ...listed.own.grants], chain: [], rows: listed.own.rows },
738
+ other: { target: '', grants: [...other, ...listed.other.grants], values: [...values, ...listed.values], chain: [], rows: listed.other.rows },
739
+ }
740
+ }
741
+
742
+ /**
743
+ * One row of each table `named` (`rows`) in each of two scopes of `dimension`, which lists it: the grants of `action`
744
+ * that reach it, its key by input field, and every value of the other scope's rows.
745
+ */
746
+ const listedRows = async (action: string, dimension: string, named: readonly RowField[]) => {
747
+ const ownGrants: Grant[] = []
748
+ const otherGrants: Grant[] = []
749
+ const ownRows: Record<string, string> = {}
750
+ const otherRows: Record<string, string> = {}
751
+ const values: string[] = []
752
+ for (const { field, table } of named) {
753
+ if (listDimensionOf(table) !== dimension) {
754
+ throw new Error(`a list of ${dimension} reaches no ${table} row, so the kit seeds none for ${field}`)
755
+ }
756
+ const worlds = await postgres.seedWorlds(tables, table)
757
+ ownGrants.push({ action, scope: { type: dimension, value: worlds.own.scope } })
758
+ otherGrants.push({ action, scope: { type: dimension, value: worlds.other.scope } })
759
+ ownRows[field] = worlds.own.key
760
+ otherRows[field] = worlds.other.key
761
+ values.push(...worldValues(worlds, 'other', {}))
664
762
  }
665
- return { own: { target: '', grants: own, chain: [], rows: {} }, other: { target: '', grants: other, values, chain: [], rows: {} } }
763
+ return { own: { grants: ownGrants, rows: ownRows }, other: { grants: otherGrants, rows: otherRows }, values }
666
764
  }
667
765
 
668
766
  /**
669
767
  * For a report `in` `dimension`: one row in each scope of every table that lies in it, the table that owns it with
670
768
  * `seed`. Each side's targets are its rows' values of `dimension`, and each caller holds all of them.
671
769
  */
672
- const inScopesOf = async (action: string, dimension: string, field: SchemaShape | undefined, seed: Seed, pinning: Pinning = NO_PINNING) => {
770
+ const inScopesOf = async (
771
+ action: string,
772
+ dimension: string,
773
+ field: SchemaShape | undefined,
774
+ seed: Seed,
775
+ named: readonly RowField[],
776
+ pinning: Pinning,
777
+ ) => {
673
778
  const own: InTarget[] = []
674
779
  const other: InTarget[] = []
675
780
  const values: string[] = []
676
- for (const name of tableNames) {
781
+ const scopes = knownScopes(dimension, field)
782
+ const unpinned = { pins: {}, removals: pinning.removals }
783
+ // The owner first: a row of a known value another table's seed inserted would pass for a stored one, which takes no seed.
784
+ const owner = ownerOf(dimension)
785
+ for (const name of [...(owner === undefined ? [] : [owner]), ...tableNames.filter((candidate) => candidate !== owner)]) {
677
786
  const mode = policies[name]?.scope.mode
678
787
  if (mode !== 'dimension' && mode !== 'child') continue
679
- const owned = name === ownerOf(dimension)
788
+ const owned = name === owner
680
789
  const worlds = owned
681
- ? pinned(await postgres.seedWorlds(tables, name, seed, pinning.pins), pinning)
682
- : await postgres.seedWorlds(tables, name)
790
+ ? pinned(await postgres.seedWorlds(tables, name, seed, pinning.pins, scopes), pinning, scopes)
791
+ : pinned(await postgres.seedWorlds(tables, name, {}, {}, scopes), unpinned, scopes)
683
792
  const ownAt = worlds.own.chain.findIndex((link) => link.type === dimension)
684
793
  const otherAt = worlds.other.chain.findIndex((link) => link.type === dimension)
685
794
  const ownValue = worlds.own.chain[ownAt]?.value
686
795
  const otherValue = worlds.other.chain[otherAt]?.value
687
796
  if (ownValue !== undefined && otherValue !== undefined) {
688
- own.push({ target: ownValue, chain: worlds.own.chain.slice(ownAt) })
689
- other.push({ target: otherValue, chain: worlds.other.chain.slice(otherAt) })
690
- values.push(...worldValues(worlds, 'other'))
797
+ const ownChain = worlds.own.chain.slice(ownAt)
798
+ const otherChain = worlds.other.chain.slice(otherAt)
799
+ const removals = Object.keys(scopes).length > 0 ? pinning.removals : []
800
+ const ownRows = await rowsIn(ownChain, named, removals)
801
+ const otherRows = await rowsIn(otherChain, named, removals)
802
+ own.push({ target: ownValue, chain: ownChain, rows: ownRows.rows })
803
+ other.push({ target: otherValue, chain: otherChain, rows: otherRows.rows })
804
+ values.push(...worldValues(worlds, 'other', scopes), ...otherRows.values)
691
805
  }
692
806
  }
693
807
  if (own.length === 0) {
694
- const scopes = await scopesOf(action, dimension, field, seed, {}, pinning)
808
+ const scopes = await scopesOf(action, dimension, field, seed, named, pinning)
695
809
  return { own: [scopes.own], other: [scopes.other], values: scopes.other.values }
696
810
  }
697
811
  return { own, other, values }
@@ -824,7 +938,7 @@ export function endpointAccessKit<DB, P>(
824
938
  if (owner === undefined) {
825
939
  throw new Error(`${row.id}: no table owns ${access.dimension}, so no link can be bound to one`)
826
940
  }
827
- const { own } = pinned(await postgres.seedWorlds(tables, owner, seed, pinning.pins), pinning)
941
+ const { own } = pinned(await postgres.seedWorlds(tables, owner, seed, pinning.pins), pinning, {})
828
942
  const holder = kit.testCaller([{ action: row.action, scope: { type: access.dimension, value: own.key } }], {
829
943
  kind: 'link',
830
944
  link: { mount, chain: own.chain },
@@ -834,7 +948,7 @@ export function endpointAccessKit<DB, P>(
834
948
  headers.set('Authorization', `Bearer ${holder.key ?? ''}`)
835
949
  return kit.fetch(request, { ...init, headers })
836
950
  }
837
- return { fetch, rows: (await rowsIn(own, rowFields(input))).rows }
951
+ return { fetch, rows: (await rowsIn(own.chain, rowFields(input), [])).rows }
838
952
  }
839
953
 
840
954
  // The cases of one call: `removals` takes the removal of the application rows it seeds, which `drained` runs once
@@ -843,6 +957,8 @@ export function endpointAccessKit<DB, P>(
843
957
  const accessKitOf = (removals: (() => Promise<void>)[]): EndpointAccessKit => {
844
958
  /** The pins of `endpoint`, whose seeded rows this call removes once it is over. */
845
959
  const pinningOf = (endpoint: string): Pinning => ({ pins: options.pins?.[endpoint] ?? {}, removals })
960
+ /** No pins, and the removals of this call: for a scope a case seeds beside its endpoint's own. */
961
+ const unpinned: Pinning = { pins: {}, removals }
846
962
 
847
963
  /** One row of each application table `appRows` names, for this call only. */
848
964
  const seedAppRows = async (appRows: AppRows): Promise<void> => {
@@ -857,7 +973,7 @@ export function endpointAccessKit<DB, P>(
857
973
  if (access.form !== 'on' && access.form !== 'in') {
858
974
  throw new Error(`${endpoint} has the access form ${access.form}; only on and in name an object or a scope value`)
859
975
  }
860
- const scopes = await scopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, input, pinningOf(endpoint))
976
+ const scopes = await scopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, rowFields(input), pinningOf(endpoint))
861
977
  const asked = addressing(input, access.from, scopes.other)
862
978
  const { status } = await ask(row, holding(row, input, scopes.own.grants, scopes.own.chain), asked, scopes.own.chain)
863
979
  return { status }
@@ -867,7 +983,7 @@ export function endpointAccessKit<DB, P>(
867
983
  const { action, access } = row
868
984
  if (access.form === 'in') {
869
985
  await seedAppRows(appRows)
870
- const scopes = await inScopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, pinningOf(endpoint))
986
+ const scopes = await inScopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, rowFields(input), pinningOf(endpoint))
871
987
  const grants = (targets: readonly InTarget[]): Grant[] =>
872
988
  targets.flatMap(({ target, chain }) => holding(row, input, [{ action, scope: { type: access.dimension, value: target } }], chain))
873
989
  const marks: string[] = []
@@ -886,8 +1002,8 @@ export function endpointAccessKit<DB, P>(
886
1002
  }
887
1003
  await seedAppRows(appRows)
888
1004
  const scopes = access.form === 'on'
889
- ? await scopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, input, pinningOf(endpoint))
890
- : await listScopesOf(action, access.dimension)
1005
+ ? await scopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, rowFields(input), pinningOf(endpoint))
1006
+ : await listScopesOf(action, access.dimension, rowFields(input), unpinned)
891
1007
  const from = access.form === 'on' ? access.from : null
892
1008
  // The other scope asks first, to fill whatever a handler keeps between requests; its pins differ from the own
893
1009
  // scope's, so a refusal the fixtures declare is its answer too. The own scope's answer is the one checked.
@@ -918,7 +1034,7 @@ export function endpointAccessKit<DB, P>(
918
1034
  const { status } = await askAs(row, holder.fetch, { ...input, ...holder.rows }, 'declared')
919
1035
  return { status }
920
1036
  }
921
- const scopes = await scopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, input, pinningOf(endpoint))
1037
+ const scopes = await scopesOf(action, access.dimension, fieldOf(row.input, access.from), seed, rowFields(input), pinningOf(endpoint))
922
1038
  const { status } = await ask(
923
1039
  row,
924
1040
  holding(row, input, scopes.own.grants, scopes.own.chain),
@@ -967,25 +1083,39 @@ export function endpointAccessKit<DB, P>(
967
1083
  `${endpoint}: capability '${capability}' has no denied case: '${ruledOutBy}' needs its action too, ${named.action}, in a related dimension, so every caller that passes it is answered the list`,
968
1084
  )
969
1085
  }
1086
+ const fields = rowFields(input)
1087
+ for (const { field, capability: placed } of fields) {
1088
+ if (placed === null || !capabilities.has(placed)) {
1089
+ throw new Error(`${endpoint}: ${field} names a row in the scope of no capability of it, so the kit does not know where to seed it`)
1090
+ }
1091
+ }
1092
+ const rowsOf = (name: string): RowField[] => fields.filter((field) => field.capability === name)
970
1093
  const grants: Grant[] = []
971
1094
  let asked = input
1095
+ // The named one first: a known value another one's seed inserted would pass for a stored row, which takes no seed.
1096
+ if (access.form === 'on' || access.form === 'in') {
1097
+ const scopes = await scopesOf(named.action, access.dimension, fieldOf(named.input, access.from), seed, rowsOf(capability), pinningOf(endpoint))
1098
+ asked = addressing(asked, access.from, scopes.other)
1099
+ grants.push(...scopes.own.grants)
1100
+ }
972
1101
  for (const [name, other] of capabilities) {
973
1102
  if (name === capability) continue
974
1103
  // Each other one in a scope of its own, apart from the named one's: a global grant would also meet the named
975
1104
  // capability when both share an action. An `over` one lists from any value it is held in, so a fresh uuid does,
976
- // a valid key whether the dimension's is text or uuid, and no row of it is seeded.
1105
+ // a valid key whether the dimension's is text or uuid; it also holds the scope of each row it names.
977
1106
  if (other.access.form === 'over') {
978
- grants.push({ action: other.action, scope: { type: other.access.dimension, value: crypto.randomUUID() } })
1107
+ const listed = await listedRows(other.action, other.access.dimension, rowsOf(name))
1108
+ grants.push({ action: other.action, scope: { type: other.access.dimension, value: crypto.randomUUID() } }, ...listed.own.grants)
1109
+ asked = { ...asked, ...listed.own.rows }
979
1110
  } else if (other.access.form === 'on' || other.access.form === 'in') {
980
- const { own } = await scopesOf(other.action, other.access.dimension, fieldOf(other.input, other.access.from), {}, input)
1111
+ const { own } = await scopesOf(other.action, other.access.dimension, fieldOf(other.input, other.access.from), {}, rowsOf(name), unpinned)
981
1112
  asked = addressing(asked, other.access.from, own)
982
1113
  grants.push(...own.grants)
983
1114
  }
984
1115
  }
985
- if (access.form === 'on' || access.form === 'in') {
986
- const scopes = await scopesOf(named.action, access.dimension, fieldOf(named.input, access.from), seed, input, pinningOf(endpoint))
987
- asked = addressing(asked, access.from, scopes.other)
988
- grants.push(...scopes.own.grants)
1116
+ if (access.form === 'over') {
1117
+ // The caller holds the named action nowhere it lists, so its rows lie in a scope of their own.
1118
+ asked = { ...asked, ...(await listedRows(named.action, access.dimension, rowsOf(capability))).other.rows }
989
1119
  }
990
1120
  const { status } = await askAs(named, callerFor(named, grants).fetch, asked)
991
1121
  return { status }
@@ -1,11 +1,13 @@
1
1
  // A small file the testing kits write: the leading bytes `files/sniff.ts` accepts for its type, then a text marker.
2
2
 
3
+ import { INLINE_DOCUMENT_TYPES } from '@fabrika/proxy-core/headers'
4
+
3
5
  const randomHex = (): string => crypto.randomUUID().replaceAll('-', '').slice(0, 8)
4
6
 
5
7
  const ascii = (text: string): number[] => [...text].map((char) => char.charCodeAt(0))
6
8
  const ZIP_HEAD = [0x50, 0x4b, 0x03, 0x04]
7
9
 
8
- /** The leading bytes `files/sniff.ts` accepts for each binary type it verifies; a text type needs none. */
10
+ /** The leading bytes `files/sniff.ts` accepts for each binary or XML type it verifies; another text type needs none. */
9
11
  const SAMPLE_HEADS: Readonly<Record<string, readonly number[]>> = {
10
12
  'image/png': [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a],
11
13
  'image/jpeg': [0xff, 0xd8, 0xff, 0xe0],
@@ -17,6 +19,7 @@ const SAMPLE_HEADS: Readonly<Record<string, readonly number[]>> = {
17
19
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ZIP_HEAD,
18
20
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ZIP_HEAD,
19
21
  'application/vnd.openxmlformats-officedocument.presentationml.presentation': ZIP_HEAD,
22
+ ...Object.fromEntries(INLINE_DOCUMENT_TYPES.map((type) => [type, ascii('<?xml version="1.0"?>\n')])),
20
23
  }
21
24
  const TEXT_TYPES: ReadonlySet<string> = new Set(['text/plain', 'text/csv', 'text/markdown', 'application/json', 'image/svg+xml'])
22
25
 
@@ -258,7 +258,7 @@ export interface WebhookMountDeclaration<S> extends OptionsRecord {
258
258
  readonly declared?: unknown;
259
259
  }
260
260
  /**
261
- * A file kind (`c.files({ types, maxBytes, scan? })`, no `owner`): a class of stored files a table's file column holds.
261
+ * A file kind (`c.files({ types, maxBytes, scan?, inline? })`, no `owner`): a class of stored files a table's file column holds.
262
262
  * It has no owner, no actions and no endpoint.
263
263
  */
264
264
  export interface FileKindDeclaration extends OptionsRecord {
@@ -267,6 +267,8 @@ export interface FileKindDeclaration extends OptionsRecord {
267
267
  readonly maxBytes: number;
268
268
  /** Every file waits `quarantined` until the scan gives it a clean verdict; a byte consumer answers 409 until then. */
269
269
  readonly scan?: boolean;
270
+ /** Its files are shown, not downloaded: only inert images and the XML documents a machine reads. */
271
+ readonly inline?: boolean;
270
272
  }
271
273
  export interface CronDeclaration extends OptionsRecord {
272
274
  readonly kind: 'cron';
@@ -207,10 +207,12 @@ export declare const GENERATED_INVITATION = "fabrika:invitation";
207
207
  export declare const GENERATED_LINK = "fabrika:link";
208
208
  /**
209
209
  * The prefix of the value a generated endpoint access case sends in an input field that names a row lying in its object
210
- * (`rows` of `endpoint-access.fixtures.ts`), followed by the row's table: `fabrika:row:note_comments`. The endpoint
211
- * access kit seeds one such row in each scope's object and sends that scope's key.
210
+ * or its list (`rows` of `endpoint-access.fixtures.ts`), followed by the row's table: `fabrika:row:note_comments`. The
211
+ * endpoint access kit seeds one such row in each scope and sends that scope's key.
212
212
  */
213
213
  export declare const GENERATED_ROW_PREFIX = "fabrika:row:";
214
+ /** What follows a row's table when the row lies in the scope of one capability of an endpoint of several: `@<name>`. */
215
+ export declare const GENERATED_ROW_CAPABILITY = "@";
214
216
  /**
215
217
  * The prefix of the value a generated endpoint access case sends in a file field, followed by the field's file kind:
216
218
  * `fabrika:file:attachments`. The endpoint access kit sends a small file of the kind's first type it can write in its place.
@@ -224,7 +224,7 @@ export interface WebhookMount<B extends string, Acts extends string, I extends S
224
224
  readonly actions: readonly Acts[];
225
225
  readonly input: I;
226
226
  }
227
- /** A file kind `c.files({ types, maxBytes, scan? })` declares: what a file column of that kind holds. */
227
+ /** A file kind `c.files({ types, maxBytes, scan?, inline? })` declares: what a file column of that kind holds. */
228
228
  export interface FileKind extends FileKindDeclaration {
229
229
  }
230
230
  export interface CronJob<Acts extends string> extends CronDeclaration {
@@ -331,6 +331,11 @@ export interface Kit<A extends string, D extends string, CD extends string> {
331
331
  readonly maxBytes: number;
332
332
  /** Each file is scanned for malware and served only after a clean verdict; until then it answers 409. */
333
333
  readonly scan?: boolean;
334
+ /**
335
+ * Each file is shown, not downloaded (`Content-Disposition: inline`): a feed or a sitemap a machine reads. Every
336
+ * type is an inert image or `application/xml`, `text/xml`, `application/rss+xml`, `application/atom+xml`.
337
+ */
338
+ readonly inline?: boolean;
334
339
  } & Owned<'kind'>): FileKind;
335
340
  /** A job of the whole application, holding `actions`; it runs on its schedule (UTC, five fields) and when kicked. */
336
341
  cron<const Acts extends readonly [A, ...A[]]>(schedule: string, options: {
@@ -70,8 +70,8 @@ export type SignsField<Sg, Purposes extends string> = {
70
70
  readonly signs: Sg & NoInfer<KnownPurposes<Sg, Purposes>>;
71
71
  });
72
72
  /**
73
- * The HTTPS origins a site's code calls (`fetch`): each an exact origin, no path or wildcard. A guard on the global
74
- * `fetch` refuses any other while the site runs; a public procedure declares none.
73
+ * The HTTPS origins a site's code calls (`fetch`): each an exact origin or `https://*.<domain>`, one label, no path. A
74
+ * guard on the global `fetch` refuses any other while the site runs; a public procedure declares none.
75
75
  */
76
76
  export interface EgressField {
77
77
  readonly egress?: readonly `https://${string}`[];
@@ -208,8 +208,10 @@ export interface Endpoint<T extends ProcedureType, I extends InputSchema | null,
208
208
  /**
209
209
  * An endpoint before `.handle`: a group refuses it. `Tk` are the kit's token purposes: a signed token field of the input
210
210
  * reaches the handler as the claims of its purpose.
211
+ * The parameters are declared invariant, stricter than their structure: measuring that variance through `ExactReturn`
212
+ * exceeds TypeScript 7's instantiation limit (TS2589), and the compiler does not check an `in out` annotation.
211
213
  */
212
- export interface EndpointBuilder<T extends ProcedureType, I extends InputSchema | null, O extends Schema, Acc, D, Ctx, X = unknown, Tk = Record<never, never>> extends PendingEndpoint {
214
+ export interface EndpointBuilder<in out T extends ProcedureType, in out I extends InputSchema | null, in out O extends Schema, in out Acc, in out D, in out Ctx, in out X = unknown, in out Tk = Record<never, never>> extends PendingEndpoint {
213
215
  /** The endpoint's handler, typed by its access form and declaration; it may return only the output's fields. */
214
216
  handle<const F extends KitHandler<WithClaims<HandlerInput<I, Acc>, Tk>, Ctx, HandlerReturn<F, O>, X>>(handler: F): ExactReturn<F, O, Endpoint<T, I, O, Acc, D>>;
215
217
  }
@@ -3,6 +3,7 @@ export { type Attachment, attachment, type AttachmentBrand, type AttachmentMark,
3
3
  export { buildArtifact } from './build';
4
4
  export { deniedCaseRuledOutBy } from './capability-cases';
5
5
  export { compileContract, describeContract } from './compile';
6
+ export type { ContractArtifact } from '@fabrika/auth-core';
6
7
  export { type ConnectSnapshot, describeSnapshot, exportDescription, exportDescriptionSchema, incompatibleChanges, incompatibleMountChanges, parseExportDescription, type SnapshotProcedure, } from './connect';
7
8
  export type * from './context';
8
9
  export * from './declaration';
@@ -1,3 +1,4 @@
1
+ import type { Scrubber } from '../jobs/scrub.js';
1
2
  import { type DevLogLine } from './wire.js';
2
3
  export type OutputStream = DevLogLine['stream'];
3
4
  export interface OutputSink {
@@ -6,23 +7,23 @@ export interface OutputSink {
6
7
  /** The launcher process's own stdout and stderr. */
7
8
  export declare const processOutput: OutputSink;
8
9
  /**
9
- * The newest `capacity` lines, numbered from 0 since the launcher started, with every known secret value replaced. A
10
- * mark starts the lines a report carries: those of the newest sync or reset, and the output after it.
10
+ * The newest `capacity` lines, numbered from 0 since the launcher started, each scrubbed of secrets once, as it arrives.
11
+ * A mark starts the lines a report carries: those of the newest sync or reset, and the output after it.
11
12
  */
12
13
  export declare class OutputRing {
13
14
  private readonly capacity;
14
- private readonly secrets;
15
+ private readonly scrubber;
15
16
  private readonly sink;
16
17
  private readonly lines;
17
18
  private next;
18
19
  private marked;
19
- constructor(capacity: number, secrets: readonly string[], sink: OutputSink);
20
- push(stream: OutputStream, text: string): void;
20
+ constructor(capacity: number, scrubber: Scrubber, sink: OutputSink);
21
+ /** Log and keep `text` scrubbed, and return the scrubbed line: a caller keeps that copy and never the raw one. */
22
+ push(stream: OutputStream, text: string): string;
21
23
  /** Report from the next line on: the lines before it belong to an older head. */
22
24
  mark(): void;
23
25
  /** The newest `count` lines since the mark, oldest first. */
24
26
  tail(count: number): DevLogLine[];
25
- private redact;
26
27
  }
27
28
  /** Feed `stream` to `onLine` one line at a time; a last line without a newline is fed when the stream ends. */
28
29
  export declare function readLines(stream: ReadableStream<Uint8Array>, onLine: (line: string) => void): Promise<void>;
@@ -12,7 +12,8 @@ export declare class FileDownload {
12
12
  readonly name: string | null;
13
13
  });
14
14
  }
15
- export declare function contentDisposition(contentType: string, name: string | null): string;
16
- export declare function fileResponse(file: FileDownload): Response;
15
+ /** `inline` is the row's `inlineFileTypes`. */
16
+ export declare function contentDisposition(contentType: string, name: string | null, inline?: readonly string[]): string;
17
+ export declare function fileResponse(file: FileDownload, inline: readonly string[]): Response;
17
18
  /** An error of a download endpoint, with the file treatment in place of the header policy. */
18
- export declare function withFileTreatment(response: Response): Response;
19
+ export declare function withFileTreatment(response: Response, inline: readonly string[]): Response;
@@ -1,8 +1,3 @@
1
- /**
2
- * The client a per-client limit counts: an IPv4 address, or an IPv6 address's /64 (one subscriber's prefix, of which
3
- * it may hold every address). Anything else, the header's absence included, is one shared `unknown` client.
4
- */
5
- export declare function clientKey(header: string | null): string;
6
1
  /**
7
2
  * The bucket of the client the proxy saw. Only `X-Fabrika-Client-Ip` is read: the proxy deletes it and sets it from
8
3
  * the connection on every request, and the proxy secret proves the request came through it. A forwarding header a